[racket] Capturing Procedures in Macros: Style Question

From: Deren Dohoda (deren.dohoda at gmail.com)
Date: Sat Jun 18 11:17:38 EDT 2011

Hi everyone,

I wrote a small polynomial math library. In it are operations like
poly-add, poly-times, poly-expt, and poly-sub, performing the
operations that should be obvious. In a language like C++, one might
have defined a polynomial class and then, possibly, override the +, -,
and * operators (and throw up about the expt operation). I'm not
normally a fan of operator overloading in a language because I feel it
obscures what's actually happening. But in a language like Racket,
overloading for a particular scope can be explicit and it seems less
like encryption and more like good sugar.

The macro I have is:
(define-syntax using-poly-math
  (λ(stx)
    (syntax-case stx ()
      ((_ exp exps ...)
       (with-syntax ((+ (datum->syntax #'exp '+))
                     (- (datum->syntax #'exp '-))
                     (* (datum->syntax #'exp '*))
                     (expt (datum->syntax #'exp 'expt)))
         #'(let ((+ poly-add)
                 (- poly-sub)
                 (* poly-times)
                 (expt poly-expt))
             (begin exp
                    exps ...)))))))

My understanding of macros which capture variables is poor, compounded
by my also poor understanding of syntax-case, and in fact this was
kind of ripped from a blog post (I believe Eli's). But with it:
> (let ((p1 '(1 1)))
    (using-poly-math
     (+ p1 (expt p1 5))))
'(1 5 10 10 6 2)

Which is nice and concise.

I have two questions:
1) Is this kind of capturing macro a bad style?
2) Is this macro correct for what I'm trying to do? Is it expressed poorly?

Thanks for any insight,
Deren



Posted on the users mailing list.