(* Given a max value n, returns list [1, 2, 3, ..., n-1, n]. Implemented tail-recursively to be more efficient (O(n)). *) fun range(n) = let fun helper(i) = if i > n then [] else i :: helper(i+1) in helper(1) end; (* Given a list L = [a, b, c, ..., y, z], returns [z, y, ..., c, b, a]. Implemented tail-recursively to be more efficient (O(n)). The helper parameter 'tempList' is used as an 'accumulator' to store values being built up in progress. *) fun reverse([]) = [] | reverse(L) = let fun helper([], tempList) = tempList | helper(first::rest, tempList) = helper(rest, first::tempList) in helper(L, []) end; (* Computes the n'th Fibonacci number, where each is the sum of the last two. Implemented using tail recursion to make the computation iterative and O(n) rather than O(2^n) (yipes!) without tail recursion. *) fun fibonacci(1) = 1 | fibonacci(2) = 1 | fibonacci(n) = let fun helper(prev, curr, k) = if k = n then curr else helper(curr, curr + prev, k + 1) in helper(1, 1, 2) end; (* A silly function that just computes 2*n. But when implemented as 2 + timesTwo(n-1), very slow. We unrolled the computation into an iterative tail-recursive helper. *) fun timesTwo(0) = 0 | timesTwo(n) = let fun helper(0, sum) = sum | helper(n, sum) = helper(n-1, sum+2) in helper(n, 0) end;