What is "polymorphism a la carte" and how can I benefit from it?

In his talk Simple Made Easy, Rick Hickey talks about "Polymorphism a la carte" (about 30:00 into the video). In the same context, he also mentions Haskell's Type Classes and Clojure's Multi-Methods (and protocols).

Since I am not very familiar with these concepts, I would like to understand its usefulness when trying to achieve simplicity. I am particularly interested in any examples or showcases of this concept in Scala.


Solution 1:

You can take Polymorphism a la carte as Polymorphism on demand.

Clojure community are proud of the term Polymorphism a la carte because of the fact that Clojure support multiple polymorphism strategies. Some of them are:

  • Prototype-based polymorphism

  • Inheritance polymorphism

    This is the polymorphism strategy used by Java. Clojure support this by proxy. Useful when doing Java interop.

  • Protocol

    Protocol to Clojure is as TypeClass to Haskell.

  • Multimethod

    While protocols provide polymorphic dispatch based on the type of the first argument, multimethods are much more flexible which can dispatch based on any function of the method's (any) arguments.

Polymorphism a la carte means "Select whatever polymorphism strategy best for your case. They're all in your toolbox."

You can implement TypeClass pattern in Scala using implicits. Read Scalaz source if you want real world examples. Scala does not support multimethods at language level, but I guess it is possible with the help of the upcoming 2.10 macro.

As for the benefits, advanced polymorphism strategies such as TypeClass and Multimethod can help solve the Expression Problem.

"The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts)".

BTW, this question is too big to fit into a single StackOverflow question. My suggestion is to get familiar with these concepts, and then you'll understand their usefulness.