Generating Fibonacci series in F#

后端 未结 11 2005
南方客
南方客 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: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]*)
    

提交回复
热议问题