Easy way to break foldl

久未见 提交于 2019-12-04 06:47:57

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.

Just curious, what is the point of using foldl here? If you need to break out, use recursion, foldl is not designed 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:

Another options is to use takewhile:

lists:foldl(fun(E, A) -> A + E end, 0, lists:takewhile(fun(E) -> E < 10 end, L))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!