Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how and why is defmulti and defmethod used? and what are the advantages?

Tags:

I would like to know why defmulti & defmethod are used? What are the advantages? And how do you use it? Please explain what is happening in the code.

like image 884
Phil Avatar asked Oct 13 '12 11:10

Phil


1 Answers

In "general terms" you would call it a if/else on steroids and in "impress me" style you would name it with "dynamic dispatch", "runtime polymorphism" etc.

Lets say you want to define a function "Add" which should work for various data types like in case of Int it should add the numbers, in case of strings it should concat the strings. Now it is very simple to implement it using if else, basically you check the type of arguments and if they are integers then add them, if they are strings then concat them else throw exception. But the problem with this is that in case you want to add support for new data type in your Add function you will need to modify the Add function, which may not be possible in cases where you don't control the source of Add such as the case it is defined in some library etc. defmulti and defmethod allows you to solve this problem i.e adding a new case to existing function without modifying its code.

(defmulti add (fn [a b] [(type a) (type b)]))

add is the function name, the anonymous function is your if/else, basically this will be called on your add arguments and the return value of this function will be checked if there is any implementation. Now lets implement it for Integer.

(defmethod add [Integer Integer] ([a b] (+ a b)))

[Integer Integer] is sort switch case on the return value of the anonymous function we defined in defmulti and then the implementation.

Similarly we can do for strings

(defmethod add [String String] ([a b] (str a b)))

Calling it with integers (add (int 1) (int 2))

Calling it with strings (add "hello" "world")

Calling it with something that doesn't match our if/else i.e not implementation yet for a case will result in an exception

like image 117
Ankur Avatar answered Oct 10 '22 21:10

Ankur