£199.99 £139.99 for one year of Unlimited learning. Offer ends on 28 February 2023 at 23:59 (UTC). T&Cs apply

# Types with Class

Type classes are a way to overload functions or operators by putting constraints on polymorphism
7.1
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.
39.7
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.
87.3
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.
129.2
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.
146.7
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.
165.5
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.

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.

Likewise,

 (<) :: 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.