Clojure multi-methods

I consider myself neither a genius nor stupid. Somewhere in between my mind and determination have allowed me great freedom in learning new things. It comes about from a combination of Thomas Edison’s 99% perspiration along with some decent gray matter.

Learning Clojure has not been a cake walk — even though I enjoy using the cake build system — and I did not want it to be a snap. Of all the things to learn, accumulating final results using reduce, knowing when to use recursion, and so on, the most difficult thing for me to learn are multi-methods, the use of defmulti and defmethod.

I have most of the Clojure books. All of them are different offering a different approach to the language; and all of them are in my opinion well written. This topic remains elusive, but this post on Pure Danger is a start in the right direction, and it does show what I have suspected all along. The following is my non-official description of multi-methods, not an official language description.

You must construct the defmethods and the defmulti dispatch function and your input data in such a way that the parameter data becomes, in effect — tagged — with the dispatchable value. If this is wrong, it can be noted if anyone wants to comment. I don’t know why this has me stumped. I’ve gotten a lot of other concepts, but this one has me thrown out of orbit.

Advertisements

2 Comments

Filed under Clojure

2 responses to “Clojure multi-methods

  1. That’s a useful (but incomplete) thing to think about multimethods. Multimethod dispatch involves multiple steps:

    1. Evaluate the dispatch function in defmulti based on the args to the function. This produces a value (which could be a tag).

    2. Find the best “match” for the value. If the defmethod’s specify the exact value, then that’s the best match. If not, then the match can be made based on a multimethod hierarchy (lots more here: http://clojure.org/multimethods). If a value “matches” multiple possible defmethods, then you can use prefer-method to steer the answer. If nothing matches, use the :default method. This is all important because it allows for the equivalent of multiple inheritance OO polymorphism (and that’s a level of flexibility far beyond “tagging”). That said, I rarely see multimethods used with hierarchies.

    3. Invoke the selected method.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s