(* CS421 - Summer 2007 * MP1 Solution * * Please keep in mind that there may be more than one * way to solve a problem. *) (* Problem 1 *) let sum4 x y z t = x +. y +. z +. t (* Problem 2 *) let fst (x,y) = x (* Problem 3 *) let max3 x y z = let max_xy = if x > y then x else y in if max_xy > z then max_xy else z (* Problem 4 *) let cube_sum x y z = let sum = x + y + z in sum * sum * sum (* Problem 5 *) let twicehead lst = match lst with [] -> 0 | x::xs -> 2 * x (* Problem 6 *) let replacehead a lst = match lst with [] -> [] | x::xs -> a::xs (* Problem 7 *) let birthday name num = print_string name; print_string " is "; print_int num; print_string " years old today.\n" (* Problem 8 *) let divide x y = if y = 0 then (false, 0) else (true, x / y) (* Mapping recursion *) (* Problem 9 *) let rec square_lst lst = match lst with [] -> [] | x::xs -> x * x::square_lst xs (* Problem 10 *) let rec map_lst f lst = match lst with [] -> [] | x::xs -> f x::map_lst f xs (* Folding recursion *) (* Problem 11 *) let rec dropneg_lst lst = match lst with [] -> [] | x::xs -> if x < 0 then dropneg_lst xs else x::dropneg_lst xs (* Tail recursion *) (* Problem 12 *) let concat_rev_lst lst = let rec aux lst res = match lst with [] -> res | x::xs -> aux xs (x ^ res) in aux lst "" (* Problem 13 *) let sumf_lst f lst = let rec aux lst res = match lst with [] -> res | x::xs -> aux xs (if f x then x + res else res) in aux lst 0 (* Extra credit *) (* Problem 14 *) let rec repeat_item n item = if n <= 0 then [] else item::(repeat_item (n-1) item) let repeat_lst lst = let rec aux n lst = match lst with [] -> [] | x::xs -> repeat_item n x::aux (n+1) xs in aux 1 lst