我有一个Erlang元素列表,并且我正在使用lists:foreach遍历列表中的元素。是否有一种方法可以在遍历过程中退出这个“foreach循环”。例如:假设如果我在列表[2, 4, 5, 1, 2, 5]中遇到了'1',那么我想停止遍历该列表。我该怎么做?
另一种方法是使用 throw
和 catch
:
catch lists:foreach(
fun(1) ->
throw(found_one);
(X) ->
io:format("~p~n", [X])
end,
[2, 4, 5, 1, 2, 5]).
2
4
5
found_one
编辑: 受欢迎需求的影响,这里提供一个更精确的版本,只捕获您想要捕获的内容:
try lists:foreach(
fun(1) ->
throw(found_one);
(X) ->
io:format("~p~n", [X])
end,
[2, 4, 5, 1, 2, 5])
catch
throw:found_one ->
found_one
end.
traverse(Liste) ->
traverse(Liste, []).
traverse([], Acc) ->
Acc;
traverse([1|_], Acc) ->
Acc;
traverse([H|T], Acc) ->
% do something useful here maybe?
traverse(T, Acc).
在lists模块中有许多很好的函数:
lists:foreach(fun(E) -> do_something(E) end,
lists:takewhile(fun(E) -> E =/= 1 end, List)).
lists:takewhile(fun(1) -> false;
(E) -> do_something(E), true
end, List)
列表:全部?
do_something(A) ->
case A of
1 ->
false;
_ ->
true
end.
IsCompleted = lists:all(do_something(A), [2, 4, 5, 1, 2, 5]),
我遇到了同样的问题,并通过以下方式解决:
-module(foreach_until).
-export([foreach_until/3]).
foreach_until(Action, L, Judge) ->
lists:reverse(foreach_until(Action, L, Judge, []))
.
foreach_until(_, [], _, Result) ->
Result
;
foreach_until(Action, [H | T], Judge, Result) ->
case Judge(H) of
true -> Result;
false -> foreach_until(Action, T, Judge, [Action(H) | Result])
end
.
下面是一个解释如何使用的示例:
60> foreach_until:foreach_until(fun(X) -> X*X end, [1,2,3,4], fun(X)-> X >= 3 end).
[1,4]
throw
本身并不是一个异常。它确实应该用于流程控制。请参考 Erlang 的参考指南。 - gleber