Using And

Discussion of Scheme and Racket

Using And

Postby dsjoka » Wed Mar 02, 2011 7:38 pm

Lets say we have:

((and (something1)(something2)(something3)(something4)) #t)

How does it compute it, does it test if all four are true or does it in pairs like:

((something1)and(something2)=true and((something3)and(something4)=true)) Then the whole thing is true???

Thanks.
dsjoka
 
Posts: 14
Joined: Thu Feb 10, 2011 1:30 pm

Re: Using And

Postby nuntius » Wed Mar 02, 2011 11:07 pm

From the R5RS standard, and is defined as

Code: Select all
-- library syntax: and <test1> ...,
     The <test> expressions are evaluated from left to right, and the
     value of the first expression that evaluates to a false value (see
     section *note Booleans::) is returned.  Any remaining expressions
     are not evaluated.  If all the expressions evaluate to true
     values, the value of the last expression is returned.  If there
     are no expressions then #t is returned.

     (and (= 2 2) (> 2 1))                  ==>  #t
     (and (= 2 2) (< 2 1))                  ==>  #f
     (and 1 2 'c '(f g))                    ==>  (f g)
     (and)                                  ==>  #t
User avatar
nuntius
 
Posts: 500
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: Using And

Postby saulgoode » Thu Mar 10, 2011 8:10 am

dsjoka wrote:Lets say we have:

((and (something1)(something2)(something3)(something4)) #t)

Your expression appears malformed and would generate an error (unless quoted); I am guessing you want something such as:
(and (something1)(something2)(something3)(something4) #t)

dsjoka wrote:How does it compute it, does it test if all four are true or does it in pairs like:

In Scheme, 'and' is a special form (not a function). It evaluates each of its arguments one at a time, stopping when that evaluation is false (subsequent arguments will not be evaluated). If the end of all arguments is reached without any falses, the value of the last argument is returned.

(and w x y z)
is equivalent to
(if w (if x (if y z)))

Note that since 'and' is not a function, you can not use it with either 'map' or 'apply'.
saulgoode
 
Posts: 45
Joined: Tue Dec 14, 2010 1:39 am


Return to Scheme

Who is online

Users browsing this forum: No registered users and 1 guest