5
$\begingroup$

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
$\endgroup$

5 Answers 5

7
$\begingroup$

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.

$\endgroup$
7
$\begingroup$

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.

$\endgroup$
4
$\begingroup$
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}
$\endgroup$
4
$\begingroup$

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

 *) 
$\endgroup$
2
$\begingroup$
list = {1, 3, 5, 2, 7, 9, 11, 13, 15, 17, 19};

TakeWhile[list, EvenQ] == list

False

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

False

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.