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

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

问题描述

在尝试解决涉及重新执行评估的通用计算引擎时遇到的4Clojure问题,我不小心结束了调用这样的:

 (apply'/'(16 8))

 (apply / '(16 8))

这会产生混淆的副作用: 8



我后来发现我的错误后一些调试 - 我没有评估的 / 符号,然后尝试调用它 - 因此意识到 clojure.lang.Symbol 必须实现 clojure.lang.IFn 。但是,这个实现怎么做?我可以得到它做的是返回 nil 有一个参数,或第二个参数,如果给定。

符号在地图中自己查找,与关键字一样。请参见 Symbol的实现

  ... 
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}
...

code>是 clojure.lang。



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


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

(apply '/ '(16 8))

rather than the intended:

(apply / '(16 8))

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

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.

解决方案

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 }
…

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

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天全站免登陆