[racket-dev] Identifier macros
I learned about identifier macros mostly from scrambling through the
racket sources. There they are often seen in places where macros are used
instead of functions to avoid the cost of a function call. Normally.
macros have the drawback that they can't be passed around or applied like
functions.
(define-syntax-rule (call/print fun args ...)
(begin
(printf "call ~s\n" (cons 'fun '(args ...)))
(fun args ...)))
(call/print printf "~a ~a\n" 1 2) ; works
(apply call/print printf "~a ~a\n" '(1 2)) ; fails with "use does not
match pattern"
That's where identifier macros come into play:
(define-syntax call/print
(syntax-id-rules ()
[(_ fun args ...)
(begin
(printf "call ~s\n" (cons 'fun '(args ...)))
(fun args ...))]
[_ (lambda (fun . args)
(printf "call ~s\n" (cons 'fun args))
(apply fun args))]))
(call/print printf "~a ~a\n" 1 2) ; works with first rule
(apply call/print printf "~a ~a\n" '(1 2)) ; works with the second rule
Like this both cases work and the user must not know if, what he calls is
a function or a macros. The advantage for the user is that he gets a
speedup in the common case and the developer can optimize functions
without breaking code.
Maybe that would be a good addition for the "Optimization" section.
Tobias
On Tue, 04 Dec 2012 23:16:17 +0100, Carl Eastlund <cce at ccs.neu.edu> wrote:
> I'm confused about so-called "identifier macros". I had thought that
> ordinary transformers bound to functions could only transform
> application-position references to themselves, and that a "set!
> transformer" was required to transform bare references and set!
> references. Turns out I was wrong, set! transformers are in fact only
> required to transform set! references. So why are they listed under the
> documentation for "identifier macros" and why does that documentation
> imply
> that normal transformers can't handle bare references?
>
> Carl Eastlund
--
---------------------------------------------------------
Tobias Hammer
DLR / Institute of Robotics and Mechatronics
Muenchner Str. 20, D-82234 Wessling
Tel.: 08153/28-1487
Mail: tobias.hammer at dlr.de