[erlang-questions] Breaking out of a foldl

Mazen Harake <>
Sat May 30 18:19:03 CEST 2009


Because it is a hack?

a "fold_until" would be much smoother.

Consider this +1 to the set of people that wants this function in the 
lists module :)

/M

David Mercer wrote:
> 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.
>>     
>
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>   



More information about the erlang-questions mailing list