liveBook · Manning

ExistentialQuantification

As explained in Learn Haskell by Example

An existentially quantified type variable is a type variable whose concrete type is hidden inside a packaged value.

Existential quantification hides a concrete type parameter inside a value. The outside type stays fixed, so values containing different concrete types can share one heterogeneous data structure. section 11.1.1 section 11.4

Packaging values of different types

With ExistentialQuantification enabled, `data E = forall a. MkE a` gives `MkE :: a -> E`. Both `MkE (1 :: Int)` and `MkE (1 :: Float)` have type `E`, allowing `[MkE (1 :: Int), MkE (2 :: Float)] :: [E]`. section 11.1.1

Hiding the type also prevents unrestricted extraction: an `E` value does not reveal what its hidden type is. Add a constraint when every packaged value must support a shared operation, such as `Show`. section 11.1.1

A constrained existential

`data ShowData = forall a. Show a => ShowThis a` packages values such as `Int` and `String`; `showThis` can safely apply `show` to either one. section 11.1.1

Listing 13.6 The definition of a dynamic data type for PNM images
{-# LANGUAGE ExistentialQuantification #-}  #1

...

data DynamicPnmImage = forall px.
 DynamicPnmImage (PnmImage px)  #2

A dynamic PNM image packages `PnmImage px` while hiding `px`; matching the GADT constructor later refines the stored image type. section 13.1.4

How Learn Haskell by Example covers it

How deep it goes
Explains packaging, inaccessible type recovery, class constraints, and GADT-based recovery, but stops short of broader type-system formalism.
Examples
Uses `E`, `ShowData`, heterogeneous lists, and `DynamicPnmImage` to demonstrate packaging and later interpretation.
What it assumes
Assumes basic algebraic data types, polymorphic type variables, lists, type classes, and GADT constructor matching.
What you can do after
Build heterogeneous containers and safely operate on packaged values through constraints or GADT pattern matching.
How it connects
Connects heterogeneous lists, type classes, type constraints, GADTs, dynamic types, and return-type polymorphism.

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.