Re: "short circuiting" And and Or

*To*: mathgroup at smc.vnet.net*Subject*: [mg70594] Re: "short circuiting" And and Or*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Sat, 21 Oct 2006 05:13:24 -0400 (EDT)*Organization*: The Open University, Milton Keynes, UK*References*: <eha5b7$b5b$1@smc.vnet.net>

Szabolcs Horvat wrote: > I'd like to write a function that tests whether there are any elements > in a list that violate a certain condition. I could simply use > And@@condition/@list, but for reasons of efficiency I'd like to stop > the testing as soon as a "False" value is found. Is there any elegant > way of doing this without writing an explicit While loop? > > Szabolcs HorvÃ¡t > Say we have some lists of integers and we want to check that the lists contain only positive integers less or equal to ten. We can use the built-in function Select with the logical tests written as an anonymous function. Also, we set the last parameter of Select to one in order to stop searching the list at the first occurrence where the conditions do not hold. If the list returned by Select is empty, we conclude that the conditions hold for every elements of the original list. In[1]:= list1={5,2,-3,0,2,7,10,3,3,2,3,6,10,8,8,7,9,4,8,3}; list2={5,2,3,1,2,7,10,3,3,2,3,6,10,8,8,7,9,4,8,3}; violateConditionsQ[data_List,cond_]:= If[Length[Select[data,cond,1]]>0,True,False] In[4]:= violateConditionsQ[list1,(#<=0||#>10)&] Out[4]= True In[5]:= violateConditionsQ[list2,(#<=0||#>10)&] Out[5]= False Regards, Jean-Marc