从字符串生成符号并将其应用为函数 [英] Generating a symbol from a string and applying it as a function
问题描述
我只是在学习Clojure,我撞墙了.
I'm just learning clojure, and I'm hitting a wall.
我正在尝试将算术表达式作为中缀字符串读取并在Clojure中对其进行处理.
I'm trying to read an arithmetic expression as an infix string and process it in Clojure.
例如"1 + 2"->(+1 2)
e.g. "1 + 2" -> (+ 1 2)
我读了"+",并将其变成这样的符号:
I read in the "+" and turn it into a symbol like this:
(def plus (symbol "clojure.core" "+"))
哪个似乎可以正常工作,但是当我打电话给我时,我没有得到我所期望的:
Which appears to work properly, but when I call it, I don't get what I'm expecting:
user=> plus
+
user=> (plus 1 1)
1
user=> (plus 1 2)
2
user=> (plus 1 2 3)
ArityException Wrong number of args (3) passed to: Symbol clojure.lang.AFn.throwArity (AFn.java:437)
我在这里想念什么?
推荐答案
默认情况下,符号具有附加的功能.默认情况下,附加到他们的功能是在地图中查找此键.这就是为什么您的行为举止奇怪的原因.它正在尝试查找地图中的元素.
Symbols have a function attached to them by default. The function that is attached to them by default is look this key up in a map. That is why your plus behaves oddly. It is attempting to look up elements in a map.
(加1 1)
这实际上是地图1中的符号+向上,如果未找到,则返回默认值1.
(plus 1 1)
This is really look the symbol + up in the map 1 and if not found return a default value of 1.
(加1 2)
除默认值为2之外,与上述相同.
(plus 1 2)
Same as above except default value is 2.
这篇关于从字符串生成符号并将其应用为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!