clojure require syntax rationale

烈酒焚心 提交于 2019-12-02 20:41:09
  1. in the first example why does the vector need to be quoted?

require is a function, so you have to quote them in order to prevent evaluation. Otherwise those symbols will be looked up in the current context, likely resulting in an error or possibly unexpected behavior. By the way, I think this not quite right: "Counter intuitive because normally vectors are not quoted in clojure (lists are quoted and vectors are treated as data)."

It may be counter intuitive to you, however there's nothing wrong with quoting vectors (or maps or sets). I often do when quickly testing something at the REPL, and don't want to type a : for each keyword in a map or vector, for instance:

user=> '{a 1 b 2 c 3}

rather than:

user=> {:a 1 :b 2 :c 3}

The first is very marginally faster to type if I just want to quickly get some data to test something with.

  1. why does it not need to be quoted in the ns macro?

Macros don't evaluate their arguments, they're sort of lazier than normal function calls, so the symbols (clj-json.core and json) don't need to be quoted to prevent evaluation.

  1. why does the list notation not allow :as?

Sorry, I don't know the answer to this one.

Ah, I took a look at the docs for require and found out. There's another form supported:

"The following would load the libraries clojure.zip and clojure.set abbreviated as 's'."

(require '(clojure zip [set :as s]))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!