I am trying to write a macro that defines a special class of data structure with associated functions.
I know this is possible; it is done multiple times in the core language itself.
As a specific example, how would I define the define-struct macro in Scheme itself. It needs to create make-struct, struct-<<field>>, etc functions.
I tried doing this using define, however, this only defines the function in the macro’s lexical scope.
How can I actually define a function in a macro?
The key for an answer is
datum->syntax. The basic idea is that you want to take some random data and turn it into a syntax — in this case, turn a symbol into an identifier. An identifier is basically a symbol with some lexical information that (very roughly) indicates how it is bound. Usingdatum->syntaxyou can do exactly that: it expects an existing piece of syntax which is where it copies the binding from, and a datum (a symbol here) which is the value that is contained in the syntax wrapper.Here’s an example that demonstrates a
define-struct-like tool using this:And here’s an example of using it: