liveBook · Manning

Generalized algebraic data type

As explained in Learn Haskell by Example

A generalized algebraic data type allows data constructors to specify more precise type information than ordinary algebraic data types.

A generalized algebraic data type (GADT) is an algebraic data type whose constructors can refine the type parameter to a concrete type. Ordinary constructors may all produce MyGADT a, while GADT constructors can produce MyGADT Bool or MyGADT String. Enable the feature with the GADTs language extension. section 13.1.2

GADTs become useful when a function must remain polymorphic while recovering precise type information:

  • Define constructors with precise result types, allowing pattern matching to refine a polymorphic parameter. section 13.1.2
  • Return values whose types follow from the matched constructor, as with giveMe :: GiveMe a -> a. section 13.1.2
  • Pair a GADT with existential quantification when a container must hide its type parameter while retaining recoverable type information. section 13.1.4

Typed image representations

An Image px GADT stores either 8-bit or 16-bit pixels while recording the pixel type in its result: Image8Bit produces Image P.PixelRGB8, and Image16Bit produces Image P.PixelRGB16. A conversion function can pattern-match safely, transform 8-bit pixels, and leave an already 16-bit image unchanged.

How Learn Haskell by Example covers it

How deep it goes
Explains syntax, constructor-driven refinement, pattern matching, and existential composition, stopping short of broader implementation internals.
Examples
Demonstrates GiveMe values, typed PNM images, and conversion from 8-bit to 16-bit pixels.
What it assumes
Assumes ordinary algebraic data types and polymorphism, then teaches constructor-based type refinement through small examples.
What you can do after
Build it from scratch using GADTs to write type-safe polymorphic functions and dynamically store typed image values.
How it connects
Connects GADTs to algebraic data types, type classes, parametric polymorphism, return-type polymorphism, and existential quantification.

Also explained in

Compare how 2 books explain generalized algebraic data type →

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.