[Clojure Multimethods] Dawn Breaks Over Marblehead

Phew! Dawn breaks over Marblehead Finally I am beginning to understand multi-methods.

(defn get-int-calc-tag [acct-type]
(cond   (= acct-type C) :checking
(= acct-type S) :savings
(= acct-type M) :moneym
:else            :default))

(defrecord AcctInfo [acct-type int-val cur-bal])

(defmulti calc-int (fn [acct-info] (get-int-calc-tag (:acct-type acct-info))))

(defmethod calc-int :checking [acct-info] (* (:cur-bal acct-info) (:int-val acct-info)))
(defmethod calc-int :savings [acct-info] (* (:cur-bal acct-info) (:int-val acct-info)))
(defmethod calc-int :moneym [acct-info] (* (:cur-bal acct-info) (:int-val acct-info)))
(defmethod calc-int :default [acct-info] (println "Unknown account type."))

Please note this doesn’t run on Clojure 1.2.1, and I’m trying to find out why.



Filed under Clojure

3 responses to “[Clojure Multimethods] Dawn Breaks Over Marblehead

  1. A few comments:

    1) I assume you’re planning on varying the defmethod impls, right? (or else there’s no reason to use a multimethod…)

    2) You don’t need the :else case in get-int-calc-tag – omitting it will return nil, which will map automatically to :default in the defmulti. You can actually rewrite this either way more simply as a “case” too:

    (case acct-type
    C :checking
    S :savings
    M :moneym)

    3) You don’t actually need get-int-calc-tag at all (but maybe you are just stepping towards something more complicated). Instead in the current impl, you could just switch on (:acct-type acct-info) and replace :checking with C (etc etc) in your defmethod impls.

    • Octopusgrabbus

      Thanks. I had intended to use the defmethod. Using your example, I had some ns reload issues, and code that looked like it should work didn’t with a zero args error. Now, it’s all working.

      So, far, your example is, for me, the best one I’ve found. Now, I’m understanding the others.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s