concept defmethod in category clojure

appears as: defmethod, defmethod
Clojure: The Essential Reference

This is an excerpt from Manning's book Clojure: The Essential Reference.

  • “defmulti and defmethod” along with defmethod defines multimethods in Clojure. Consider using multimethods if the quality and number of conditions in a cond tends to expand frequently to handle previously unknown cases. “defmulti and defmethod” offers a flexible polymorphic dispatch including the possibility to extend the multimethod from different namespaces (while all cond expressions need to be defined inside a single form).
  • (def total-payments ; #1
      {:op 'times
       :expr
       [[:loan 150000]
        {:op 'pow
         :expr
         [{:op 'plus
           :expr
           [[:incr 1]
            {:op 'divide
             :expr [[:rate 3.16]
                    [:decimals 100]
                    [:months 12]]}]}
          {:op 'times
           :expr [[:months 12] [:years 10]]}]}]})
    
    (def ops ; #2
      {'plus +
       'times *
       'divide /
       'pow #(Math/pow %1 %2)})
    
    (defmulti calculate ; #3
      (fn [form] (:op form)))
    
    (defmethod calculate 'plus ; #4
      [{:keys [op expr]}]
      (apply (ops op) (map calculate expr)))
    
    (defmethod calculate 'times
      [{:keys [op expr]}]
      (apply (ops op) (map calculate expr)))
    
    (defmethod calculate 'divide
      [{:keys [op expr]}]
      (apply (ops op) (map calculate expr)))
    
    (defmethod calculate 'pow
      [{[x y] :expr}]
      (Math/pow (calculate x) (calculate y)))
    
    (defmethod calculate nil ; #5
      [[descr number]]
      number)
    
    (defmethod calculate :default [form] ; #6
      (throw (RuntimeException. (str "Don't know how to calculate" form))))
    
    (calculate total-payments) ; #7
    ;; 205659.10262863498

    We could use a custom hierarchy to take care of the potential duplication generated by similar defmethods. In the previous example, defmethod implementations are changing in relation to the number of arguments supported by each operation. In the following improved implementation, we provide calculate with a custom hierarchy to group operations by number of arguments. The custom hierarchy builds on top of a new data structure that replaces the previous dictionary called ops: