Skip to 0 minutes and 7 seconds WIM: Hello, everyone. In this short video, we are going to do a quick recap of type classes that you’ve seen in the previous lectures. So type classes are a way to restrict the polymorphism in types so that you can actually overload functions and operators in specific cases. This is called ad-hoc polymorphism. So let’s give a few examples. So the first example is of the addition operation.
Skip to 0 minutes and 40 seconds So the addition operation should work on any number types– should work on real types, on rational types, on integers. So we need some kind of type variable to express this. So we could write the signature as a type variable– so the operation takes something of type a– two elements and returns something of type a. But, of course, that’s not good enough because if a is not a number, it will not work. Similarly, if we have say smaller than– the less than operator– again, you could say, OK, it takes something of a certain type and something of the same type, and it returns a Boolean. So it indicates whether the comparison is true or false.
Skip to 1 minute and 27 seconds But again, that’s not good enough because, in general, types are not necessarily such that they can be compared to one another in a meaningful way. So in both cases, the way we solve this problem is by introducing type classes. So type classes are actually constructs that allow you to put constraints on the types without … you express that for instance, in this expression, a must be a number, and in this expression, a must be orderable. And the way we do that is we extend the syntax a little bit.
Skip to 2 minutes and 9 seconds So for instance, we say for addition given that a belongs to the Num type class, meaning a is a number, then we can write this valid signature.
Skip to 2 minutes and 27 seconds And the same for this one. Given that a belongs to Ord type class– that’s what this fat arrow means– then the following signature is valid.
Skip to 2 minutes and 46 seconds So these are practical examples of type classes. Other ones that you have seen are the Show and the Read type classes. What we are going to do in the next step is to look at how you can define type classes– how type classes are defined and how you can make your own.
Types with Class
Type classes are a way to overload functions or operators by putting constraints on polymorphism.
For example, we have seen that:
(+) :: a -> a -> a
is not OK because we want to restrict addition to numbers.
(<) :: a -> a -> Bool
is not OK because it is not clear a priori how to compare to arbitrary types.
To address this issue Haskell provides type classes. These restrict the polymorphism. For example:
(+) :: Num a => a -> a -> a
says that the type a must be a numeric type, and
(<) :: Ord a => a -> a -> Bool
says that a must be orderable.
© Wim Vanderbauwhede