Write for-loop in Erlang

How to write a method in Erlang

for_loop_with_index_and_value(F, L) 

which is analogous to the loop in Go

 for index, value := range array { F(index, value) } 

I read the foreach loop with a counter but I cannot rewrite

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

so that F does not return the next index.

Ok, thank you all. Why

 for_loop_with_index_and_value(fun(I, V) -> calc(I, V) end, L) 

works but

 for_loop_with_index_and_value(fun calc/2, L) 

does not work?

+4
source share
2 answers

Why can't you use lists:foldl(fun(E,Cnt) -> ..., Cnt+1 end, 0, Y). ? Yes, you can:

 for_loop_with_index_and_value(F, L) when is_function(F, 2), is_list(L) -> lists:foldl(fun(E, I) -> F(I, E), I+1 end, 0, L). 

Overall foldl with index:

 foldli(F, L, Acc0) when is_function(F, 3), is_list(L) -> {_, Result} = lists:foldl(fun(E, {I, Acc}) -> {I+1, F(I, E, Acc)} end, {0, Acc0}, L), Result. 

map with index:

 mapi(F, L) when is_function(F, 2), is_list(L) -> {Result, _} = lists:mapfoldl(fun(E, I) -> {F(I, E), I+1} end, 0, L), Result. 
+3
source

You can write a recursive function as shown below.

 * I: index * N: max_value * D: increment -export([start/0]). for(I, N, _) when I == N -> 1; for(I, N, D) when I < N -> io:fwrite("~w~n", [I]), //function body do what ever you want!!! for(I+D, N, D). start() -> for(0, 4, 2). 

The 3rd parameter "_" in for(I, N, _) means that D does not matter, so any value can be used as the third parameter.

+1
source

Source: https://habr.com/ru/post/1479098/


All Articles