Easy way to break a crease

I need to exit foldl. Here is a dummy example of how to break from the fold when I am counting the sum of the values ​​in a list and encountering a value too large (i.e. 10)

L = [1,2,3,4,10,5,6,7], Res = try lists:foldl( fun(I, Value) -> if (I < 10) -> Value + I; true -> throw({too_big_value, Value}) end end, 0, L) catch throw:{too_big_value, Value} -> Value end, Res. 

I know this example is artificial, but is there any good way to break a crease (I know that creases always look through the whole structure)?

Please note that I need to get the correct data, even if I break. In this case, I should get the data from the previous iteration (as it was in my example).

+4
source share
2 answers

You do it right, using a throw with try / catch for a non-local return. If a function looked at the return value from fun to decide whether to continue or not, it would no longer add up.

+6
source

Just curious, what's the point of using foldl here? If you need to break free, use recursion, foldl not intended for it.

 main([]) -> L = [1,2,3,4,5,10,6,7], io:format("[~w]", [s(L, 0)]). s([], S) -> S; s([H|T], S) -> if (H < 10) -> s(T, S + H); true -> S end. 

Update:

Other parameters are takewhile :

 lists:foldl(fun(E, A) -> A + E end, 0, lists:takewhile(fun(E) -> E < 10 end, L)) 
+7
source

Source: https://habr.com/ru/post/912006/


All Articles