Type Classes
Earlier in this book, you learned about a type of polymorphism called parametric polymorphism that allows you to write a single implementation of a function that can work with many different types using type variables. This style of polymorphism is when you are concerned with data structures and the shape of the data you are working with, but don’t need to directly inspect values. Unfortunately, parametric polymorphism falls short when we need to deal with the polymorphic values in a non-generic way. As soon as we need to carry out specific operations on a polymorphic value, we run into the problem that our operations depend on what type the value happens to be.
Object-oriented programming languages let you solve this problem using inheritance or interfaces to write different implementations of functions depending on their type. The idea that we can provide a different implementation of a function depending on its type is called ad hoc polymorphism . Haskell provides its own approach to ad hoc polymorphism with type classes .
In this chapter, you will learn more about the limitations of parametric polymorphism and how to use type classes to write more expressive interfaces and how to build polymorphic functions that behave differently based on the type of their inputs. You will also learn to use Haskell’s powerful deriving mechanism to get the benefit of ad hoc polymorphism without needing to write boilerplate code.