tail recursion vs. forward recursion

后端 未结 3 2072
萌比男神i
萌比男神i 2020-12-04 18:21

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 18:49

    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.

提交回复
热议问题