|
|
|
|
|
by AKrumbach
3046 days ago
|
|
I don't know about "won't have a clue what macros are capable of before..." -- there are quite a few use cases for macros which can be described easily to any programmer, even those who never used Lisp.
I would like to believe it would suffice to say "macros in Lisp allow you to fully extend the the language with new primitives and abstractions in a way that no other language does", but examples are always helpful. Lisp has a macro called setf, which takes any call which gets a value -- whether from a local function variable, or a class, to an array or hash table entry -- and converts it to the corresponding setter call. (If you define your own value places/types, there are also functions to make setf aware of how they work, so this isn't restricted to just some defined set of features in the language. Anything that holds a value in Lisp can be "setf" to a new value.) There are a couple of other "big" Lisp macros in the language standard like with-open-file (which ensures a file is closed once control flow exits the body), loop (does pretty much what it says on the tin: provides whatever looping method you might want), or handler-case (try-catch style error handling; yes, Lisp allows for other methods). Or how about the example I recently saw in a cryptography library. Since a lot of cryptographic algorithms use integer math modulo some giant number, this library defined a macro "mod-n" which took a base and some Lisp code, and re-wrote the code so the common integer math functions (addition, multiplication, etc.) would only return values "modulo {base}" --that is, return only values between 0 (inclusive) and base (exclusive). This meant their modulo math code looked (nearly) the same as normal, just standard arithmetic functions. This wasn't a very large macro either: only around 10 lines long (and about half of that being the list of operator replacements). |
|