Last time, we saw “type declarations:” type
name =
type-expr
The simplest case that does introduces a new type and values is an enumerated union:
type
name
=
Value1
|
Value2
| ... |
Value𝓀
For example:
Introduces the new type size
, and three values that only belong to the type size: Tall
, Grande
, Venti
.
We can also use type
to declare a disjoint union type:
This declaration introduces new value constructors: Int
, Real
, and Complex
construct new values of type number
.
# let x = Int 2 ;;
val x : number = Int 2
# let y = Real 2.0 ;;
val y : number = Real 2.0
# let z = Complex (1.414, 1.414) ;;
val z : number = Complex (1.414, 1.414)
# let zeta = Complex 0.0 ;;
Value constructors are not functions but follow type constraints.
Computing with disjoint unions works similarly to lists and product types:
Define real_part
, imag_part : number -> float
type hostinfo
that is either a 4-tuple of int
s or a domain name (string
).
find_domains : hostinfo list -> hostinfo list
class_b_subnet : hostinfo -> int*int
Disjoint unions can also be parametric: e.g. what should imag_part
and class_b_subnet
do:
One possibility: the predefined option
type:
type 'a option = None | Some of 'a
val imag_part : number -> float option
cs2041.org