fun mul(a, b) = a * b; fun mul(a, b) = let fun m(x) = a * x; in m(b) end; fun mulMaker(a) = let fun m(x) = a * x; in m end; fn (x) => (x - 2) * 3; fun halveList([]) = [] | halveList(n::rest) = (n div 2)::halveList(rest); fun doubleList([]) = [] | doubleList(n::rest) = (n * 2)::doubleList(rest); fun applyFunToList(f, []) = [] | applyFunToList(f, a::rest) = f(a)::applyFunToList(f, rest); fun halve(n) = n div 2; applyFunToList(halve, [22, 54, 33, 28]); applyFunToList(fn (x) => x * 2 , [2, 3, 4, 5]); applyFunToList(real,[2, 3, 4, 5]); fun applyListOfFunsToSomething([], a) = [] | applyListOfFunsToSomething(f::rest, a) = f(a)::applyListOfFunsToSomething(rest, a); applyListOfFunsToSomething([fn(x) => x div 2, fn(x) => x * 2, fn(x) => x * x], 4); (* the next one has a type error *) applyListOfFunsToSomething([fn(x) => x / 2, fn(x) => x * 2, fn(x) => x * x], 4); (* Earlier version of sorting a list ... *) fun removeFirst(x, []) = [] | removeFirst(x, a::rest) = if x = a then rest else a::removeFirst(x, rest); fun listMin([a]) = a | listMin(a::rest) = let val min = listMin(rest) in if a < min then a else min end; fun sort([]) = [] | sort(xx) = let val min = listMin(xx); val subList = removeFirst(min, xx); in min::sort(subList) end; (* New version, parameterized by the comparison function *) fun sort(yy, comp) = let fun removeFirst(x, []) = [] | removeFirst(x, a::rest) = if x = a then rest else a::removeFirst(x, rest); fun listMin([a]) = a | listMin(a::rest) = let val min = listMin(rest) in if comp(a, min) then a else min end; fun sortHelper([]) = [] | sortHelper(xx) = let val min = listMin(xx); val subList = removeFirst(min, xx); in min::sortHelper(subList) end; in sortHelper(yy) end; (* Sort a list backwards *) sort([2, 5,1,7,4,6,3], fn (x,y) => x > y); (* Sort lists (in a list of lists) by their length *) fun isShorterOrEq([], _) = true | isShorterOrEq(_, []) = false | isShorterOrEq(a::aRest, b::bRest) = isShorterOrEq(aRest, bRest); sort([[2,5,3], [3], [], [3,4,6,5,4,2,3], [2,5], [2,4,6,4], [1,2,3]], isShorterOrEq); (* for ex 7.3.3 *) fun makeListExtractor(xx) = let fun findNth([], x) = ~1 | findNth(a::rest, 1) = ?? | findNth(a::rest, x) = ?? fun extract(x) = ?? in extract end; fun makeListExtractor(xx) = let fun findNth([], x) = ~1 | findNth(a::rest, 1) = ?? | findNth(a::rest, x) = ?? in fn(x) => ?? end; (* For ex 7.3.4 *) fun makeListMul(x) = let fun listMul([]) = [] | listMul(a::rest) = ?? in ?? end; (* For ex 7.3.8 *) datatype tree = Leaf of int | Internal of (int * tree * tree); fun transformTree(Leaf(x), f) = ?? | transformTree(Internal(x, left, right), f) = ??