在Clojure中,函数,带引号的函数和尖引号的函数之间的差异 [英] In Clojure, difference between function, quoted function and sharp-quote function
问题描述
在Clojure中,我想知道以下三个之间的区别.
In clojure, I'd like to know what are the differences between the three below.
(println (map + '(1 2 3) '(4 5 6)))
(println (map '+ '(1 2 3) '(4 5 6)))
(println (map #'+ '(1 2 3) '(4 5 6)))
结果是
(5 7 9)
(4 5 6)
(5 7 9)
我听不懂第二个人的行为.
I can't understand the second one's behavior.
我觉得Clojure中的第一个和第三个是相同的Lisp-1并且不区分评估变量和同名函数.
I feel the first one and the third one are the same in clojure which is Lisp-1 and doesn't distinguish between evaluating a variable and the identically named function.
这可能是一个基本问题,但似乎信息量不足.请教我.
This may be a basic question, but there seems not to be enough infomation. Please teach me.
谢谢.
推荐答案
关于第三种情况,与Common Lisp相比,#'+
不能理解为(function +)
并在函数名称空间中引用符号 +
的值,因为Clojure没有函数名称空间.而是将其读取为(var +)
,并引用称为 +
的 var
.应用 var
与应用存储在 var
中的值相同.
Regarding the third case, in contrast to Common Lisp, #'+
does not read as (function +)
and refer to the value of the symbol +
in the function namespace, since Clojure does not have a function namespace. Instead, it reads as (var +)
and refers to the var
called +
. Applying a var
is the same as applying the value stored in the var
.
在第二种情况下,您将一个符号重复地应用于一对数字.这是偶然发生的.在地图上应用符号与在该地图中建立索引相同:
In the second case, you are repeatedly applying a symbol to a pair of numbers. This is valid by accident. Applying a symbol to a map is the same as indexing into that map:
user> ('a {'a 1, 'b 2, 'c 3, '+ 4})
1
user> ('+ {'a 1, 'b 2, 'c 3, '+ 4})
4
如果提供第二个参数,则在地图中找不到匹配键的情况下,它将用作默认值:
If you supply a second argument, it is used as the default value in case no matching key is found in the map:
user> ('+ {'a 1, 'b 2, 'c 3} 4)
4
由于在每次迭代中,您都将符号 +
应用于一对数字,并且由于数字不是映射,因此不包含 +
作为键,则返回第二个参数作为匹配失败的默认值.
Since in each iteration, you apply the symbol +
to a pair of numbers, and since a number isn't a map and therefore doesn't contain +
as a key, the second argument is returned as the default value of a failed match.
user> ('+ 'foo 4)
4
user> ('+ {} 4)
4
user> ('+ 1 4)
4
这篇关于在Clojure中,函数,带引号的函数和尖引号的函数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!