运算符重载在Clojure [英] Operator Overloading in Clojure
问题描述
甚至仔细查看关于Clojure的文档,我没有看到任何关于Clojure是否支持操作符重载的直接确认。
如果是,有人可以给我提供一个如何重载的快速剪辑,让我们说,+运算符委托一些预定义的方法,我们可以调用 myPlus
。
我是新的Clojure,所以有人的帮助在这里将非常感激。
(defn ** [xy](Math / pow xy))$ +运算符(和一些其他数学运算符)是Clojure中的一个特例,因为它是一个特殊的例子。是内联的(对于二元情况,至少)。你可以在一定程度上避免这种情况,不要引用 clojure.core
(或排除 clojure.core / +
)
要创建一个命名空间,其中+被重新定义:
(ns my-ns
(:refer-clojure:exclude [+]))
(defn + [xy](println xy))
(+lookma)
是让你的+一个多方法,并为数字情况调用核心+函数。
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.
解决方案 Clojure's (as any Lisp's) operators are plain functions; you can define an "operator" like a function:
(defn ** [x y] (Math/pow x y))
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 excluding clojure.core/+
) in your namespace, but this can be very hairy.
To create a namespace where + is redefined:
(ns my-ns
(:refer-clojure :exclude [+]))
(defn + [x y] (println x y))
(+ "look" "ma")
One good strategy would probably be to make your + a multimethod and call core's + function for the numeric cases.
这篇关于运算符重载在Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!