🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Custom Typeclasses

A custom typeclass is a new class that you define for your own types. It names the methods that each instance must provide.

A custom class names one method

Greet names a single method. An instance for Name defines it.

class Greet a where
  greet :: a -> String
data Name = Name String
instance Greet Name where
  greet (Name n) = "Hello " ++ n
main :: IO ()
main = print (greet (Name "Ana"))

One class can serve two types

Name and Pet are different types. Each gets its own Greet instance.

class Greet a where
  greet :: a -> String
data Name = Name String
data Pet = Pet String
instance Greet Name where
  greet (Name n) = "Hello " ++ n
instance Greet Pet where
  greet (Pet n) = "Hello " ++ n
main :: IO ()
main = do
  print (greet (Name "Ana"))
  print (greet (Pet "Bo"))

MINIMAL names the methods an instance must supply

Loud has two methods but its minimal set is one of them. Defining shout alone is enough for this instance.

class Loud a where
  shout :: a -> String
  whisper :: a -> String
  {-# MINIMAL shout | whisper #-}
data Bell = Bell
instance Loud Bell where
  shout _ = "DING"
main :: IO ()
main = print (shout Bell)

Example

class Animal a where
  sound :: a -> String
  name :: a -> String
data Dog = Dog
data Cat = Cat
instance Animal Dog where
  sound _ = "woof"
  name _ = "Rex"
instance Animal Cat where
  sound _ = "meow"
  name _ = "Mia"
main :: IO ()
main = do
  print (name Dog, sound Dog)
  print (name Cat, sound Cat)

Key points

  • Custom class: a class definition that names methods and their types.
  • Method: a function declared in the class and defined in each instance.
  • Instance: a definition that gives the methods for one specific type.
  • Minimal set: the smallest group of methods an instance must define.
  • MINIMAL note: a note on a class that names its minimal set.

In this example, Animal names sound and name for any animal type. Dog and Cat each give both methods, and each print shows one animal name with its sound.

Note

a class can have instances for your own types and for existing types alike.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does a MINIMAL note on a custom class name?