Record

References: CS3110 - Records and Tuples CS3110 - Advanced Pattern Matching

Records allow multiple named types to be stored in a single datatype.

Setup

1type ptype = TNormal | TFire | TWater;;
2type mon = {name : string; hp : int; ptype : ptype };;

Assign

1let charmander = { name = "Charmander"; hp = 30; ptype = TFire };;

Copy

1let c = {name = "C"; hp = charmander.hp; ptype = charmander.ptype };;

Getter

1let get_hp m = match m with {name = _; hp = h; ptype = _} -> h;;

…or…

1let get_hp m = match m with {hp = h} -> h;;

…or…

1let get_hp m = m.hp;

Pattern Matching with Let

1let {name = n; hp = h; ptype = p} = charmander;;
val n : string = "Charmander"
val h : int = 30
val p : ptype = TFire

Pattern Matching with Match

1let get_hp m = 
2match m with
3| {name = _; hp = h; ptype = _ } -> h;;
4
5get_hp charmander;;
- : int = 30