Clojure 符号用作函数时会做什么? [英] What do Clojure symbols do when used as functions?

查看:19
本文介绍了Clojure 符号用作函数时会做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试解决涉及重新实现评估的 4Clojure 问题通用计算引擎"时,我不小心最终调用了这样的东西:

While trying to solve the 4Clojure problem "Universal Computation Engine" involving reimplementing evaluation, I accidentally ended up calling something like this:

(apply '/ '(16 8))

而不是预期:

(apply / '(16 8))

这会产生返回 8 的令人困惑的副作用,这让我觉得我把数学搞砸了.

This had the confusing side effect of returning 8, which made me think I had messed up my maths.

我后来在一些调试后意识到我的错误——我在尝试调用它之前未能评估 / 符号——因此意识到 clojure.lang.Symbol 必须实现clojure.lang.IFn.但是那个实现做什么?我所能做的就是返回带有一个参数的 nil ,或者如果给定第二个参数.

I later realised my error after some debugging—I was failing to evaluate the / symbol before attempting to call it—and so realised that clojure.lang.Symbol must implement clojure.lang.IFn. But what does that implementation do? All I can get it to do is return nil with one argument, or the second argument if given.

推荐答案

符号在地图中查找,就像关键字一样.参见 Symbol 的实现:

Symbols look themselves up in a map, much as keywords do. See Symbol's implementation:

…
122 public Object invoke(Object obj) {
123         return RT.get(obj, this);
124 }
125
126 public Object invoke(Object obj, Object notFound) {
127         return RT.get(obj, this, notFound);
128 }
…

(RTclojure.lang.RT,它几乎可以完成所有事情.RunTime"?)

(RT is clojure.lang.RT, which does just about everything. "RunTime"?)

在给出的示例中,查找失败(因为 16 不是映射),因此返回 notFound 值 (8).

In the example given, the lookup is failing (because 16 is not a map), and therefore the notFound value (8) is being returned.

这篇关于Clojure 符号用作函数时会做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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