Clojure 中的运算符重载 [英] Operator Overloading in Clojure

查看:28
本文介绍了Clojure 中的运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使仔细查看关于 Clojure 的文档,我也没有看到任何关于 Clojure 是否支持运算符重载的直接确认.

Even looking closely over documentation on Clojure, I do not see any direct confirmation as to whether or not Clojure supports operator overloading.

如果是这样,有人可以向我提供有关如何重载的快速片段,例如+"运算符以委托给我们可以调用 myPlus 的某些预定义方法.

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.

我对 Clojure 非常,因此非常感谢有人在这里提供帮助.

I am very new to Clojure, so someone's help here would be greatly appreciated.

推荐答案

Clojure 的(和任何 Lisp 的一样)操作符是普通函数;您可以像函数一样定义运算符":

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))

+"运算符(和其他一些数学运算符)是 Clojure 中的一个特殊情况,因为它是内联的(至少对于二进制情况).您可以在一定程度上通过不在命名空间中引用 clojure.core(或排除 clojure.core/+)来避免这种情况,但这可能非常麻烦.

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屋!

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