These are exercises about "higher order functions". 1.) Compute the result of each map. (a) map (fn x => x+3) [1, 3, 6, 5, 9]; (b) map String.size ["cats", "dog", "apple", "pear"]; (c) map length [[2,3,5], [4], [6,7,4,3], [4,4]]; (d) map hd [[2,3,5], [4], [6,7,4,3], [4,4]]; (e) map tl [[2,3,5], [4], [6,7,4,3], [4,4]]; (f) map (map (fn x=>x+3)) [[2,3,5], [4], [6,7,4,3], [4,4]]; (g) map (map (fn x=>x*x)) [[2,3,5], [4], [6,7,4,3], [4,4]]; 2.) Let fun f x y z = 2*x + 3*y + 4*z; Describe each of the functions g1 through g14 (what formula does each function simplify to?). val g1 = f 5; (* g1(u,v) = 10 + 3*u + 4*v *) fun g2 u v = f 5 u v; (* g2(u,v) = 10 + 3*u + 4*v *) fun g3 u v = f 5 v u; (* g3(u,v) = 10 + 3*v + 4*u *) fun g4 u v = f u 5 v; (* g4(u,v) = 15 + 2*u + 4*v *) fun g5 u v = f u v 5; val g6 = f 5 4; (* g6(a) = 22 + 4*a *) fun g7 u = f 5 4 u; fun g8 u = f u 5 4; fun g9 u = f 5 u 4; val g10 = g2 5; val g11 = g3 5; val g12 = g4 5; val g13 = g5 5; fun g14 u v = g3 v u; 3.) Find the value of each of these expressions. (a) (fn x => 3*x+2) 5; fun h x = 3*x + 2; h 5; val h = fn x => 3*x + 2; h 5; (b) (fn x => (fn y => 3*x+y)) 5 2; fun h x y = 3*x + y; h 5 2; (c) (fn x => x+2) ((fn x => 3*x) 5); fun h1 x = 3*x; fun h2 x = x + 2; h2 (h1 5) (d) Analyze the expression by doing repeated substitutions. (fn x => (fn y => x (x y))) (fn w => 3*w) 4; --------------------------- ------------- - (fn y => (fn w => 3*w) ((fn w => 3*w) y)) 4 (fn w => 3*w) ((fn w => 3*w) 4) (fn w => 3*w) 3*4 3*12 36 Here is another way to analyze this expression. fun h1 g y = g (g y); fun h2 w = 3*w; h1 h2 4; (* simplifies to, h2 (h2 4) *) (e) (fn x => (fn y => x*y)) ((fn w => 3*w) 4) 5; (f) (fn x => (fn y => fn z => z (x+y))) 3 4 (fn w => 5*w); (g) (fn f => fn g => fn x => f (g x)) (fn x => 5*x) (fn x => 6*x) 2; 4.) Compute the result of each fold. (a) foldr (op +) 10 [1,2,3,4,5]; 1 + (2 + (3 + (4 + (5 + 10)))); (* foldr *) (b) foldl (op +) 10 [1,2,3,4,5]; 5 + (4 + (3 + (2 + (1 + 10)))); (* ML's foldl *) ((((10 + 1) + 2) + 3) + 4) + 5; (* foldl for everyone but ML *) (c) foldr (fn (x, y) => if (0 = x mod 2) then x+y else y) 0 [1,2,3,4,5,6]; Evaluate f(1, f(2, f(3, f(4, f(5, f(6, 0)))))); where fun f (x, y) = if (0 = x mod 2) then x+y else y; The foldl sums up the even numbers from the list. (d) foldr (fn (x, y) => (hd (explode x))::y) [] ["bye","saw","we","cat","dog"]; Evaluate f("bye", f("saw", f("we", f("cat", f("dog", []))))); where fun f (x, y) = hd (explode x) :: y; (e) foldr (fn (f, xs) => map f xs) [2,3,4,5,6,7] [fn x=>2*x, fn x=>3*x, fn x=>x*x];