type day_of_week = Sun | Mon | Tue | Wed | Thu | Fri | Sat (* Algebraic Data Types *) type int_or_float = Int of int | Float of float;; let i = Int 5;; let f = Float 3.14;; let l = [Int 5; Float 3.14];; let add1 (x: int_or_float) : int_or_float = match x with | Int i -> Int (i + 1) | Float a -> Float (a +. 1.0) ;; type intlist = | Nil | Cons of int * intlist ;; type 'a my_list = | MyNil | MyCons of 'a * 'a my_list ;; type int_or_float_list = | IFNil | ICons of int * int_or_float_list | FCons of float * int_or_float_list ;; (* Trees *) type 'a tree = | Leaf | Node of 'a * 'a tree * 'a tree ;; let rec insert (k: 'a) (t: 'a tree) : 'a tree = match t with | Leaf -> Node (k, Leaf, Leaf) | Node (k', l, r) -> if k > k' then Node (k', l, insert k r) else if k < k' then Node (k', insert k l, r) else t ;; let t1 = insert 42 Leaf;; let t2 = insert 56 t1;; let t3 = insert 20 t2;; let t4 = insert 47 t3;; let rec lookup (k: 'a) (t: 'a tree) : bool = match t with | Leaf -> false | Node (k', l, r) -> if k = k' then true else if k > k' then lookup k r else lookup k l ;; (* Higher-order functions *) let rec add1_to_all (l: int list) : int list = match l with | [] -> [] | h::t -> (h + 1)::(add1_to_all t) ;; let rec double_all (l: int list) : int list = match l with | [] -> [] | h::t -> (2 * h)::(double_all t) ;; let rec pair_all (l: 'a list) : ('a * 'a) list = match l with | [] -> [] | h::t -> (h, h)::(pair_all t) ;; let rec map (f: 'a -> 'b) (l: 'a list) : 'b list = match l with | [] -> [] | h::t -> (f h)::(map f t) ;; let add1_to_all l = map ((+) 1) l let add1_to_all = map ((+) 1);; let double_all = map (( *) 2);; let pair_all = let pair x = (x, x) in map pair ;; let pair_all = map (fun x -> (x, x));; let rec only_evens (l: int list) : int list = match l with | [] -> [] | h::t -> if h mod 2 = 0 then h::(only_evens t) else only_evens t ;; let rec only_odds (l: int list) : int list = match l with | [] -> [] | h::t -> if h mod 2 <> 0 then h::(only_odds t) else only_odds t ;; let rec only_not_empty (l: 'a list list) : 'a list list = match l with | [] -> [] | h::t -> if h <> [] then h::(only_not_empty t) else only_not_empty t ;; let rec filter (f: 'a -> bool) (l: 'a list) : 'a list = match l with | [] -> [] | h::t -> if f h then h::(filter f t) else filter f t ;; let only_odds = filter (fun x -> x mod 2 <> 0);;