Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading