Key to CSE341 Sample Midterm handout #6 1. Expression Value ----------------------------------------------------------------------- reduce(uncurry( * ), 3--5) 60 map(List.hd % List.tl, [9; 5; 8; 9] [8--12; 4--9; 7--8; 8--10]) map((fun x -> x mod 4), 1--7) [1; 2; 3; 0; 1; 2; 3] reduce(uncurry(+), 30 map((fun x -> x * x), 1--4)) filter((fun x -> x mod 4 > 1), 1--12) [2; 3; 6; 7; 10; 11] map((fun x -> "(" ^ x ^ ")"), words) ["(live)"; "(long)"; "(and)"; "(prosper)"] reduce(uncurry(@), [1--3; 4--6; 5--7]) [1; 2; 3; 4; 5; 6; 5; 6; 7] map((fun x -> float_of_int(x) +. 0.5), 1--4) [1.5; 2.5; 3.5; 4.5] reduce(uncurry(+), map(String.length, words)) 18 reduce(uncurry( * ), 105 map((fun x -> 2 * x - 1), 2--4)) 2. Expression Type ------------------------------------------------------------------------- lst (string * int) list [List.tl(lst)] (string * int) list list (8, [["a"; "b"]; ["c"; "d"]]) int * string list list fun x -> (List.hd(x) mod 3, List.tl(x)) int list -> int * int list float_of_int % List.hd % List.tl int list -> float 3. The binding is: val answer = 199 4. One possible solution appears below. let sum_positives = reduce2 (+) % filter2 ((<) 0) let strip = map2 (implode % reverse % List.tl % reverse % explode) 5. One possible solution appears below. let powers(n, m) = let rec loop(i, product) = if i = 0 then [product] else product::loop(i - 1, product * m) in loop(n, 1) 6. One possible solution appears below. let sorted_chars(s) = implode(qsort(uncurry(<), map(Char.lowercase_ascii, filter(is_alpha, explode(s))))) 7. One possible solution appears below. let rec interleave(params) = match params with | ([], ys) -> ys | (xs, []) -> xs | x::xs, y::ys -> x::y::interleave(xs, ys) 8. One possible solution appears below. let rec nodes(tree) = match tree with | Empty -> 0 | Node(_, left, right) -> 1 + nodes(left) + nodes(right) let rec leaves(tree) = match tree with | Empty -> [] | Node(root, Empty, Empty) -> [root] | Node(_, left, right) -> leaves(left) @ leaves(right) 9. One possible solution appears below. let rec cartesian_product(list1, list2) = match list1 with | [] -> [] | x::xs -> map((fun y -> (x, y)), list2) @ cartesian_product(xs, list2) let product(xs, ys) = map((fun (x, y) -> x * y), cartesian_product(xs, ys)) 10. One possible solution appears below. let rec factors(list) = match list with | [(p, n)] -> powers(n, p) | (p, n)::rest -> product(powers(n, p), factors(rest))
Stuart Reges
Last modified: Wed Apr 24 12:07:21 PDT 2024