Key to CSE341 Midterm handout #13
1. Expression Value
-----------------------------------------------------------------------
reduce(op +, numbers) 19.0
map(hd o tl o rev, [1--3, 2--4, 5--6, 3--9]) [2,3,5,8]
reduce(op *, map(round, numbers)) 210
filter(fn x => 20 div x < 2, (1--12) @ (8--14)) [11,12,11,12,13,14]
map(fn x => x--4, 2--5) [[2,3,4],[3,4],[4],[]]
reduce(op *, map(fn x => 3 * x - 1, 1--3)) 80
map(fn n => n - 1.1, numbers) [6.2,0.3,2.1,3.8,1.1]
reduce(op +, filter(fn n => 6 mod n = 0, 1--5)) 6
map(fn x => (x, x - 1), 2--4) [(2,1),(3,2)(4,3)]
implode(reduce(op @, map(tl o explode "ooaraz"
["foo","bar","baz"])));
2. Expression Type
-------------------------------------------------------------------------
lst real list
(lst, map(round, lst)) real list * int list
map(fn x => (round(x), x), lst) (int * real) list
round o hd o tl real list -> int
fn x => [(x, [x])]; 'a -> ('a * 'a list) list
3. The binding is:
val answer = 75
4. One possible solution appears below.
val sum = reduce2 op+ o map2 ord o explode;
val counts = map2 (curry op-- 1) o curry op-- 1;
5. One possible solution appears below.
fun evens(lst) =
let fun helper([], count) = count
| helper(x::xs, count) =
if x mod 2 = 0 then helper(xs, count + 1)
else helper(xs, count)
in helper(lst, 0)
end;
6. One possible solution appears below.
fun mapIndex(f, lst) =
let fun helper([], n) = []
| helper(x::xs, n) = f(x, n) :: helper(xs, n + 1)
in helper(lst, 0)
end;
7. One possible solution appears below.
fun insert(x, []) = []
| insert(x, y::ys) = (x::y)::insert(x, ys);
8. One possible solution appears below.
fun tighten(Empty) = Empty
| tighten(Node(root, Empty, Empty)) = Node(root, Empty, Empty)
| tighten(Node(root, left, Empty)) = tighten(left)
| tighten(Node(root, Empty, right)) = tighten(right)
| tighten(Node(root, left, right)) =
Node(root, tighten(left), tighten(right));
9. Three possible solutions to indexSum and one solution to minSum appear
below.
fun indexSum(lst) =
let fun helper([], n) = 0
| helper(x::xs, n) = n * evens(x) + helper(xs, n + 1)
in helper(lst, 0)
end;
fun indexSum([]) = 0
| indexSum(lst) =
reduce(op+, mapIndex(fn (x, n) => evens(x) * n, lst));
fun indexSum(lst) =
foldl op+ 0 (mapIndex(fn (x, n) => evens(x) * n, lst));
fun minSum(lst) = msort(fn (x, y) => evens(x) > evens(y), lst);
10. One possible solution appears below.
fun pick(0, lst) = [[]]
| pick(n, []) = []
| pick(n, x::xs) = insert(x, pick(n - 1, xs)) @ pick(n, xs);