clojure中带有第一个自变量引用的列表的值是最后一个自变量? [英] Value of a list with quoted first argument in clojure is the last argument?

查看:34
本文介绍了clojure中带有第一个自变量引用的列表的值是最后一个自变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要表达

('+ 10 20)

评估为 20 ?这对我来说真的很奇怪!我本来希望给出一个错误,因为列表的第一个元素'+ 我不是可以评估的东西!

evaluate to 20? This is realy bizarre to me! I would have expected to give an error, because the first element of the list, '+ i not a thing that can be evaluated!

推荐答案

无论是好是坏,这都是Clojure的常见问题解答.因此,'+ (quote +)的简写,其结果为符号 + .符号(和关键字)可以视为函数,并在其参数中查找自身,因此('+ 10 20)本质上是(get 10'+ 20),这就是 get not-found Arity,因此,如果"collection" 10 不包含符号'+ ,则它将返回第三个参数 20 .

This is pretty much an FAQ with Clojure, for good or bad. So '+ is shorthand for (quote +) which evaluates to the symbol +. Symbols (and keywords) can be treated as functions and look themselves up in their argument, so ('+ 10 20) is essentially (get 10 '+ 20) and that's the not-found arity of get so if the "collection" 10 does not include the symbol '+ then it will return the third argument, 20.

您可能希望针对 10 的关联查询失败并引发异常,但是Clojure中有很多情况会导致查询返回 nil (或未找到版本),因为它从 nil -punning的角度来看是有益的,并且是导致惯用Clojure的一部分.

You might expect associative lookup against 10 to fail and throw an exception but there are a lot of situations in Clojure where lookup will return nil (or the not-found version) because it's beneficial from a nil-punning point of view and is part of what leads to idiomatic Clojure.

某些函数 do 执行这种参数检查:例如,(包含?10'+)会引发异常,而两个(得到10'+)(得到'+ 10)都将返回 nil .

Some functions do perform that sort of argument checking: (contains? 10 '+) will throw an exception, for example, whereas both (get 10 '+) and (get '+ 10) will both return nil.

可能还值得注意的是,以下内容引发了异常:

It's probably also worth noting that the following throws an exception:

user=> ('+ 10 20 30)
Execution error (ArityException) at user/eval39476 (REPL:1).
Wrong number of args (3) passed to: clojure.lang.Symbol

您询问在clojure中带有第一个自变量引用的列表的值是否为最后一个自变量"?并且答案是否定的,由于上述逻辑,这非常具体地是两个参数的函数调用:具有3个参数的符号,只能具有1或2.

You asked if the "value of a list with quoted first argument in clojure is the last argument" and the answer is no, this is very specifically a two-argument function invocation, because of the above logic: you can't "call" a symbol with 3 args, only with 1 or 2.

值得一提的是0 args情况的区别:

Worth noting the difference here for the 0 args case:

user=> ('+)
Execution error (ArityException) at user/eval39478 (REPL:1).
Wrong number of args (0) passed to: clojure.lang.Symbol
user=> (+)
0

第一种情况是符号查找-至少需要一个集合才能在其中查找自身-而第二种情况是函数调用( clojure.core/+ )为零参数,其返回 + 的标识值的方式与(*)返回 1 的方式相同.

The first case is a symbol lookup -- which requires at least a collection to look itself up in -- whereas the second case is a function invocation (of clojure.core/+) with zero arguments, which returns the identity value of + in the same way that (*) returns 1.

这篇关于clojure中带有第一个自变量引用的列表的值是最后一个自变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆