Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use single quote around vector in "use" (in clojure)?

Tags:

clojure

When I use some long function names, I used the use form, like this:

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

But I don't know why add a single quote ' to the vector, so I tried to figure out its type:

(type '[clojure.string :as str])
;=> clojure.lang.PersistentVector

Simplified example:

(type ["hello"])
;=> clojure.lang.PersistentVector

(type '["hello"])
;=> clojure.lang.PersistentVector

It seems the single quote doesn't change anything, can anybody explain the usage of it in the use form?

like image 698
Nick Avatar asked Dec 06 '15 14:12

Nick


2 Answers

The intent is to quote the symbols. This way they'll be treated as symbols, and use can take those symbols as naming a namespace to load and pull into the current. You want to avoid the default treatment of a symbol, which is resolving it as the name of a Var and using the value of that Var. You can also do this as

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

but that involves some unnecessary typing; quoting the whole vector makes you less likely to forget anything. Particularly if you're doing anything with :only, :refer or similar keyword arguments.

Aside: ns doesn't need this because as a macro it can control evaluation of its arguments - functions like require and use have all their arguments read and evaluated before they themselves run. This is part of the reason why ns is normally preferred over those functions.

like image 91
Magos Avatar answered Oct 24 '22 04:10

Magos


use is a function, hence the evaluator evaluates its arguments before they are passed (applicative order evaluation).

You don't want [clojure.string :as str] to be evaluated as the evaluator would try to resolve the symbols in it with no success before applying use.

Hence quote (reader shorthand ') is there to prevent their evaluation.

like image 32
Leon Grapenthin Avatar answered Oct 24 '22 04:10

Leon Grapenthin