🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Multi-Parameter Typeclasses

A multi-parameter typeclass is a typeclass that takes two types instead of one. It lets one class describe a relation between a pair of types.

One class can take two types

Pair relates two types. Its method takes a pair and returns the first part.

{-# LANGUAGE MultiParamTypeClasses #-}
class Pair a b where
  firstOf :: (a, b) -> a
instance Pair Int String where
  firstOf (x, _) = x
main :: IO ()
main = print (firstOf ((5 :: Int), "x"))

A class can offer both parts of a pair

Adding secondOf completes the pair. Each method returns one part.

{-# LANGUAGE MultiParamTypeClasses #-}
class Pair a b where
  firstOf :: (a, b) -> a
  secondOf :: (a, b) -> b
instance Pair Int Bool where
  firstOf (x, _) = x
  secondOf (_, y) = y
main :: IO ()
main = print (firstOf ((3 :: Int), True), secondOf ((3 :: Int), True))

Different instances cover different type pairs

One instance covers Int and String. Another covers Int and Bool, and each pair uses its own instance.

{-# LANGUAGE MultiParamTypeClasses #-}
class Pair a b where
  firstOf :: (a, b) -> a
instance Pair Int String where
  firstOf (x, _) = x
instance Pair Int Bool where
  firstOf (x, _) = x
main :: IO ()
main = print (firstOf ((5 :: Int), "x"), firstOf ((7 :: Int), True))

Example

{-# LANGUAGE MultiParamTypeClasses #-}
class Pair a b where
  firstOf :: (a, b) -> a
  secondOf :: (a, b) -> b
instance Pair Int String where
  firstOf (x, _) = x
  secondOf (_, y) = y
instance Pair String Int where
  firstOf (x, _) = x
  secondOf (_, y) = y
main :: IO ()
main = do
  print (firstOf ((5 :: Int), "x"), secondOf ((5 :: Int), "x"))
  print (firstOf ("hi", (7 :: Int)), secondOf ("hi", (7 :: Int)))

Key points

  • Multi-parameter class: a class with two type variables, such as Pair a b.
  • Pragma: a special line at the very top of the code that turns on an extra language feature.
  • Instance: an instance fixes both type variables, such as Int and String.
  • Method: firstOf takes a pair and returns its first part.
  • Two instances: the same class can have one instance for Int and String and another for Int and Bool.

In this example, Pair offers firstOf and secondOf for any two types. The Int and String instance handles a number with text, and the String and Int instance handles text with a number. Each print shows both parts of its pair in order.

Note

GHC needs the pragma because a plain class takes only one type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which line must appear at the very top of a file that defines a multi-parameter class?