Homework #7 Solution Sketches 1) Higher order functions map, foldl, or foldr are each possible answers. 2) a) if b then statement1 else statement2 if b -> statement1 | !b -> statement2 fi b) if b then statement if b -> statement | !b -> noop fi c) while b do statement do b -> statement od d) repeat statement until b statement; do !b -> statement od e) for i := 1 to 100 do statement i=1; do i < 100 -> {statement; i++} od 3) SML is a functional programming language which implies side-effect free, referential transparency (meaning the execution of a function always produces the same result when given the same parameters). In other words, there is really no concept of "state." Thus, conventional wisdom implies that ML uses the "pass by value" parameter passing mechanism. The following simple test code confirms this conclusion: - val x = 1; val x = 1 : int - x; val x = 1 : int - fun foo x = x+1; val foo = fn : int -> int - foo 1; val it = 2 : int - foo x; val it = 2 : int - x; val x = 1 : int 4) a) swap (value, list[0]) => value = 2, list = {1, 3, 5, 7, 9} swap (list[0], list[1]) => value = 2, list = {1, 3, 5, 7, 9} swap (value, list[value]) => value = 2, list = {1, 3, 5, 7, 9} b) swap (value, list[0]) => value = 1, list = {2, 3, 5, 7, 9} swap (list[0], list[1]) => value = 2, list = {3, 1, 5, 7, 9} swap (value, list[value]) => value = 2, list = {3, 1, 5, 7, 9} c) swap (value, list[0]) => value = 1, list = {2, 3, 5, 7, 9} swap (list[0], list[1]) => value = 1, list = {3, 2, 5, 7, 9} swap (value, list[value]) => value = 2, list = {3, 1, 5, 7, 9}, assuming the result of list[value] is copied back to the same location in memory as the value passed in, i.e., list[1]. swap (value, list[value]) => value = 2, list = {3, 2, 1, 7, 9} assuming the result of list[value] is copied back to list[value] (now list[2]) after the value of "value" from the function is copied back to the variable "value" in the calling function, main(). 5) pass by value: The values of i and A[i] are passed in, the value of the global i is updated, but nothing is passed out to overwrite the global i. Prints: 101 99 pass by reference: Aliases to i and A[i] are passed into the function, but the function never updates their values. The i in the function foo on the r.h.s. of the assignment is referring the global i in main and thus it is updated. Prints: 101 99 pass by result: The values of i and A[i] are never passed into foo; on the function return i and A[i] are returned as garbage, undefined, or default values. Prints: undefined undefined pass by value-result: The values of i and A[i] are passed in, the value of the global i is updated, but then when the function returns, the values of the formal parameters x and y are copied back to their respective actual parameters i and A[i] in main. Prints: 2 99 pass by name: A textual substitution is performed and i := x + y becomes i := i + A[i]. Prints: 101 99