在Erlang中为循环写入

在Erlang中为循环写入,erlang,Erlang,如何用Erlang编写方法 for_loop_with_index_and_value(F, L) 哪一个是Go中环路的模拟 for index, value := range array { F(index, value) } 我读过 但我不能重写 lists:foldl(fun(E,Cnt) -> ..., Cnt+1 end, 0, Y) 这样F就不会返回下一个索引 好的,非常感谢大家。为什么 for_loop_with_index_and_value(fun(I, V

如何用Erlang编写方法

for_loop_with_index_and_value(F, L)
哪一个是Go中环路的模拟

for index, value := range array {
    F(index, value)
}
我读过 但我不能重写

lists:foldl(fun(E,Cnt) -> ..., Cnt+1 end, 0, Y)
这样F就不会返回下一个索引

好的,非常感谢大家。为什么

for_loop_with_index_and_value(fun(I, V) -> calc(I, V) end, L)
工作但是

for_loop_with_index_and_value(fun calc/2, L)

不起作用?

为什么不能使用
列表:foldl(fun(E,Cnt)->…,Cnt+1 end,0,Y)。
?是的,你可以:

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).
更一般的
foldl
索引:

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.
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.
map
带索引:

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.
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.

您可以编写一个递归函数,如下所示

* 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).
*I:索引
*N:最大值
*D:增量
-导出([start/0])。
当I==N->1时(I,N,u);
当I
io:fwrite(“~w~n,[I]),//函数体可以随心所欲!!!
对于(I+D,N,D)。
开始()->
对于(0,4,2)。
(I,N,u)的
中的第三个参数
“u”
表示D不重要,因此任何值都可以用作第三个参数。

似乎符合您的要求。