Classes in Haskell (hint they’re more like interfaces)

A class (also know as typeclass) in Haskell is more analogous to an interfaces in C# and Java.

Let’s look at a simple class which will supply a toString function

class ToString a where 
  toString :: a -> String

This class allows us to use a toString function on different types. So think of this as an interface where data types that support it will now work with the toString function.

Let’s just create a simple data type as an example

data Point = Point { x :: Integer, y :: Integer }

Now it’d be cool if we could use code such as print (toString pt) and have the output a string like this “X:1, Y:2”. All we need to do is create an instance of the class. Before we do this, we’re going to need to also support converting of an Integer (as it’s used in the Point) to a string, so we may as well create an instance of the ToString class for Integer’s first and then use this code in our Point instance

instance ToString Integer where    
    toString i = show i

So now we’ve got a ToString to handle Integer’s we can combine to create an instance for a Point, like this

instance ToString Point where    
    toString pt = "X:" ++ toString (x pt) ++ ", " ++ "Y:" ++ toString (y pt)