Exploring Multi-Methods in Clojure
Currently reading through the Joy of Clojure book I have recently been introduced to Clojure’s multi-method support. I decided that it would be interesting to see this feature in action, so I opened up LightTable and codified some example use-cases.
The implementation below carries on from were my article about FizzBuzz in Clojure left off.
Using the two documented
buzz? helpers, followed by the
juxt core function we are able to codify the problem in a highly descriptive manner.
We are also able to use multi-methods in a similar manner to pattern-matching found in languages such as Scala and Haskell.
The below implementation recursively computes the supplied arguments factorial value, handling the base-case of 0 using the function
identity as the dispatch call.
We are able to expand upon the rules based approach laid out in the previous examples by documenting the Rock-Paper-Scissors game in code. Using this multi-method allows us to compute all the possible winning-moves for both players.
Odd or Even
Finally we can use the core
odd? function to polymorphically return a string depicting the supplied values odd-even status.