[erlang-questions] Breaking out of a foldl

David Mercer <>
Fri May 29 18:51:21 CEST 2009


Why not use throw and catch?  E.g.:

  1> SumOr10 = fun(X, Y) when X + Y >= 10 -> throw(10); (X, Y) -> X + Y end.
  #Fun<erl_eval.12.113037538>
  2> catch lists:foldl(SumOr10, 0, [1,2,3]).
  6
  3> catch lists:foldl(SumOr10, 0, [1,2,3,4]).
  10
  4> catch lists:foldl(SumOr10, 0, [1,2,3,4,5]).
  10

> -----Original Message-----
> From:  [mailto:] On
> Behalf Of Juan Jose Comellas
> Sent: Friday, May 29, 2009 11:16 AM
> To: Erlang Questions
> Subject: [erlang-questions] Breaking out of a foldl
> 
> Several times I've come across the need of a variant of foldl/foldr where
> I
> can break out of the iteration before going over allthe elements of a
> list.
> Has anybody thought of adding a function like the one below to the lists
> module?
> 
> bfoldl(Fun, Acc0, [Head | Tail]) ->
>     case Fun(Head, Acc0) of
>         {ok, Acc} ->
>             bfoldl(Fun, Acc, Tail);
>         {break, _Acc} = Result ->
>             Result;
>         break ->
>             {break, Acc0}
>     end;
> bfoldl(_Fun, Acc0, []) ->
>     {ok, Acc0}.
> 
> Where a function can return {ok, Acc} to continue iterating and break /
> {break, Acc} to interrupt it.



More information about the erlang-questions mailing list