Generating Fibonacci series in F#

后端 未结 11 1978
南方客
南方客 2020-12-31 02:58

I\'m just starting to learn F# using VS2010 and below is my first attempt at generating the Fibonacci series. What I\'m trying to do is to build a list of all numbers less

11条回答
  •  死守一世寂寞
    2020-12-31 03:31

    Here's an infinite tail-recursive solution using sequence expressions. It's quite efficient, producing the 100,000th term in just a few seconds. The "yield" operator is just like C#'s "yield return", and the "yield!" operator may be read as "yield all", where in C# you would have to do "foreach item ... yield return item".

    https://stackoverflow.com/questions/2296664/code-chess-fibonacci-sequence/2892670#2892670

    let fibseq =    
        let rec fibseq n1 n2 = 
            seq { let n0 = n1 + n2 
                  yield n0
                  yield! fibseq n0 n1 }
        seq { yield 1I ; yield 1I ; yield! (fibseq 1I 1I) }
    
    let fibTake n = fibseq |> Seq.take n //the first n Fibonacci numbers
    let fib n = fibseq |> Seq.nth (n-1) //the nth Fibonacci number
    

    This approach is similar to the following in C# (which uses a while(true) loop instead of recursion):

    Finding Fibonacci sequence in C#. [Project Euler Exercise]

提交回复
热议问题