17 ms·
pepper_sauce's example is a good one, the ability to mold the language to what features you need today is a big point. But even beyond that I think the big pur
by komon 8y ago
pepper_sauce's example is a good one, the ability to mold the language to what features you need today is a big point.
But even beyond that I think the big purpose of macros is the ability to mold the language the application you're applying it to. This is the Domain Specific Language (DSL) idea.
For instance, take Protocol Buffers. The .proto format is a language that lets you define your messages and denote which fields are required, optional, etc. You run a compiler against these .proto files that spits out a generated library for the platform you're on.
This sort of workflow isn't as onerous as it used to be with all the CI/CD push to have tools that build your application in one step. But it is still a separate language with its own compiler that must be maintained entirely outside of your project or language ecosystem.
If, in a hypothetical universe where Lisp dominated Google, protocol buffers had been written in Lisp you wouldn't need a separate compiler and language. A library of macros like defpackage and defmessage could be written that would generate the code for sending and receiving each message type you define inline with the rest of your application. It would all be Lisp code and would benefit from all of your Lisp tools, like linting, debugging, and testing.
And if it was written in a Lisp-y tradition, such a DSL would likely be riddled with hooks for your application code to be able to attach to dynamically, say if you would like every receipt of a message to be logged or if a message fails validation you would want to page the on-call to figure out who's sending bad messages and why.
So, in short, macros allow you to extend the language for reasons even beyond syntactical conveniences like DESTRUCTURING-BIND. It allows you to really shape your tools to the application at hand, and allows others to shape the tools you share to their applications.