Alex Rivera | Logout

tail recursion vs. forward recursion

Asked 2010-06-15T06:22:56.383
27

Can someone give me the difference between these two kinds recursions and example (specifically in OCaml)?

Edit
Report

1 Answer

11

Here's an example of a tail recursive factorial function:

let fac n =
  let rec f n a =
    match n with
      0 -> a
    | _ -> f (n-1) (n*a)
  in
  f n 1

Here is it's non-tail recursive counterpart:

let rec non_tail_fac n =
  match n with
    0 -> 1
  | _ -> (non_tail_fac n-1) * n

The tail recursive function uses an accumulator, a, to store the value of the result of the previous call. This allows OCaml to perform tail call optimization which results in the the stack not overflowing. Typically a tail recursive function will make use of an accumulator value to allow tail call optimization to occur.

answered 2010-06-15T07:46:32.020

Your Answer