Algebraic Data Types

OCaml Types

Uninhabited/ Empty types

#type zero;;

Unit type

  # ();;
  - : unit = ()
# type one = Unit;;
- : type one = Unit

Boolean

# type two = Left | Right
- : type two = Left | Right

Variant Types

# type weekday = Monday | Tuesday | Wednesday | Thursday | Friday ;;
- : type weekday = Monday | Tuesday | Wednesday | Thursday | Friday
# let next_day = function
  |Monday -> Tuesday
  |Tuesday ->Wednesday
  |Wednesday -> Thursday
  |Thursday -> Friday
  |Friday -> Monday;;

- : val next_day : weekday -> weekday = <fun>
# next_day Monday;;
- : weekday = Tuesday

Product types

-: (1,'a') : int * char
-: (True, Monday) : bool * weekday

Option Type

# type 'a option = None | Some of 'a;;

Sum Type

# type ('a, 'b)sum = Left of 'a | Right of 'b;;

Exponential Types

Type isomorphism

g(f(x))=x(gf)x=x`g(f(x)) = x \equiv (g \circ f)x = x`

Equations

1+1=2`1+1 =2`
is equivalent to
(Unit,Unit)sumbool`(Unit, Unit)sum \simeq bool`

# let f = (function
| Left () -> true
| Right () -> false)

# let g = (function
| true -> Left ()
| false -> Right ())

Algebra Proposition Type Constructor Destructor (pattern)
0`0` `\bot` empty None language-dependent
1`1` `\top` unit () ()
a×b`a\times b` AB`A\land B` 'a * 'b (a, b) match (a, b) with ...
a+b`a+b` AB`A\vee B` ('a, 'b)sum Left a, Right b match ... with Left a -> ... | Right b -> ...
ba`b^a` ab`a\supset b` 'a->'b fun x -> ... function application