re: The Coolest Programming Language Features VIEW POST


What a great post! It's really kicked off some good discussion.

Now... to business!


For those of you that don’t know, macros are actually a metaprogramming feature. More specifically, macros allow us to modify the language directly by adding rules to the abstract syntax tree. These rules are generated through pattern matching.

Alas! Alas, that you should have stumbled upon macros in Rust of all places! Macros in Rust are horrible - look at that syntax:

macro_rules! print {
    ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));

A whole new and weird 'pattern matching' language to manipulate Rust's AST. No wonder we're not meant to use it - it's horrible! macro_rules!? More like macro_sucks!.

My friend, if you want to see and do macro programming right, you need to get yourself a Lisp. Preferably Common Lisp, but Racket, Scheme or Clojure will do in a pinch. Because these languages exhibit homoiconicity, which is to say that the representation of the language - the way you write it - is a data structure of the language. You write Lisp - as lists!

This means that, when it comes to changing the program with a macro, you're using the same language (Lisp) to manipulate the list structures that are the syntax of Lisp. No weird embedded pattern matching language - just the same stuff you've been writing all along (only occuring before evaluation which takes a bit of getting used to...). Code is data! Data is code!

Try them today - Lisp macros are fun and easy!

(Whether they're a good idea or not is more contentious...)


So, I've actually written a pretty basic Lisp interpreter (in an imperative language no less), so it makes sense that you can manipulate the language with itself. In fact, I believe Racket has a ton of support for dialects, but I haven't gotten a chance to play around with that feature myself.

Thanks for the tip! I know C has macros as well, and they're arguably worse the Rust's, so I guess I could have used a worse example. haha

code of conduct - report abuse