Reading and evaluating code
Let's have a look at how code can be parsed and evaluated in Clojure. The most elementary way to convert text into an expression is by using the read
function. This function accepts a java.io.PushbackReader
instance as its first argument, as shown here:
user> (read (-> "(list 1 2 3)" .toCharArray java.io.CharArrayReader. java.io.PushbackReader.)) (list 1 2 3)
Note
These examples can be found in src/m_clj/c4/read_and_eval.clj
of the book's source code.
In this example, a string containing a valid expression is first converted into an instance of java.io.PushbackReader
and then passed to the read
function. It seems like a lot of unnecessary work to read a string, but it is due to the fact that the read
function deals ...
Get Clojure: High Performance JVM Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.