(* file: lists.ml * author: Bob Muller * * CS1101 Computer Science I * * Code introducing lists covered in class on Tuesday * February 9, 2016. *) (* length : 'a list -> int *) let rec length xs = match xs with | [] -> 0 | _ :: ys -> 1 + (length ys) (* mem : 'a -> 'a list -> bool *) let rec mem x xs = match xs with | [] -> false | y :: ys -> (match x = y with | true -> true | false -> mem x ys) let rec add ns = match ns with | [] -> 0 | m :: ms -> m + (add ms) (* copy : 'a -> int -> 'a list *) let rec copy item n = match n = 0 with | true -> [] | false -> item :: (copy item (n - 1)) (* range : int -> int list * * The call (range n) returns the list [0; ...; n - 1]. *) let range n = let rec loop n acc = match n = 0 with | true -> acc | false -> let m = n - 1 in loop m (m :: acc) in loop n [] (* append : 'a list -> 'a list -> 'a list * * The call (append xs ys) returns a list with xs * appended to ys. This function performs ~N units * of work where N is the length of xs. *) let rec append xs ys = match xs with | [] -> ys | z :: zs -> z :: (append zs ys) (* badReverse : 'a list -> 'a list * * The call (badReverse xs) returns a list that is * the reverse of xs. However, this is a bad function * because it does ~N^2 units of work, when it can * otherwise be done more efficiently. *) let rec badReverse xs = match xs with | [] -> [] | y :: ys -> append (reverse ys) [y] (* goodReverse : 'a list -> 'a list * * Like badReverse, (goodReverse xs) returns a list with * the elements of xs reversed. This version requires ~N * units of work. *) let goodReverse xs = let rec repeat xs acc = match xs with | [] -> acc | y :: ys -> repeat ys (y :: acc) in repeat xs [] (* remove : 'a -> 'a list -> 'a list * * The call (remove item items) returns a list like * items but with the first occurrence of item removed. * We left the question of how to remove -all- occurrences * of item, open. *) let rec remove item items = match items with | [] -> [] | item' :: items' -> (match item = item' with | true -> items' | false -> item' :: (remove item items')) let a = ["Mary"; "Bob"; "Alice"]