Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure when is an apostrophe needed before vector

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.

like image 274
Alonzorz Avatar asked Oct 11 '14 08:10

Alonzorz


1 Answers

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.

like image 114
Mark Karpov Avatar answered Sep 30 '22 17:09

Mark Karpov