gpt4 book ai didi

erlang - 在 Erlang 中编写 for 循环

转载 作者:行者123 更新时间:2023-12-02 15:22:15 28 4
gpt4 key购买 nike

如何在 Erlang 中编写该方法

for_loop_with_index_and_value(F, L)

这类似于 Go 中的循环

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

我已阅读foreach loop with counter但我无法重写

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)

不起作用?

最佳答案

为什么不能使用lists: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.

map ,索引为:

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.

关于erlang - 在 Erlang 中编写 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16371089/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com