Foreach loop with counter

I would like to add a counter to this loop to find out the line of each list item. Do you have a simple solution?

lists:foreach(fun(X) .... end,Y),

+5
source share
2 answers

Use lists: foldl or write your own function:

lists:foldl(fun(E,Cnt) -> ..., Cnt+1 end, 0, Y),
+10
source

If you want to collapse yourself, this seems to work as needed:

foreach_index(F, [H|T]) ->
    foreach_index(F, [H|T], 0).

foreach_index(F, [H|T], N) ->
    F(H, N),
    foreach_index(F, T, N + 1);

foreach_index(F, [], N) when is_function(F, 2) -> ok.

The function Fwill be called with two parameters - a separate entry from the list and its index.

+2
source

All Articles