0

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?

joseville
  • 685
  • 3
  • 16
  • Does this answer your question? [why \`and\` operator in scheme is not an built-in procedure](https://stackoverflow.com/questions/26902224/why-and-operator-in-scheme-is-not-an-built-in-procedure) – ad absurdum Dec 12 '21 at 05:25

1 Answers1

4

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.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • Thanks! Just wanted to say that I found your first edit easier to understand at a glance. – joseville Dec 12 '21 at 01:48
  • 1
    Yeah, I know, specifications are formal and usually harder to read. The first edit was to class website and not a specification as I claimed. – Allan Wind Dec 12 '21 at 01:50