Foreach loop with counter

后端 未结 2 966
遥遥无期
遥遥无期 2020-12-19 11:59

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

2条回答
  •  太阳男子
    2020-12-19 12:48

    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.

提交回复
热议问题