Fun with Typeclasses

Posted on September 9, 2019 by Riccardo

I’ve recently started reading “Haskell in Depth”. The first part of the book covers the basics of the language. Here, among other cool things I’ve found an interesting example using two existing typeclasses (i.e. Enum, Bounded) and two new typeclasses that seem to make a lot of sense (i.e. BoundedEnum, CyclicEnum).

Let’s see that stuff in action. First of all, we need a type to play with:

The instance of Enum enables us to enumerate the values of type Direction. In other words, we can move to the next value or previous value by using succ and pred. Not only that, by making Direction enumerable, we can use the .. operator:

The instance Bounded allows us to generically call the lower-bound and upper-bound minBound and maxBound:

Now, in Haskell an Enum could be not Bounded and the other way around. In case a type is both, it makes sense to define a BoundedEnum typeclass and instance. That way, we can abstract the range [minBound .. maxBound]:

There is still a problem though. In fact, the following raises a runtime exception:

As a matter of fact, the enumeration does not wrap around and North is the first value in the enum! We can solve that by defining a CyclicEnum typeclass and instance: