These examples show two ways of constructing new types in OCaml: records and variant types.
(* C:\Documents and Settings\Default\Desktop\4651\examples\types.ml *)
(* a record type: specifies components *)
type color = {red: int; green: int; blue: int};;
let yellow = {red = 255; green = 255; blue = 0};;
let inverse c = {red = 255 - c.red; green = 255 - c.green; blue = 255 - c.blue};;
(* a function defined without pattern-matching *)
let isBlue c = if c.blue > 0 then true else false;;
isBlue yellow;;
isBlue (inverse (yellow));;
(* same function with pattern-matching *)
let isBlue = function
{red=r; green=g; blue=0} -> false
| _ -> true;;
isBlue yellow;;
isBlue (inverse (yellow));;
(* a variant type: specifies alternatives *)
type 'a list = Empty | Node of 'a * 'a list;;
let emptylist = Empty;;
let mylist = (Node (5, (Node (3, Empty))));;
let isEmpty = function
Empty -> true
| _ -> false;;
isEmpty emptylist;;
isEmpty mylist;;
let rec countList = function
Empty -> 0
| Node( _ , l) -> 1 + countList (l);;
countList Empty;;
countList mylist;;