Generating Fibonacci series in F#

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

    One more codata'ish way:

    let rec fib = seq {
      yield! seq {0..1}
      yield! Seq.map (fun(a,b)->a+b) <| Seq.zip fib (Seq.skip 1 fib)
    }
    let a = fib |> Seq.take 10 |> Seq.toList
    
    0 讨论(0)
  • 2020-12-31 03:43

    Here's a good article by .Net guru Scott Hanselman on generating fibonacci series in F#

    let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)
    

    http://www.hanselman.com/blog/TheWeeklySourceCode13FibonacciEdition.aspx

    It also compares with other languages as a reference

    0 讨论(0)
  • 2020-12-31 03:54

    Yes, mutable variables and while loops are usually a good sign that your code is not very functional. Also the fibonacci series, doesn't start with 1,2 - it starts with 0,1 or 1,1 depending on who you ask.

    Here's how I'd do it:

    let rec fabListHelper (a:int,b:int,n:int) =
      if a+b < n then
        a+b :: fabListHelper (b, a+b, n)
      else
        [];;
    
    let fabList (n:int) = 0 :: 1 :: fabListHelper (0,1, n);;
    
    (*> fabList 400;;
    val it : int list = [0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377]*)
    
    0 讨论(0)
  • 2020-12-31 03:57

    One with an array:

    let fibonacci n = [|1..n|] |> Array.fold (fun (a,b) _ -> b, a + b) (0,1) |> fst
    
    0 讨论(0)
  • 2020-12-31 03:57

    The great solution of Scott Hanselman does not report the 0 the fibonacci sequence starts with.

    So here is a minor change to his solution to also report the 0. I used a small list from 0 to 10 to display the first 11 items of the sequence.

    let nums=[0..10]
    let rec fib n = if n < 1 then 0 else if n < 2 then 1 else fib (n-2) + fib(n-1)
    let finres = List.map fib nums
    printfn "%A" finres
    

    I'm new and incompetent in relation to f# and still not totally fully understanding the need of it. But found this an interesting test.

    Just for fun : If found a formula of Binet that calculates the n-th Fibonacci number. Unfortunately some floating point functions are needed to get the integer result back in the end : [Fibonacci formula of Binet][1]

    http://i.stack.imgur.com/nMkxf.png

    let fib2 n = (1.0 / sqrt(5.0)) * ( (((1.0 + sqrt(5.0)) /2.0)**n)  -  (((1.0 -  sqrt(5.0)) /2.0)**n) )
    let fib2res = fib2 10.0
    System.Console.WriteLine(fib2res)
    let strLine = System.Console.ReadLine()
    

    A quick and dirty translation to f# would be as shown above. I'm sure others can improve on this in matter of style and efficiency. The example calculates the 10th number. The result will be 55.

    0 讨论(0)
提交回复
热议问题