Clojure - 如何准确评估符号?

Clojure - how exactly symbols are evaluated?

我们知道 clojure 在从读取 unicode 字符到 reader 输出的实际评估的几个阶段评估 (+ 1 1)...

在代码中,看起来像
(eval (read-string "(+ 1 1)"))

但是 ('+ '1 '2)(或 ('+ 1 2))给我 2 时...

核心> (def something ('+ '1 '2))
#'alcamii4hr.core/something
核心>(输入内容)
java.lang.Long

符号和关键字一样,可以像函数一样调用。当被调用时,他们都做同样的事情,在他们认为是地图的地方查找自己。他们有两个参数 [a-map][a-map not-found].

;; not-found defaults to nil
('foo {'bar 42}) ;=> nil

('foo {'foo 42}) ;=> 42

;; not-found can also be supplied in the arity-2 case
('foo {'bar 42} :not-found) ;=> :not-found

在您的特定情况下,它只是假设第一个参数是关联的,并且不检查。它在假定为地图的内容中找不到符号 +,因此 returns 未找到的值:2.

('+ '1) ;=> nil     ; not-found

('+ '1 '2) ;=> 2    ; because 2 is the not-found values

('+ '1 '2 '3) ;=> clojure.lang.ArityException

要了解这一切如何组合在一起,您可以查看 invoke method on the symbol class, 调用 clojure.RT.get, which is what looks something up in an associative thing. This is the same method called by clojure.core/get.

在 clourescript 中,其工作方式相同,但实现方式不同。 (在 clojurescript 本身,而不是在宿主语言中。)你可以阅读 here.