'How to write these nested for-loops in Erlang
I want to implement this psuedo code in Erlang:
function()
B[1] <-- 1
for m <-- 2 to 21 do
B[m] <-- 0
for k <-- 1 to m - 1 do
B[m] <-- B[m] − 9 * B[k]
B[m] <-- B[m]/m
return B
My first thought was to do something with a list comprehension, something like
[...|| M <- lists:seq(2,21), K <- lists:seq(1,M-1)] in order to try to "translate" the nested for-loops somehow, but now I'm stuck and I don't know how to continue.
I'd really appreciate some help on how to write this code in Erlang, I feel a bit lost.
Thanks in advance!
Solution 1:[1]
The code may be like as follows:
test_loop2()->
M = lists:seq(2,21),
Dict = dict:new(),
Dict_a = dict:store(1,1,Dict),
Dict_b = lists:foldl(fun(X,Acc_x)->
io:format("x:~p~n",[X]),
Value = lists:foldl(fun(A,Acc_a)->
Acc_a - 9*A
end,0,lists:seq(1,X-1)),
dict:store(X,Value,Acc_x)
end,Dict_a,M),
io:format("~p",[lists:sort(dict:to_list(Dict_b))]).
Solution 2:[2]
In erlang, a for-loop is written like this:
loop(StopIndex, StopIndex) -> ok;
loop(CurrentIndex, StopIndex) ->
%% do stuff
loop(CurrentIndex+1, StopIndex).
Nested loops look like this:
outer_loop(StopIndex, StopIndex) -> ok;
outer_loop(Index, StopIndex) ->
io:format("---->outer_loop index: ~w~n", [Index]),
inner_loop(1, Index-1),
outer_loop(Index+1, StopIndex).
inner_loop(StopIndex, StopIndex) ->
io:format("inner_loop index: ~w~n", [StopIndex]);
inner_loop(Index, StopIndex) ->
io:format("inner_loop index: ~w~n", [Index]),
inner_loop(Index+1, StopIndex).
In the shell:
12> a:outer_loop(2, 7).
---->outer_loop index: 2
inner_loop index: 1
---->outer_loop index: 3
inner_loop index: 1
inner_loop index: 2
---->outer_loop index: 4
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
---->outer_loop index: 5
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
inner_loop index: 4
---->outer_loop index: 6
inner_loop index: 1
inner_loop index: 2
inner_loop index: 3
inner_loop index: 4
inner_loop index: 5
ok
If you need to manipulate some data in the loops, then you can add other parameter variables to the function definitions to hold the data. For instance, in your example the inner loop would need a variable to store the data structure B.
Lastly, you should be aware that lists suck at random access, e.g. B[m], so consider using the array module.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chen Yu |
| Solution 2 |
