Skip to content

Standard Type Classes

Type classes are everywhere in Haskell code. That's a consequence of Haskell programmers' focus on writing reusable code. Where a C++ or Java programmer generally asks whether they have a good reason to make a function generic, the Haskell or Rust programmer will ask whether they have good reason not to make it generic or polymorphic. Since writing polymorphic functions in Haskell or Rust has virtually no syntactic overhead and polymorphism leads to more reusable code, we shy away from it only if, for example, the runtime overhead it entails kills the performance of our code.

As we discussed earlier, polymorphic functions that do not constrain their argument types in any way cannot do anything interesting with their arguments, as there are no functions which they can use to inspect these arguments. Thus, most interesting polymorphic functions require that their arguments are equality testable, can be ordered, support arithmetic operations, etc. These constraints are imposed using type classes.

Discussing all the standard type classes used throughout the standard library would lead us too far astray. We'll have a quick look at the most important ones here. We'll encounter a few more in subsequent chapters.

Here is a diagram that shows the relationships between the type classes we discuss here.

Hierarchy of standard type classes

Superclass-subclass relationships between different standard type classes