Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 57 ยท Defining types

Defining Your Own Type Classes and Instances

Learn to declare a Haskell type class, write instances, use default methods and deriving, and avoid orphan instances, with a runnable JavaScript stand-in.

You have already used type classes such as Eq, Ord and Show. A type class names a set of operations, and an instance says how a particular type provides them. Writing your own classes lets you define a shared interface once and implement it for many types, without inheritance and without touching the types themselves.

This lesson shows the syntax for class and instance, default methods, deriving, and a few rules that keep large programs sane. It assumes you know Parametric Polymorphism and Type Variables and Type Classes: Eq, Ord, Show, Read, Num.

Haskell is not run on this site, so the Haskell code is read-only. JavaScript stand-ins imitate the idea with explicit "instance" objects.

Declaring a class

A class declaration lists method signatures. The type variable (here a) stands for any type that will become an instance:

HASKELL
class Shape a where
  area      :: a -> Double
  perimeter :: a -> Double
  describe  :: a -> String

Now define some types and make them instances:

HASKELL
data Circle = Circle Double
data Rect   = Rect Double Double

instance Shape Circle where
  area (Circle r)      = pi * r * r
  perimeter (Circle r) = 2 * pi * r
  describe c           = "circle with area " ++ show (area c)

instance Shape Rect where
  area (Rect w h)      = w * h
  perimeter (Rect w h) = 2 * (w + h)
  describe r           = "rectangle with area " ++ show (area r)

Calling area (Circle 1.0) picks the Circle implementation, and area (Rect 2 3) the Rect one. The compiler decides from the argument's type. A function can be generic over any shape by using a constraint:

HASKELL
totalArea2 :: (Shape a, Shape b) => a -> b -> Double
totalArea2 x y = area x + area y

Class and instance

class Names the operations and their types.
instance Gives the code for one type.
Constraint Shape a => ... accepts only types with an instance.
1 / 2

A class is not a type. You cannot write a list of "any Shape" directly, because [Shape] makes no sense: Shape is a constraint, not a type. If you need a mixed collection, define a sum type (data AnyShape = C Circle | R Rect) or use an existential type (an advanced extension).

Default methods and minimal definitions

A class can supply default implementations written in terms of other methods. Instances then only need to define what is missing. This is how Eq works: it defines == and /= in terms of each other, so you provide either one.

HASKELL
class Container f where
  empty  :: f a
  insert :: a -> f a -> f a
  toL    :: f a -> [a]

  size :: f a -> Int
  size = length . toL          -- default, built from toL

Here f is not a plain type but a type constructor (it takes an argument, like [] or Maybe). Classes over constructors are common; Functor and Monad are the famous ones.

HASKELL
newtype Stack a = Stack [a]

instance Container Stack where
  empty                 = Stack []
  insert x (Stack xs)   = Stack (x : xs)
  toL (Stack xs)        = xs
  -- size comes from the default

Instances may override a default if they can do better, for example size (Stack xs) = length xs is the same here, but a balanced tree could store its size.

GHC documents what you must define with a # MINIMAL ... # pragma, and warns (with -Wall) when an instance misses a required method. Leaving out a method that has no default compiles but crashes at runtime if called, so heed the warning.

An instance with a missing method is only a warning, not an error. Compile with -Wall and treat "No explicit implementation for ..." as a bug.

Superclasses and constrained instances

A class may require another. Ord has Eq as a superclass, so every Ord type must also be Eq:

HASKELL
class Shape a => Solid a where
  volume :: a -> Double

An instance can also depend on instances of its parts. This is how Show for lists works: a list is showable if its elements are.

HASKELL
data Pair a = Pair a a

instance Show a => Show (Pair a) where
  show (Pair x y) = "<" ++ show x ++ ", " ++ show y ++ ">"

Read Show a => Show (Pair a) as "to show a Pair a, we need to be able to show an a."

deriving

Writing boring instances by hand is tedious, so GHC can generate them with deriving:

HASKELL
data Color = Red | Green | Blue
  deriving (Eq, Ord, Show, Read, Enum, Bounded)

You can derive Eq, Ord, Show, Read, Enum and Bounded out of the box. With extensions, more classes are available: Functor, Foldable and Traversable via DeriveFunctor and friends, Generic, and others. Derived Ord compares constructors in declaration order, so Red < Green < Blue here. Derived Show prints constructor names and fields as Haskell syntax.

Derive when the automatic behaviour is what you want; write the instance by hand when the meaning is special. For example, you might compare Version records by their numbers only, not by every field.

A word on DerivingVia

Sometimes a newtype should behave like an existing type's instance. GeneralizedNewtypeDeriving reuses the underlying type's instance, and the newer DerivingVia goes further: you name which type's instance to borrow.

HASKELL
# LANGUAGE DerivingVia #
import Data.Monoid (Sum (..))

newtype Score = Score Int
  deriving (Semigroup, Monoid) via (Sum Int)

Now Score 3 <> Score 4 adds the numbers because it borrows the behaviour of Sum Int. You will meet Sum in Semigroups and Monoids. Treat this as a taste; it is not needed for everyday code.

Coherence and orphan instances

Haskell requires that for each class and type there is at most one instance in the whole program. This property is called coherence. It lets the compiler choose an instance without ambiguity, and it is why there is no way to say "use this other Ord Int just here". When you need a different ordering, wrap the value in a newtype (the standard library provides Down for reverse order).

An orphan instance is an instance defined in a module that owns neither the class nor the type. For example, defining instance Show (a -> b) in your own code. It works, but two libraries could define the same orphan, and then they cannot be combined. GHC warns about orphans with -Worphans. The usual guidance:

  • Put an instance next to the class or next to the type.
  • If you own neither, create a newtype wrapper and give that the instance.

Also remember that instance declarations are global: importing a module brings its instances into scope, and you cannot hide them.

A stand-in: classes as dictionaries

Compilers implement classes by passing a dictionary, a record of the methods, to constrained functions. We can mimic that in JavaScript by passing an instance object by hand. This is a stand-in for the idea, not how GHC syntax looks.

JS Shape class with two instances (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A second stand-in shows a default method and an instance override. Eq defines /= from ==:

JS Default methods (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an instance declaration do?

    An instance supplies the method definitions for a specific type; types do not inherit from each other in Haskell.
  2. 2. Why can you not write a type [Shape] for a class Shape?

    Shape a => ... constrains a type variable. For mixed collections use a sum type or an existential type.
  3. 3. What is an orphan instance?

    Orphans can clash between libraries; prefer placing the instance with the class or type, or use a newtype wrapper.
  4. 4. In class Eq, why do instances usually define only one of == and /=?

    Each has a default definition in terms of the other, so providing one is enough (a MINIMAL pragma records that).
  5. 5. How does Haskell avoid ambiguity about which instance to use?

    Coherence means the compiler can pick the single instance from the type alone. A newtype gives a different behaviour.

Summary

  • A class declares method signatures; an instance implements them for a type.
  • Default methods let an instance define only the essential operations; compile with -Wall to catch missing ones.
  • Superclasses (class Eq a => Ord a) and constrained instances (Show a => Show (Pair a)) build on each other.
  • deriving generates standard instances; DerivingVia borrows another type's instance for a newtype.
  • There is one instance per class and type; avoid orphan instances and use a newtype for alternative behaviour.
  • A class is a constraint, not a type, so mixed collections need a sum type.

Next: Lazy Evaluation.