(* CS 421 Fall 2009 MP3 *) open Mp3common (* Problem 1 *) let rec remove_all list m = match list with [] -> [] | (x::xs) -> let r = remove_all xs m in if x = m then r else x::r (* Problem 2 *) let rec all_from_to m n p = if m <= n then let r = (all_from_to (m+1) n p) in r + (if p m then 1 else 0) else 0 (* Problem 3 *) let rec separate p l = match l with [] -> (0,0) | (x::xs) -> (match separate p xs with (m,n) -> if p x then (m+1,n) else (m,n+1)) (* Problem 4 *) let rec all_even list = match list with [] -> true | (h::t) -> ((h mod 2 = 0) && all_even t) (* The above is the same as (syntactic sugar for) let rec all_even list = match list with [] -> true | (h::t) -> (match (h mod 2 = 0) with true -> all_even t | false -> false) *) (* Problem 5 *) let sum_square m n = let rec ss_aux m s = if m >= n then s else ss_aux (m+1) (s + (m * m)) in ss_aux (m + 1) 0 (* An alternative solution let sum_square m n = let rec ss_aux m n s = if m >= n - 1 then s else ss_aux (m+1) n (s + ((m + 1) * (m +1))) in ss_aux m n 0 *) (* Problem 6 *) let concat s list = let rec concat_aux list (res, first) = match list with [] -> res | st::stl -> concat_aux stl (if st = s then (res, first) else ((if first then st else (res^" "^st)), false)) in concat_aux list ("", true) (* Problem 7 *) let remove_all_base = [] let remove_all_rec m n r = if n = m then r else n::r (* Problem 8 *) let separate_base = (0,0) let separate_rec p x (tl, fl) = if p x then (tl+1, fl) else (tl, fl+1) (* Problem 9 *) let all_even_base = true let all_even_rec r x = ((x mod 2) = 0) && r (* Problem 10 *) let concat2 s list = match List.fold_left (fun (res,first) st -> (if st = s then (res,first) else ((if first then st else (res ^ " " ^ st)), false))) ("", true) list with (s,_) -> s;; (* Problem 11 *) let app_all fs list = List.map (fun f -> List.map f list) fs (* Problem 12 *) let subk n m k = k(n-m) let catk a b k = k(a^b) let doublek a k = catk a a k let plusk x y k = k(x +. y) let multk x y k = k(x *. y) let is_posk n k = k(n > 0) (* Problem 13 *) let abcdk a b c d k = plusk a b (fun ab -> multk ab c (fun abc -> plusk abc d k)) (* Also OK: let abcdk a b c d k = plusk a b multk c plusk d k;; *) (* Problem 14 *) (* The solution to this problem depends upon what you gave for problem 1 *) let rec remove_allk list m k = match list with [] -> k[] | (x::xs) -> remove_allk xs m (fun r -> if x = m then k r else k (x::r));; (* Problem 15 *) let rec all_evenk list k = match list with [] -> k true | (h::t) -> match (h mod 2 = 0) with true -> all_evenk t k | false -> k false (* Uses that a && b is syntactic sugar for match a with true -> b | false -> false *) (* Problem 16 *) let rec all_from_tok m n pk k = if m <= n then all_from_tok (m+1) n pk (fun r -> pk m (fun b -> k(r + (if b then 1 else 0)))) else k 0