Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What laws are the standard Haskell type classes expected to uphold?

It's well-known that Monad instances ought to follow the Monad laws. It's perhaps less well-known that Functor instances ought to follow the Functor laws. Nevertheless, I would feel fairly confident writing a GHC rewrite rule that optimizes fmap id == id.

What other standard classes have implicit laws? Does (==) have to be a true equivalence relation? Does Ord have to form a partial order? A total order? Can we at least assume it's transitive? Anti-symmetric?

These last few don't appear to be specified in the Haskell 2010 report nor would I feel confident writing rewrite rules taking advantage of them. Are there any common libraries which do, however? How pathological an instance can one write confidently?

Finally, assuming that there is a boundary for how pathological such an instance can be is there a standard, comprehensive resource for the laws that each type class instance must uphold?


As an example, how much trouble would I be in to define

newtype Doh = Doh Bool
instance Eq Doh where a == (Doh b) = b

is it merely hard to understand or will the compiler optimize incorrectly anywhere?

like image 247
J. Abrahamson Avatar asked Feb 13 '13 19:02

J. Abrahamson


1 Answers

The Haskell report mentions laws for:

  • Functor (e.g. fmap id == id)
  • Monad (e.g. m >>= return == m)
  • Integral (e.g. (x ‘quot‘ y)*y + (x ‘rem‘ y) == x)
  • Num (abs x * signum x == x)
  • Show (showsPrec d x r ++ s == showsPrec d x (r ++ s))
  • Ix (e.g. inRange (l,u) i == elem i (range (l,u)))

That is all I could find. Specifically, the section about Eq (6.3.1) mentions no laws, neither does the next one about Ord.

like image 56
David Avatar answered Sep 27 '22 18:09

David