# Breaking out of a foldl

mats cronqvist <>
Mon Jun 1 11:10:50 CEST 2009

```Mazen Harake <> writes:

> Because it is a hack?

It's most definitely not a "hack".

> a "fold_until" would be much smoother.

Yes, and a "fold_while", and of course a "fold_if" and trusty old
"fold_unless." Or am I being too subtle here?

Replacing a general mechanism, i.e. try-catch, with an infinitude of
special cases is just lame.

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