Harry Spier
Harry Spier

Reputation: 1435

Scheme macro for "or"

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?

Upvotes: 3

Views: 302

Answers (2)

Eli Barzilay
Eli Barzilay

Reputation: 29554

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 ...))))))

?)

Upvotes: 6

Doug Currie
Doug Currie

Reputation: 41220

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.

Upvotes: 2

Related Questions