In Scheme, does `or` and `and` short circuit?

484 views Asked by At

Do and and or short circuit in Scheme?

The following are two implementation of lat? (list of atoms). One uses condelse and the other uses or and and. I was wondering if they are equivalent and the answer to that hinges on whether or and and have short circuit evaluation in Scheme.

(define lat?
  (lambda (l)
    (cond
         ((null? l) #t)
         ((atom? (car l)) (lat? (cdr l)))
         (else #f))))
  • uses cond and else

(define lat?
  (lambda (l)
    (or (null? l)
        (and (atom? (car l))
             (lat? (cdr l))))))
  • uses or and and

I think or short-circuits. Why? I know (car ()) and (cdr ()) each produce Error: Attempt to apply…. If or didn’t short-circuit, then (lat? ()) would eventually evaluate (car ()) and produce the error. However, (lat? ()) does not produce the error, therefore (via Modus Tollens) or short-circuits. Is this correct? And does and short-circuit?

1

There are 1 answers

2
Allan Wind On BEST ANSWER

Yes, they both short-circuit per r6rs specification (didn't find html version of r7rs online but here a link to the pdf version of r7rs specification, see section 4.2):

If there are no <test>s, #t is returned. Otherwise, the expressions are evaluated from left to right until a <test> returns #f or the last <test> is reached. In the former case, the and expression returns #f without evaluating the remaining expressions. In the latter case, the last expression is evaluated and its values are returned.

and & or is subsequently defined in terms of test.