Generating Fibonacci series in F#

后端 未结 11 2004
南方客
南方客 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:33

    Other posts tell you how to write the while loop using recursive functions. This is another way by using the Seq library in F#:

    // generate an infinite Fibonacci sequence
    let fibSeq = Seq.unfold (fun (a,b) -> Some( a+b, (b, a+b) ) ) (0,1)
    // take the first few numbers in the sequence and convert the sequence to a list
    let fibList = fibSeq |> Seq.takeWhile (fun x -> x<=400 ) |> Seq.toList
    

    for explanation, please ref solution 2 in F# for Project Euler Problems, where the first 50 Euler problems are solved. I think you will be interested in these solutions.

提交回复
热议问题