Do and and or short circuit in Scheme?
The following are two implementation of lat? (list of atoms). One uses cond … else 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
condandelse
(define lat?
(lambda (l)
(or (null? l)
(and (atom? (car l))
(lat? (cdr l))))))
- uses
orandand
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?
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):
and&oris subsequently defined in terms oftest.