Fish Touching🐟🎣

OCaml Type

Jul 28, 2023

# Checking

(123 : int);;
- : int = 33

(33 : bool);;
Error: This expression has type int but an expression was expected of type bool

# int

# float

# char

# string

# type variable

# type variant

type t1 = C | D
type t2 = D | E
let x = D

type t = C1 [of t1] | ... | Cn [of tn]


type node = {value : int; next : mylist}
	and mylist = Nil | Node of node


type 'a mylist = Nil | Cons of 'a * 'a mylist

let rec length : 'a mylist -> int = function
  | Nil -> 0
  | Cons (_, t) -> 1 + length t

let empty : 'a mylist -> bool = function
  | Nil -> true
  | Cons _ -> false

Provide a type-safe way of doing something that might before have seemed impossible.
Variant types may mention their own name inside their own body

# Polymorphic Variants

  1. You don’t have declare their type or constructors before using them.
  2. There is no name for a polymorphic variant type. (So another name for this feature could have been “anonymous variants”.)
  3. The constructors of a polymorphic variant start with a backquote character.
let f = function
  | 0 -> `Infinity
  | 1 -> `Finite 1
  | n -> `Finite (-n)