Search code examples
listerlangtranslate

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

  • 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))]).