Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "regular" and "reader" macros?

Tags:

macros

clojure

I am relatively new to Clojure and can't quite wrap my mind around the difference between reader macros and regular macros, and why the difference is significant.

In what situations would you use one over the other and why?

like image 973
Lincoln Bergeson Avatar asked May 22 '17 13:05

Lincoln Bergeson


1 Answers

Reader macros change the syntax of the language (for example, @foo turns into (deref foo)) in ways that normal macros can't (a normal macro wouldn't be able to get rid of the parentheses, so you'd have to do something like (@ foo)). It's called a reader macro, because it's implemented in the read pass of the repl (check out the source).

As a clojure developer, you'll only create regular macros, but you'll use plenty of reader macros, without necessarily considering them explicitly.

The full list of reader macros is here: https://clojure.org/reference/reader and includes common things like @ ', and #{}.

Clojure (unlike some other lisps) doesn't support user-defined reader macros, but there is some extensibility built into the reader via tagged literals (e.g. #inst or #uuid)

like image 74
Alejandro C. Avatar answered Sep 20 '22 16:09

Alejandro C.