Type classes

Contents
What a class is
deriving
Reading a constraint
Write an instance

What a class is

A type class is a set of functions that several types can implement. It is closer to an interface than to an object-oriented class: the type stays plain data, and behaviour is added from outside.

class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool instance Eq Bool where True == True = True False == False = True _ == _ = False

The four classes you meet first are Eq for equality, Ord for ordering, Show for printing, and Num for arithmetic.

deriving

For your own data types the compiler writes the boring instances. Ask for the ones you need and move on:

data Color = Red | Green | Blue deriving (Eq, Ord, Show) -- Red == Red True -- show Green "Green" -- Red < Blue True, by declaration order

The derived Ord follows the order of the constructors, which is rarely what a domain wants. Define compare by hand when the order is meaningful.

Reading a constraint

The part before the fat arrow restricts which types fit. It is a promise the caller must keep, not a conversion:

maximumOf :: Ord a => [a] -> a maximumOf = foldr1 max maximumOf [3,1,2] -- 3 -- maximumOf [True,False] works too

Read it as: for any type a that can be ordered, this takes a list of a and returns one a. Nothing about the body depends on knowing which type it is.

Write an instance

An instance for your own class needs the class first. A small one for describing values is a good exercise:

class Describe a where describe :: a -> String instance Describe Color where describe Red = "the color of blood" describe Green = "the color of grass" describe Blue = "the color of sky"

Every instance must cover every method without a default. That is the same exhaustiveness rule as a pattern match, applied one level up.

Next: Parametric polymorphism

Article author: Arthur Isaev

Related articles
Haskell
Haskell course: zero to hero in 50 lessons
What is Haskell and why it matters
Install the toolchain with GHCup
GHCi: the interactive shell
Your first program
Values with let and where
Types and type signatures
Functions and application
Currying and partial application
Operators, sections, and fixity
if, guards, and pattern guards
case expressions
Pattern matching
Tuples
Lists
Ranges and enumeration
List comprehensions
Recursion replaces loops
map, filter, and foldr
Lambdas and composition
Type classes
Parametric polymorphism
Maybe and null safety
Either and recoverable errors
data: product types
data: sum types
Records
newtype and type synonyms
Recursive data: binary trees
Functor
Applicative
Monad
do notation
IO and purity
Files and IO
Modules and imports
Cabal projects
Dependencies
Testing with HUnit
Property testing with QuickCheck
Laziness and infinite lists
Strictness and space leaks
Folds
Monoids
Traversable
Monad transformers
Errors and exceptions
Concurrency
Parsing with Megaparsec
Capstone: a todo CLI
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: