Clojure 中的运算符重载
即使仔细查看 Clojure 上的文档,我也没有看到任何关于 Clojure 是否支持运算符重载的直接确认。
如果确实如此,有人可以为我提供一个关于如何重载的快速片段,比方说,将“+”运算符委托给我们可以调用 myPlus
的某个预定义方法。
我对 Clojure 非常陌生,因此非常感谢这里有人的帮助。
Even looking closely over documentation on Clojure, I do not see any direct confirmation as to whether or not Clojure supports operator overloading.
If it does, could someone provide me with a quick snipplet of how to overload, let's say, the "+" operator to delegate to some predefined method that we can call myPlus
.
I am very new to Clojure, so someone's help here would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看这个:
http://clojure.org/multimethods
某些函数(例如 +)是核心函数,无法重新定义。
例如,您可以创建一个新函数并将其命名为“.+”或“!+”,这在可读性方面是相似的。
使用上面包含的多方法 URL 中的信息,您可以构建一个函数来告诉您的 .+ 使用哪个实现。
Take a look at this:
http://clojure.org/multimethods
Certain functions, like + are core and cannot be redefined.
You could make a new function and call it ".+" or "!+" for example, which is similar in terms of readability.
Using the information in the multimethods URL included above, you can build a function that tells your .+ which implementation to use.
Clojure 的(和任何 Lisp 的)运算符都是普通函数;您可以像函数一样定义“运算符”:
“+”运算符(以及其他一些数学运算符)是 Clojure 中的特殊情况,因为它是内联的(至少对于二进制情况)。您可以在一定程度上避免这种情况,方法是在命名空间中不引用
clojure.core
(或排除clojure.core/+
),但这可能会非常棘手。创建一个重新定义 + 的命名空间:
一个好的策略可能是使 + 成为多方法并针对数字情况调用核心的 + 函数。
Clojure's (as any Lisp's) operators are plain functions; you can define an "operator" like a function:
The "+" operator (and some other math-operators) is a special case in Clojure, since it is inlined (for the binary case, at least). You can to a certain extent avoid this by not referring to
clojure.core
(or excludingclojure.core/+
) in your namespace, but this can be very hairy.To create a namespace where + is redefined:
One good strategy would probably be to make your + a multimethod and call core's + function for the numeric cases.