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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With