(* * CS 334 * Stephen Freund * Tail Recursion Examples *) (* Sum squares from 1 up to n*n. *) fun sumSq n = if n <= 0 then 0 else n*n + sumSq(n-1); (* Sum squares using tail-recursive helper function that requires O(1) space. *) fun sumSq n = let fun sumSqTail(0,t) = t | sumSqTail(n,t) = sumSqTail(n-1, t + n*n) in sumSqTail(n,0) end; sumSq 10; (****************************************************) (* An O(n^2) function to reverse a list *) fun rev nil = nil | rev (x::xs) = (rev xs) @ [x]; (* A tail-recursive version that runs in O(n) time and uses only O(1) space. *) fun rev l = let fun revTail(nil,r) = r | revTail(x::xs,r) = revTail(xs,x::r) in revTail(l,nil) end; rev [1,2,3,4,5];