Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

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


  • Prev by Date: Re: Programming style: postfix/prefix vs. functional
  • Next by Date: Re: Re: Subscript vs SubscriptBox
  • Previous by thread: Re: Re: "short circuiting" And and Or
  • Next by thread: Re: "short circuiting" And and Or