Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Overloading in 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.

like image 284
Ryan Delucchi Avatar asked Oct 08 '09 01:10

Ryan Delucchi


2 Answers

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.

like image 186
pmf Avatar answered Sep 24 '22 10:09

pmf


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.

like image 28
Mark Bolusmjak Avatar answered Sep 22 '22 10:09

Mark Bolusmjak