reddit / emacs

Need help learning defmacro

ixlxixl · 2022-07-28 19:00
I have the following code: (defmacro print-name-from-language (language) (let ((name (symbol-name language))) `(message ,name))) (print-name-from-language 'c++) and I'm getting this error: let: Wrong type argument: symbolp, 'c++
TheBB · 2022-07-28 19:24
Don't quote c++ in the macro call. Macro arguments aren't evaluated, so you're getting `(quote c++)`.
Phil-Hudson · 2022-07-29 06:42
Having said that, and understanding that you may have given us an over-simplified example, bear in mind that `message` uses the same escapes as `format`, meaning the `%S` (uppercase S, not lowercase) escape will do the `symbol-name` lookup for you. You can thus replace the whole body of this macro with `(message "%S" language)`. This leads to a more important insight: don't create a Lisp macro where a function will do. At first it might seem like it makes no difference, but trust me, it does. I can go into it at length if you like, but basically, functions are more *tractable*, as they are first-class objects available at runtime. Lisp macros are a fantastic tool for automated programming, making Lisp "the programmable programming language", but they should not be used for ordinary computation.
purcell · 2022-07-29 10:28
Read the corresponding chapters in Practical Common Lisp, available free online.
ieure · 2022-07-29 14:28
On Lisp also has a chapter on macros.
ixlxixl · 2022-07-29 19:33
Very good points! I think of macros as template programming in C++.
ixlxixl · 2022-07-29 19:33
Thanks for sharing!
Phil-Hudson · 2022-07-29 19:44
You're free now. Free, I tell you! You will never have to deal with such an abomination as C++ templates again. Relax, take a deep breath and let it go. Ahhh. That's better!
Phil-Hudson · 2022-07-30 02:10
And straight after "On Lisp", read "Let Over Lambda", which is all about Lisp macros (in Common Lisp): https://letoverlambda.com/index.cl/toc