Haskell type classes: a compilation of laws

2017-11-01

This post is a reference for type classes’ laws. It will be expanded with time.


1 Functor

class Functor f where
  fmap :: (a -> b) -> f a -> f b

1.1 Laws


2 Applicative

class Functor f => Applicative f where
  pure :: a -> f a
  <*> :: f (a -> b) -> f a -> f b

An alternative definition could be:

class Functor f => Applicative f where
  pure :: a -> f a
  zip :: (f a, f b) -> f (a, b)

2.1 Laws

or:


3 Monad

class Applicative m => Monad m where
  (>>=) :: m a -> (a -> m b) -> m b

An alternative definition could be:

class Applicative m => Monad m where
  (>=>) :: (a -> m b) -> (b -> m c) -> (a -> m c)

3.1 Laws

or:


4 Alternative

class Applicative f => Alternative f where
  empty :: f a
  (<|>) :: f a -> f a -> f a

4.1 Laws

and:


5 Foldable

class Foldable f where
  foldMap :: Monoid m => (a -> m) -> f a -> m

5.1 Laws

There are no laws. However, when it is also a functor, it is expected that:

also, if t is monoid morphism, that is:

t mempty = mempty
t (a <> b) = t a <> t b

it is expected that:


6 Traversable

class (Functor t, Foldable t) => Traversable t where
  traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

6.1 Laws

Let t be an applicative transformation, that is:

t (pure a) = pure a
t (a <*> b) = t a <*> t b

then:

and: