Some Practical Clojure Examples
← prev | next →     Top-level ToC     /read-and-eval.html     (printable version)

Two independent steps:

Read
The Clojure reader reads text and turns it into regular Clojure data structures (an AST).
Evaluate
Given a data structure (an AST), the evaluator evaluates it.

For example:

;; Results in a data structure:
(def x (read-string "(+ 1 2)")) ;=> (+ 1 2)

;; Here's that same data structure:
(def y '(+ 1 2))

(= x y) ;=> true

;; Eval it:
(eval x)             ;=> 3
(eval (list + 1 2))  ;=> 3
(eval (cons + [1 2]) ;=> 3

1 Read

clojure.core/read
clojure.core/read-string
clojure.edn/read
clojure.edn/read-string
clojure.tools.reader.edn/read
clojure.tools.reader.edn/read-string

The first two are not for reading data from untrusted sources.
The last four are safe and don’t allow any code execution.

Note: pr-strread-string

2 Evaluate

Many simple things evaluate to themselves:

nil   ;=> nil
true  ;=> true
3     ;=> 3
'foo  ;=> foo
:bar  ;=> :bar
"hi"  ;=> "hi"
\a    ;=> \a
{}    ;=> {}
#{}   ;=> #{}
()    ;=> ()   the empty list
[]    ;=> []

Symbols are