# How to stop mapping on true results for large lists?

Assuming I have a long list (real data with more than 100k elements). I have a function that I want to apply to the list, for example, EvenQ. I want the mapping to stop once the result for one element returns True and the code should return True to minimize computation. If no True is encountered while mapping all elements, then the code should return False. How can I achieve this? The list and the function EvenQ are used here for illustration purposes.

list = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};
EvenQ/@list


The AllTrue function will short circuit.

AllTrue[list, EvenQ]


But I may have misunderstood, because you said you want short-circuiting on True, so maybe you want

AllTrue[list, Not@*EvenQ]


which is baically equivalent to

AllTrue[list, OddQ]


Anyway, you can craft whatever specific function you need.

You can use AnyTrue. AnyTrue short-circuits on first True result and returns True in that case.

With

list = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};


then

AnyTrue[list, EvenQ]

True


Hope this helps.

alist = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};
blist = {1, 3, 5, 7};

f = FirstPosition[#, _?EvenQ, False] /. {_} :> True &;

f /@ {alist, blist}


Result:

{True, False}


Unlike the case with Map, Throw may be used to exit from Scan

Maybe

list = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};

Catch[{Scan[If[EvenQ[#], Throw[True]] &, list], Throw[False]}]

Catch[{Scan[If[EvenQ[#], Throw[True]] &, DeleteCases[list, 2]], Throw[False]}]

(*

True
False

*)

list = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};

TakeWhile[list, EvenQ] == list


False

LengthWhile[list, EvenQ] == Length[list]


False