Typeclasses II, Batteries Included

Introduction

This page aims to highlight some of main typeclasses available in Prelude. The diagram below, from the 2010 Haskell report is a useful summary. Arrows from A to B indicate that B has a typeclass constraint of A.

Batteries included: Some common typeclasses

These typeclasses are all part of the Haskell 2010 standard. Note that the type hierarchy given there no longer exactly that in the GHC Prelude.

Eq

The Eq class defines equality (==) and inequality (/=). All basic datatypes in Prelude are instances of Eq.

Note that it suffices to define either (==) or (/=), but not both. The compiler can use the presence of one to compute the value of the other. For more on the properties of Eq, see here.

Ord

The Ord typeclass defines functions that compare values. Ordering can be represented in Haskell using the built-in type

The typeclass definition is below. Note the constraint Eq a - this allows us to use equality testing in the definition below.

Defining either compare or <= is sufficient for a minimal complete definition. See here for more properties.

Show

The typeclass Show handles conversion of values to readable Strings. This is the machinery used whenever we write deriving (Show) for custom types.

Defining either showsPrec or show is sufficient for a minimal completion definition. See here for more properties.

Enum

The typeclass Enum defines operations on sequentially ordered types. This is the typeclass used in Haskell’s translation of values like [n..m].

The default Prelude declaration is below.

It suffices to define toEnum and fromEnum for a complete definition. See here for more properties and documentation.

Num

The typeclass Num defines the basic numeric class. The default Prelude declaration is below.

For a minimal complete definition, we must define (+), (*), abs, signum, fromInteger, and negate (or (-)).

References