One way to accomplish this is via :refer-clojure in ns.

Usage is like:

(ns test
  (:refer-clojure :exclude [+]))

This would allow you to, for example, dispatch the implementation
based on the type of the first argument via multimethods (as Michel S.
noted, at a performance penalty). The original implementation of + is
still available as clojure.core/+.

For example, you could define + for complex numbers (as a contrived
example) by switching on the class of the first element, using a
custom adding routing for complex numbers when the first element is a
struct instance, and falling back on clojure.core/+ otherwise.

(defstruct complex :real :imaginary)

(defmulti + (fn [& args] (class (first args))))
(defmethod + clojure.lang.PersistentStructMap [& more]
  (letfn [(add-complex [{x-real :real x-imaginary :imaginary}
                        {y-real :real y-imaginary :imaginary}]
            (struct-map complex
              :real (clojure.core/+ x-real y-real)
              :imaginary (clojure.core/+ x-imaginary y-imaginary)))]
    (reduce add-complex more)))
(defmethod + :default [& more] (apply clojure.core/+ more))

Example usage would be:

(println (+ 1 2 3))
; -> 6

(println (+ (struct complex 1 2)
            (struct complex 2 3)
            (struct complex 3 4)))
; -> {:real 6 :imaginary 9}

That said, I believe it is considered bad practice to redefine core
functions. A better approach to this particular problem can be seen in
clojure.core.complex-numbers.

Best,

Trevor

On May 16, 4:32 pm, Saptarshi <saptarshi.g...@gmail.com> wrote:
> Hello,
> I am totally new to Clojure and have dabbled in Scala. In Scala, it is
> possible to override the + operator ,e.g a class A can overide +.
> In Clojure, I would have a struct and not a class. Can I still
> override the + operator in Clojure?
>
> Regards
> Saptarshi
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to