[gambit-list] macro-expand

Joel Borggrén-Franck joel.borggren.franck at gmail.com
Sat Mar 8 10:31:09 EST 2008


The manual says to use pp as a macro expander:

> (define-macro (push var #!optional val)
    `(set! ,var (cons ,val ,var)))
> (pp (lambda () (push stack 1) (push stack) (push stack 3)))
(lambda ()
  (set! stack (cons 1 stack))
  (set! stack (cons #f stack))
  (set! stack (cons 3 stack)))

Since I got tired of the extra writing and the lambda in the output, I
wrote my own macro-expand macro based on the pp example from the
manual:

;; Expand one a gambit-c macro form.
(define-macro (macro-expand mac)
  (let ((port (gensym))
        (form (gensym)))
    `(let ((,port (open-string)))
        (pp (lambda () ,mac) ,port)
        (let ((,form (read ,port)))
          (caddr ,form)))))

It works as I expect:
> (macro-expand (macro-expand 0))
(let ((#:g2 (open-string))) (pp (lambda () 0) #:g2) (let ((#:g3 (read
#:g2))) (caddr #:g3)))

but it strikes me as a bit inelegant.

Is there a better solution? Is there a way to read from pp without
creating a port first? I played around with with-output-to-string
first but that just gave me a headache.

/Joel



More information about the Gambit-list mailing list