gpt4 book ai didi

Clojure 向量前何时需要撇号

转载 作者:行者123 更新时间:2023-12-02 05:02:16 24 4
gpt4 key购买 nike

来自《Clojure 的乐趣》一书:

第一个例子:

(def fifth (comp first rest rest rest rest))
(fifth [1 2 3 4 5])
;=> e

第二个例子:

(defn fnth [n]
(apply comp
(cons first
(take (dec n) (repeat rest)))))
((fnth 5) '[a b c d e])
;=> e

为什么在第二个示例中(但第一个示例中不需要)需要撇号?如果没有,第二个示例将引发错误。

最佳答案

在第二个示例中,您必须使用撇号,因为您想防止对向量元素进行求值。如果删除撇号,Clojure 将尝试解析符号 ab 等,就好像它们绑定(bind)到某些值一样。

示例:

user> '[a b c d e]
;; => [a b c d e]
user> [a b c d e]
CompilerException java.lang.RuntimeException: Unable to resolve symbol: a
user> (let [a 1
b 2
c 3
d 4
e 5]
[a b c d e])
;; => [1 2 3 4 5]

请注意,您不必对数字使用撇号,因为它们会自行计算:

user> 1
;; => 1
user> 2
;; => 2
user> [1 2 3]
;; => [1 2 3]

虽然符号不存在,Clojure 将搜索给定符号绑定(bind)到的值:

user> x
CompilerException java.lang.RuntimeException: Unable to resolve symbol: x

因此,了解了这些信息以及在进入函数之前对函数参数进行求值的事实,应该清楚为什么以及何时在向量之前使用撇号。

关于Clojure 向量前何时需要撇号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26312789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com