11

from "The Joy of Clojure" book:

first example:

(def fifth (comp first rest rest rest rest))
(fifth [1 2 3 4 5])
;=> e

second example:

(defn fnth [n]
  (apply comp
    (cons first
      (take (dec n) (repeat rest)))))
((fnth 5) '[a b c d e])
;=> e

why in the second example (but not in the first) do I need an apostrophe? without one the second example will raise an error.

Alonzorz
  • 1,764
  • 2
  • 15
  • 21

2 Answers2

10

In the second example you have to use apostrophe because you want to prevent evaluation of elements of the vector. If you remove the apostrophe, Clojure will try to resolve symbols a, b, etc., as as if they're bound to some values.

Example:

user> '[a b c d e]
;; => [a b c d e]
user> [a b c d e]
CompilerException java.lang.RuntimeException: Unable to resolve symbol: a
user> (let [a 1
            b 2
            c 3
            d 4
            e 5]
        [a b c d e])
;; => [1 2 3 4 5]

Please note that you don't have to use aphostrophe with numbers, since they evaluate to themselves:

user> 1
;; => 1
user> 2
;; => 2
user> [1 2 3]
;; => [1 2 3]

while symbols do not, Clojure will search for a value that given symbol is bound to:

user> x
CompilerException java.lang.RuntimeException: Unable to resolve symbol: x

So knowing this info and the fact that arguments of a function are evaluated before getting into the function, it should be clear why and when to use an apostrophe before a vector.

Mark Karpov
  • 7,164
  • 2
  • 23
  • 54
2

In the second example the quote ' is there to prevent the evaluator from evaluating the form after it (the vector).

The symbols in it aren't self-evaluating (read more here http://clojure.org/evaluation) and the evaluator would try to resolve them.

E. g.

(def foo 42)

[foo]
=> [42] ;; vector with number 42, resolved via foo

'[foo]
=> [foo] ;; vector with the symbol foo, decoupled from the var foo

You may want to read another quote example here http://clojure.org/special_forms#quote, and dig deeper to learn about the reader and syntax quotation here: http://clojure.org/reader

Leon Grapenthin
  • 8,937
  • 18
  • 36