CS 334: Tail Recursion Examples

Sum Squares

(* 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, acc) = acc
        | sumSqTail(n, acc) = sumSqTail(n-1, acc + n*n)
  in
    sumSqTail(n, 0)
  end;

sumSq 10;

List Reverse

(* 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, acc) = acc
        | revTail(x::xs, acc) = revTail(xs, x::acc)
  in
    revTail(l, nil)
  end;

rev [1,2,3,4,5];