Skip to main content

Work with standard typeclass

  • A typeclass is a sort of interface that defines some behavior
    • like comparing for equality, comparing for ordering, or shown in console.
  • If a type has an instance of a typeclass, that means
    • it supports and implements the behavior the typeclass describes
    • and we can use the functions that the typeclass defines with that type.

📌 You can think of them kind of as Java interfaces, not class.

standard typeclasses definition​

Let's start from the standard (or built-in) typeclasses Eq provided by PureScript.

> :type (==)
forall (@a :: Type). Eq a => a -> a -> Boolean

We can read it as: the == function takes any two values that are of the same type and returns a Bool. The type of those two values must be a member of the Eq typeclass. This is how the typeclass Eq is defined in PureScript:

class Eq a where
eq :: a -> a -> Boolean
  • class Eq a where: means that we're defining a new typeclass and it's called Eq.
  • The a is the type variable, and we will make it an instance of Eq (type a has an instance of typeclass Eq).

make instances of typeclass​

We can make instance of typeclass by deriving or by our own hand.

make instance by derive​

We can make our own types instances of the standard typeclasses by asking compiler to derive the instances for us. Let's make our own data type TrafficLight as an instance of typeclass Eq:

data TrafficLight = Red | Yellow | Green
derive instance Eq TrafficLight

Import and run it in REPL:

> Green == Red
false

> Green == Green
true

We can also give the name to the typeclass instance:

derive instance eqTrafficLight :: Eq TrafficLight

Currently, instances for the following classes can be derived by the compiler:

  • Data.Generic.Rep (class Generic) see below
  • Data.Eq (class Eq)
  • Data.Ord (class Ord)
  • Data.Functor (class Functor)
  • Data.Newtype (class Newtype)

Reference: Type Class Deriving

make instance by hand​

As the typeclass Show is not supported with derive by the comparing, so we have to make instances by ourselves:

instance Show TrafficLight where
show Red = "Red light"
show Yellow = "Yellow light"
show Green = "Green light"

Import and run it in REPL:

> Red
Red light

> Green
Green light