liveBook · Manning

Type constraint

As explained in Learn Haskell by Example

Constraint is the Haskell kind-level type representing a type-class constraint.

A type constraint limits a polymorphic type to values supporting a required type-class interface. Writing `Eq a =>` allows a function to use equality on `a`. section 5.1.3

Use constraints when a function depends on operations supplied by a type class:

  • Declare `member :: Eq a => a -> [(a, b)] -> Bool` because checking a key with `(==)` requires `Eq a`. section 5.1.4
  • Omit the constraint when the type is explicit, because a concrete type such as `Int` already determines its available instance. section 5.1.3
  • Propagate constraints through helper functions: `hasNode :: Eq a => DiGraph a -> a -> Bool` uses the same equality requirement. section 5.1.4

Checking membership in an associative list

The recursive `member` function returns `True` when a key matches with `(==)` and otherwise continues through the list. Its `Eq a` constraint prevents calls with types that cannot be compared for equality. section 5.1.4

ghci> :info Eq
type Eq :: * -> Constraint
class Eq a where
  (==) :: a -> a -> Bool
  (/=) :: a -> a -> Bool
  {-# MINIMAL (==) | (/=) #-}

Inspecting `Eq` in GHCi shows `Constraint` as the kind of type-class constraints and exposes the class operations. section 5.1.3

At the kind level, `Constraint` represents a requirement such as `Eq a` or `Functor f`, rather than an ordinary value-producing type. Thus `Functor []` is a constraint and cannot define a data field. section 8.2.3

How Learn Haskell by Example covers it

How deep it goes
Defines constraints through Eq signatures and kind-level Constraint, but does not descend into compiler implementation internals.
Examples
Uses equality-based associative-list membership and GHCi inspections of Eq, Functor, and type and kind signatures.
What you can do after
Diagnose type errors, write accurate polymorphic signatures, and inspect unfamiliar constraints with GHCi.
How it connects
Connects type constraints with type classes, Eq, Functor, polymorphism, and kinds.

Also explained in

Compare how 6 books explain type constraint →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.