Tommy
Tommy

Reputation: 13652

Foldl for truth with short circuiting

I want to know if f(X) is true for all X in some very large list L. Right now I have:

lists:foldl(fun(X, Last) -> f(X) andalso Last end, true, L)

The problem is I don't think this short circuits. Even if it is false for the first element in L it continues on always andalsoing with false.

Is there a flag to foldl such that this will short circuit or another function I can use?

I now see there is a function called all but it doesn't say whether it short circuits either.

Upvotes: 0

Views: 174

Answers (1)

Dogbert
Dogbert

Reputation: 222198

lists:foldl/3 does not have any way to stop the fold and return a value immediately. You can use lists:all/2 for this, which will stop processing the rest of the list if the function passed returns false for any item of the list:

lists:all(fun(X) -> f(X) end, L)

% or

lists:all(fun f/1, L)

Upvotes: 5

Related Questions