Lesson 13. Type classes
After reading lesson 13, you’ll be able to
- Understand the basics of type classes
- Read type class definitions
- Use common type classes: Num, Show, Eq, Ord, and Bounded
In this lesson, you’re going to look an important abstraction in Haskell’s type system: type classes. Type classes allow you to group types based on shared behavior. At first glance, type classes are similar to interfaces in most object-oriented programming languages. A type class states which functions a type must support in the same way that an interface specifies which methods a class must support. But type classes play a much more important role in Haskell than interfaces do in languages such as Java and C#. The major difference is that as you dive deeper into Haskell, you’ll see that type classes typically require you to think in increasingly more powerful forms of abstraction. In many ways, type classes are the heart of Haskell programming.
Consider this
You’ve written the function inc to increment a value a few times as a sample function. But how can you write an incrementing function that works with the wide range of possible numbers you’ve seen? Frustratingly enough, in unit 1, without specifying types, you could do this. How can you write the type signature of an inc function that works on all numbers?