Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop with counter

Tags:

erlang

I would like to add a counter in this loop in order to know the row of each element of the list. Do you have a simple solution?

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

like image 847
Bertaud Avatar asked Jan 23 '11 23:01

Bertaud


2 Answers

Use lists:foldl or write your own function:

lists:foldl(fun(E,Cnt) -> ..., Cnt+1 end, 0, Y),
like image 51
Lukas Avatar answered Sep 28 '22 06:09

Lukas


If you want to roll your own, this appear to work as required:

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 F will be called with two parameters - the individual entry from the list and its index.

like image 36
Alnitak Avatar answered Sep 28 '22 04:09

Alnitak