Clojure - Reader

1 minute read

Reader

The reader’s job is to convert the textual source code into Clojure data structures.

Reading

We can directly interact with the reader to understand it better. To do that we can use the read-string function.

1(read-string "(+ 1 2)")
2; => (+ 1 2)
3
4(eval (read-string "(+ 1 2)"))
5; => 3

The reader can also do more complex stuff like converting anonymous functions.

1(read-string "#(+ 1 %)")
2; => (fn* [p1__443#] (+ 1 p1__443#))

Reader Macros

Reader macros are what allows the reader to convert anonymous functions. They are like a set of rules for transforming text into data structures. They allows us to write more compact code by taking a short form and expanding it. They use macro characters ', # and @.

1(read-string "'(a b c)")
2; => (qoute (a b c))
3
4(red-string "@var")
5; => (clojure.core/deref var)