Operator Overloading in Clojure

后端 未结 2 1673
谎友^
谎友^ 2021-01-07 22:36

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 d

2条回答
  •  迷失自我
    2021-01-07 23:21

    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.

提交回复
热议问题