What is the best route for an experienced imperative style programmer only familiar with C macros to learn the Racket macro system. Not just the mechanics of it (the how?) but also the where and why to use it and examples that illustrate this.
Should one learn Scheme (or Lisp) macros first? I’ve heard that the book “On Lisp” has a good explanation of Lisp macros with excellent examples of their use. Would this be useful or not?
Racket’s documentation has an excellent tutorial on using macros.
I would definitely recommend Scheme macros over CL macros if you haven’t deal with any sort of Lisp macros before. That’s because Scheme macros use pattern matching, and it’s much easier to read.
Example (using Racket’s
define-syntax-rule):This is a very simple macro that defines
letin terms of creating a corresponding lambda, then applying it. It’s easy to read, and easy to reason about what it does.Slightly more complicated macro:
This defines
let*in terms of nestedlets, so that the bindings are done sequentially. It includes a base case (with no bindings), as well as a recursive case.