使用clojure符号函数进行间接函数调用 [英] using clojure symbol function to make indirect function call
问题描述
我期望下面我应该能够通过符号函数间接调用我的函数的平方,但它不工作。我在这里做错了:
I'm expecting below that I should be able to call my function squared indirectly via the symbol function, but its not working. What am I doing wrong here:
user=> (defn squared [x] (* x x))
#'user/squared
user=> (squared 2)
4
user=> ((symbol "squared") 2)
nil
user=> ((symbol "user" "squared") 2)
nil
user=>
推荐答案
符号本身不包含你的函数,var
The symbol itself does not hold your function, the Var it names does.
这表示获取内容( @
= deref <由符号(
符号
)命名的Var( resolve
)的名称为squared
并将其(作为函数)应用于参数 2
:
This says "take the contents (@
= deref
) of the Var (resolve
) named by the symbol (symbol
) whose name is "squared"
and apply it (as a function) to the argument 2
:
(@(resolve (symbol "squared")) 2)
b $ b
这表示以符号等命名的变量:
This says "take the Var named by the symbol etc.":
((resolve (symbol "squared")) 2)
这两个都可以工作,因为Vars当被要求作为一个函数, (如果你试图使用一个Var作为一个函数,当它没有绑定到一个函数,将导致一个错误。)
Both will work, since Vars, when asked to act as a function, defer to the functions stored in them. (If you try to use a Var as a function when it is not bound to a function, an error will result.)
这个说以符号的平方
并将其作为函数应用于参数 2
符号本身用作函数:
This says "take the symbol named "squared"
and apply it as a function to the argument 2
" -- note that the symbol itself is used as the function:
((symbol "squared") 2)
现在符号可以用作函数(它们实现 clojure.lang.IFn
接口),但是当它们以这种方式使用时它们的行为方式是它们在自己的参数中看起来自己,即将它们的参数作为映射处理,并在其中执行查找:
Now symbols can be used as functions (they implement the clojure.lang.IFn
interface), but the way they act when used in this way is that they look themselves up in their argument, i.e. treat their argument as a map and perform a lookup inside it:
('foo {'foo 2})
; is equivalent to
(get {'foo 2} 'foo)
到符号是不是有意义的做查找, nil
被返回。
If the argument passed to a symbol is not something it makes sense to do lookups in, nil
is returned.
这篇关于使用clojure符号函数进行间接函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!