Generalized ADT

Table of Contents

Generalized Algebraic Datatype
A GADT is an algebraic datatype whose data constructor whose constructors may return different and more specific instances of the type being defined.

A normal ADT like Maybe whose constructors always return the general form Maybe a. While with a GADT, constructors can determine the type parameter.

  {-# LANGUAGE GADTs #-}

  data Expr a where
    IntLiteral :: Int -> Expr Int
    BoolLiteral :: Bool -> Expr Bool
    Add :: Expr Int -> Expr Int -> Expr Int
    Equal :: Expr Int -> Expr Int -> Expr Bool
    If :: Expr Bool -> Expr a -> Expr a -> Expr a

Here, the type argument a denotes the result type.

1. GADT as Encapsulation: Existential Types

GADTs can hide an internal type while retaining operations available for it. For example,

  data SomeShow where
    SomeShow :: Show a => a -> SomeShow

This allows heterogenuous values. Moreover, it can hide concrete type.

  values :: [SomeShow]
  values = [ SomeShow 42, SomeShow True, SomeShow "Hello" ]

  render :: SomeShow -> String
  render (SomeShow x) = show x -- hides the concrete type of x

Date: 2026-07-31 Fri

Author: ArcaLunar