[英]How to iterate through all elements in a list with Erlang
I'm new to Erlang. 我是Erlang的新手。 All I want to do is take a list, loop through each element so I can send them to a function. 我想做的就是获取一个列表,循环遍历每个元素,这样我就可以将它们发送给一个函数。 Cannot find a clear example anywhere. 在任何地方都找不到明确的例子。
Example of what I want to do: 我想做的例子:
Mylist = [a,b,c,d,e,f,g]
for (i in Mylist) {
otherFunction(Mylist[i]);
}
Hope that help :) 希望有帮助:)
func([]) -> ok;
func([H|T]) ->
otherFunction(H),
func(T).
Or you can use list comprehension: 或者你可以使用列表理解:
[otherFunction(H) || H <- L].
You may use lists:foreach
您可以使用lists:foreach
L = [a,b,c,d,e,f,g],
Function = fun(Elem) -> atom_to_binary(Elem, utf8) end,
lists:foreach(Function, L).
Or if you need to receive some result from the function you may use lists:foldl
or lists:foldr
或者,如果您需要从函数中获得一些结果,您可以使用lists:foldl
或lists:foldr
L = [a,b,c,d,e,f,g],
F = fun(Elem, Acc) -> [atom_to_binary(Elem, utf8) | Acc] end,
lists:foldl(F, [], L).
Response will be 回应将是
[<<"g">>,<<"f">>,<<"e">>,<<"d">>,<<"c">>,<<"b">>,<<"a">>]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.