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?
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.
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.
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