((* CS:3820, Fall 2016 *) (* Cesare Tinelli *) (* The University of Iowa *) (* F# examples seen in class *) type ilist = E | L of int * ilist let l = L(1, L(2, L(3, E))) let head l = match l with | E -> failwith "list is empty!" | L(h, _) -> h let tail l = match l with | E -> failwith "list is empty!" | L(_, t) -> t let rec last l = match l with | E -> failwith "list is empty!" | L(h, E) -> h | L(h, t) -> last t type 'a list = E | L of 'a * 'a list let l1 = L(1, L(2, E)) let l2 = L("a", L("b", E)) let id x = x id 5 id 3.3 let toTriple x y z = (x, y, z) // forces first two parameters to be of the same type let toTriple (x:'a) (y:'a) (z:'b) = (x, y, z) let equal x y = (x = y) let distinct x y = not (x = y) (* Lists *) [] [3;5;6;3] ["dd"; "sdf"] [(1,2); (1,4)] [[3;1]; []; [4;5;6]] (* [3; "sdf"] *) [6] 6::[] 6 :: [] 5::(6::[]) 5::6::[] (* 5::6 *) List.head [1;2;3] List.tail [1;2;3] let (h :: t) = [1;2;3] let (h :: t) = (1 :: (2 :: (3 :: []))) let rec len l = match l with [] -> 0 | _ :: t -> 1 + (len t) len [2;5;1] len ["a";"b"] let rec len l = match l with [] -> 0 | _ :: t -> 1 + (len t) (* len (1 :: 2 :: 3 :: []) --> 1 + len (2 :: 3 :: []) --> 1 + 1 + len (3 :: []) --> 1 + 1 + 1 + len [] --> 1 + 1 + 1 + 0 --> 3 *) let rec min l = match l with [] -> failwith "Empty list!" | n :: [] -> n | n1 :: n2 :: t when n1 < n2 -> min (n1 :: t) | n1 :: n2 :: t -> min (n2 :: t) min [1;4;0;9;3] (* min (1 :: 4 :: 0 :: 9 :: 3 :: []) --> min (1 :: 0 :: 9 :: 3 :: []) --> min (0 :: 9 :: 3 :: []) --> min (0 :: 3 :: []) --> min (0 :: []) --> 0 *) let rec append l m = match l with [] -> m | h :: t -> h :: (append t m) append [1;2] [2;3;4] // append is actually predefined and has infix syntax [1;2] @ [2;3;4] let rec reverse = function [] -> [] | h :: t -> append (reverse t) [h] reverse [1;2;3] // association lista are lists of type ('a * 'b) list let al = [("a", 3); ("c", 78); ("baf", 666); ("b", 111)] let rec lookup al x = match al with | [] -> failwith "key not found" | (k,v) :: t -> if x = k then v else lookup t x