Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme macro for "or"

Tags:

scheme

I'm going through Kent Dybvig's "The Scheme Programming Language" in order to learn Scheme macros's.

In section 8.2 http://www.scheme.com/tspl4/syntax.html#./syntax:h2 he has the example for the "or" macro of

(define-syntax or
   (syntax-rules ()
     ((_) #f)
     ((_ e) e)
     ((_ e1 e2 e3 ...)
      (let ((t e1)) (if t t (or e2 e3 ...))))))

Is there some reason he didn't use the more simple form of:

(define-syntax or
   (syntax-rules ()
     ((_) #f)
     ((_ e) e)
     ((_ e1 e2 ...)
      (let ((t e1)) (if t t (or e2 ...))))))

Do the two forms expand equivalently?

like image 661
Harry Spier Avatar asked Mar 08 '26 23:03

Harry Spier


2 Answers

IMO, it's done to make things a little clearer -- your simpler form depends on the order of the cases, since (or x) can match both of the second and third rules. So making the cases mutually exclusive makes it easier to read and also more robust.

(BTW, there's a more subtle point there, which I initially thought that you were asking about: why not simplify it even further to:

(define-syntax or
  (syntax-rules ()
    ((_) #f)
    ((_ e1 e2 ...)
     (let ((t e1)) (if t t (or e2 ...))))))

?)

like image 135
Eli Barzilay Avatar answered Mar 10 '26 13:03

Eli Barzilay


A subpattern followed by ... can match zero or more elements of the input. Using e1 e2 e3 makes this case uniquely different than the preceding one.

like image 40
Doug Currie Avatar answered Mar 10 '26 13:03

Doug Currie