This chapter covers:
- Exploiting type classes as tools for writing code that works for values of different types
- Type class as a concept applicable to many types
- Using basic type classes defined in the standard library
- Abstracting computations via type classes
Haskell programmers tend to write code that can be reused in many ways. To achieve that, they write code generically, by avoiding specific types. This is possible thanks to type classes.
Type classes are usually considered the most prominent Haskell feature. They originated in Haskell and were then taken up by other programming languages. A type class is defined with respect to some type variable. It contains a collection of methods, given by type signatures. It is possible to define as many instances, or implementations, for specific types as we need.
Writing functions with respect to a type class as opposed to using concrete types allows to be more generic: a function will work with different types even if they don’t exist at the time of declaring a type class. This makes type classes especially useful for libraries because we don’t know in advance which user-defined types are going to be used with our library.