[plt-scheme] fun with define-syntax

From: Michael Vanier (mvanier at cs.caltech.edu)
Date: Thu Feb 6 21:42:21 EST 2003

I've just been playing with define-syntax and syntax-case using mzscheme's
implementation, and I quickly whipped up this variant of "if" that has
explicit "then" and "else" clauses which can include arbitrary numbers of
expressions, like cond can:

(define-syntax iff
  (lambda (x)
    (syntax-case x (then else)
     ((_ p (then c1 ...) (else a1 ...))
      (syntax (if p (begin c1 ...) (begin a1 ...))))
     ((_ p (then c1 ...))
      (syntax (if p (begin c1 ...)))))))

(define x 10)
(iff (= x 10)
  (then (display "yeah!") (newline))
  (else (display "nahh!") (newline)))
; result: yeah

(set! x 11)
(iff (= x 10)
  (then (display "yeah!") (newline))
  (else (display "nahh!") (newline)))
; result: nahh

This actually works.  The ease with which I did this totally blows my mind
("and lo, the programmer was enlightened").  I wonder why scheme doesn't
include this form right off the bat; I think beginners would find it less
confusing than the normal if.  

Hygienic macros rule.

Mike



Posted on the users mailing list.