(* --- recursive functions --- *) (* From Section 1.12 *) fun factorial(0) = 1 | factorial(n) = n * factorial(n-1); (* Ex 1.12.4. Homemade multiply *) fun multiply(x, 0) = 0 | multiply(x, y) = x + multiply(x, y-1); (* Ex 1.12.6. Summation. *) fun sum(1) = 1 | sum(n) = n + sum(n-1); (* --- list functions (didn't get to, we'll do these next time) --- *) (* examples from the text *) fun repeatEach([]) = [] | repeatEach(a::rest) = a::a::repeatEach(rest); fun sum([]) = 0 | sum(a::rest) = a + sum(rest); fun switchPair([]) = [] | switchPair((a,b)::rest) = (b, a)::switchPair(rest); (* 2.2.4 -- in class*) fun count([]) = | count(a::rest) = (* 2.2.5 -- in class *) fun findIth([], i) = (print("item not found"); ~1) | findIth(a::rest, 0) = | findIth(a::rest, i) = (* 2.2.6 -- in class *) fun reverse([]) = | reverse(a::rest) = (* Ex 2.2.10 -- in class *) fun listify([]) = | listify(a::rest) = (* Ex 2.2.12 -- in class *) fun splitList([]) = | splitList((a,b)::rest) = let val (aRest, bRest) = in end; (* sample use of splitlist: *) splitList([(1,2), (3,4), (5,6)]); (* results in ([1,3,5],[2,4,6]) *) (* problems below marked "homework" assigned 1/28, due 1/30 *) (* Ex 2.2.13 -- homework *) fun tuplify([], []) = [] | tuplify(a::rest, []) = ?? | tuplify([], b::rest) = ?? | tuplify(a::aRest, b::bRest) = ?? (* Ex 2.2.14 -- in class *) fun sumPairs([]) = | sumPairs((a,b)::rest) = (* Ex 2.2.15 -- homework *) fun sumPairList([]) = (0, 0) | sumPairList((a,b)::rest) = let val (c, d) = sumPairList(rest) in ?? end; (* Extra hint on sumPairList: use splitList (above) as a pattern to follow. Sample us of sumPairList: *) sumPairList([(1,2), (3,4), (5,6)]); (* Result should be (9, 12), that is, (1+3+5, 2+4+6) *)