type suit = Club | Diamond | Heart | Spade
type rank = Jack | Queen | King
| Ace | Num of int
let two_clubs : suit*rank = (Club, Num 2)
type card = suit*rank
let two_clubs' : card = (Club, Num 2)
let rec zip3 lists =
match lists with
([],[],[]) -> []
| (hd1::tl1,hd2::tl2,hd3::tl3) ->
(hd1,hd2,hd3)::zip3(tl1,tl2,tl3)
| _ -> raise (Failure "List length mismatch")
let rec unzip3 triples =
match triples with
[] -> ([],[],[])
| (a,b,c)::tl ->
let (l1, l2, l3) = unzip3 tl
in (a::l1,b::l2,c::l3)
(* Pattern matching *)
let e = 42+3110
(*If p is a variable x, the match succeeds and x is bound to v*)
match e with
x -> x
(* If p is _, the match succeeds and no bindings are introduced *)
match e with
_ -> 007
(* If p is a constant c, the match succeeds if v is c.
No bindings are introduced. *)
match e with
3152 -> true
| _ -> false
let c = Club
(* If p is C, the match succeeds if v is C. No bindings are introduced. *)
match c with
Club -> 1
| Diamond -> 2
| Heart -> 3
| Spade -> 4
let two = Num 2
(* If p is C p1, the match succeeds if v is C v1 (i.e., the same
constructor) and p1 matches v1. The bindings are the bindings
from the sub-match. *)
match two with
Num x -> x
| Ace -> 13
| King -> 12
| Queen -> 11
| Jack -> 10
(* If p is (p1,..., pn) and v is (v1,..., vn), the match succeeds
if p1 matches v1, and ..., and pn matches vn. The bindings are
the union of all bindings from the sub-matches. *)
match (c,two) with
(Club, Num x) -> x
| _ -> 0
type student = {name:string; age:int}
let mrc26={name="Michael Clarkson"; age=36}
(* If p is {f1=p1; ...; fn=pn} and v is {f1=v1; ...; fn=vn}, the
match succeeds if p1 matches v1, and ..., and pn matches vn.
The bindings are the union of all bindings from the sub-matches. *)
match mrc26 with
{age=36;name=n} -> n
| {name="Michael Clarkson";age=a} -> string_of_int a
| _ -> ""
type my_int_list = Nil
| Cons of int * my_int_list
let x = Cons(4,Cons(23,Cons(2008,Nil)))
let rec my_append (xs:my_int_list) (ys:my_int_list) =
match xs with
Nil -> ys
| Cons(x,xs') -> Cons(x, my_append xs' ys)