Last Updated: February 25, 2016
· askoudros

here is how i do a foreach loop in erlang

T = lists:foldl(fun(L2, A2) -> 
        % 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.
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][]