liveBook · Manning

Type class

As explained in Learn Haskell by Example

A type class defines a set of operations and laws that types can implement to support ad hoc polymorphism.

A type class states which operations a type supports. It lets one function work across many types while still requiring the operations it needs. For example, equality is not assumed for every type: using `==` requires an `Eq` instance. section 5.1.3 section 1.1.1

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

Inspect `Eq` in GHCi to see a class declaration, its equality operations, and the minimal implementation required for an instance. section 5.1.3

A constraint narrows an otherwise polymorphic type. `member :: Eq a => a -> [(a, b)] -> Bool` says that keys may have any type `a`, provided values of that type can be compared. Without the constraint, the compiler cannot justify the use of `==`. section 5.1.2 section 5.1.3

Read a type-class-based design in three parts:

One conversion API for several pitch representations

`Pitchable` defines `toFrequency :: a -> Hz`. An `Hz` value converts with `id`; semitone distances calculate a frequency; chromatic notes first convert to semitones and then reuse that conversion. Callers use `toFrequency` without choosing a separate function for each representation. section 10.4.1

Type classes support practical extension points. A `Performer` class abstracts turning a performance into a signal so more noisemakers can be added later. The same pattern can generalize CSV operations and property-test input generation rather than hard-coding behavior for one data type. section 11.2.1 section 7.0 section 9.1.5

The terminology resembles object-oriented programming, but type classes are not objects to instantiate. Think instead in terms of declared operations, concrete instances, and constraints that make generic code safe to use. section 5.1.3

How Learn Haskell by Example covers it

How deep it goes
Defines classes, instances, and constraints through Eq, then builds custom conversion and performance abstractions.
Examples
Uses associative-list membership, pitch-to-frequency conversion, performance playback, and generic random property tests.
What it assumes
Introduces type classes from an equality-operator error while assuming basic Haskell functions and type signatures.
What you can do after
Build it from scratch by declaring capabilities, implementing instances, and constraining generic Haskell functions.
How it connects
Connects type classes with polymorphism, Eq, Semigroup, Monoid, property testing, and record-based CSV data.

Also explained in

Compare how 3 books explain type class →

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.