Search code examples
clojure

What does a quote mean in front of a vector in clojure?


Suppose you have the following line of code in clojure. What do you need the quote for?

(require '[clojure.string :as str])

Solution

  • A quote prevents evaluation. By default, all expressions are evaluated in Clojure. Using a quote in front of the expression prevents the evaluation. Most expressions in Clojure are self-evaluating (they evaluate to themselves). The two main exceptions are symbols and lists. Edit: See comment from @amalloy below and response.

    In this case, the quote is creating a literal vector whose first element is the symbol clojure.string, the second element is the keyword :as and the third is the symbol str.

    Without the quote, (require [clojure.string :as str]), would try to evaluate the symbols clojure.string and str and the value would be whatever the var bound to those symbols contains (or an error, if there is nothing bound).

    Here is an example demonstrating the difference. Let's say you have the following two defs.

    (def a 16)
    (def b 12)
    

    Now, '[a 14 b] would evaluate to the vector [a 14 b]. But, [a 14 b] would evaluate to [16 14 12].

    See the Evaluation section on clojure.org for the details on exactly how a symbol is resolved in Clojure.

    You might also find the documentation for quote to be helpful, as also the section on Clojure syntax.