F# Tail Recursive Function Example

后端 未结 5 1909
灰色年华
灰色年华 2020-11-27 15:18

I am new to F# and was reading about tail recursive functions and was hoping someone could give me two different implementations of a function foo - one that is tail recursi

5条回答
  •  余生分开走
    2020-11-27 16:03

    I'm learning F# too. The following are non-tail recursive and tail recursive function to calculate the fibonacci numbers.

    Non-tail recursive version

    let rec fib = function
        | n when n < 2 -> 1
        | n -> fib(n-1) + fib(n-2);;
    

    Tail recursive version

    let fib n =
        let rec tfib n1 n2 = function
        | 0 -> n1
        | n -> tfib n2 (n2 + n1) (n - 1)
        tfib 0 1 n;;  
    

    Note: since the fibanacci number could grow really fast you could replace last line tfib 0 1 n to
    tfib 0I 1I n to take advantage of Numerics.BigInteger Structure in F#

提交回复
热议问题