Last Updated: February 25, 2016
·
4.637K
· askoudros

here is how i do a foreach loop in erlang

R=[{},{},{},{}],
T = lists:foldl(fun(L2, A2) -> 
       FS=L2,
        % do my logic on each item in the list here, 
        % the line below appends the result of all the  
        % work we do here to the accumulator A2.
    lists:append([A2,[FS]])
end, [], R),

The key to the above is the 'A2' accumulator which stores the result of each loop in a list.

This is useful when you need to take a list work on it to create a new list. Especially when working with libraries like mochiweb, webmachine where the output might be in json.

You could use the structure above to generate a mochijson2 friendly list from a regular erlang list.

[lists:foldl/3 man page][http://www.erlang.org/doc/man/lists.html#foldl-3]