轻松打破折叠的方式 [英] Easy way to break foldl
问题描述
L = [1,2,3,4,10,5,6,7],
Res =
try
列表: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} - >价值
end,
Res。
我知道这个例子是人造的,但有什么好的方法来打破折叠(我知道那个折总是扫描整个结构)?
请注意,即使我从折叠中断,我也需要检索正确的数据。在这种情况下,我应该从以前的迭代中获取数据(如我在示例中所做的那样)。
你做的正确,使用try / catch抛出非本地返回。如果函数从乐趣中看到返回值,以决定是否继续,那么它不会被折叠。
I need to break from foldl. Here is a dummy example how to break from fold when I count sum of values in a list and meet too big value (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 are there any nice method to break out fold (I know that fold always scan the whole structure)?
Please note, that i need to retrieve correct data even if i break from fold. In this case i should get data from previous iteration (as it done in my example).
You're doing it right, using a throw with try/catch for nonlocal return. If the function looked at the return value from the fun to decide whether or not to continue, it wouldn't be foldl anymore.
这篇关于轻松打破折叠的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!