Generating Fibonacci series in F#

tail recursive fibonacci f#
f# recursive function
fibonacci sequence
f# generator
yield f#
f# seq map
f# seq cast
f# infinite sequence

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 than 400.

let fabList = 
    let l =  [1;2;]
    let mutable a = 1
    let mutable b = 2
    while l.Tail < 400 do
        let c = a + b
        l.Add(c)
        let a = b
        let b = c

My first problem is that on the last statement, I'm getting an error message "Incomplete structured construct at or before this point in expression" on the last line. I don't understand what I'm doing wrong here.

While this seems to be an obvious way to build the list in a fairly efficient way (from a c++/C# programmer), from what little I know of f#, this doesn't seem to feel to be the right way to do the program. Am I correct in this feeling?


First of all, you're using let as if it was a statement to mutate a variable, but that's not the case. In F#, let is used to declare a new value (which may hide any previous values of the same name). If you want to write code using mutation, then you need to use something like:

let c = a + b  // declare new local value
l.Add(c)  
a <- b   // mutate value marked as 'mutable'
b <- c   // .. mutate the second value

The second issue with your code is that you're trying to mutate F# list by adding elements to it - F# lists are immutable, so once you create them, you cannot modify them (in particular, there is no Add member!). If you wanted to write this using mutation, you could write:

let fabList = 
  // Create a mutable list, so that we can add elements 
  // (this corresponds to standard .NET 'List<T>' type)
  let l = new ResizeArray<_>([1;2])
  let mutable a = 1
  let mutable b = 2
  while l.[l.Count - 1] < 400 do
    let c = a + b
    l.Add(c) // Add element to the mutable list
    a <- b
    b <- c
  l |> List.ofSeq // Convert any collection type to standard F# list

But, as others already noted, writing the code in this way isn't the idiomatic F# solution. In F#, you would use immutable lists and recursion instead of loops (such as while). For example like this:

// Recursive function that implements the looping
// (it takes previous two elements, a and b)
let rec fibsRec a b =
  if a + b < 400 then
    // The current element
    let current = a + b
    // Calculate all remaining elements recursively 
    // using 'b' as 'a' and 'current' as 'b' (in the next iteration)
    let rest = fibsRec b current  
    // Return the remaining elements with 'current' appended to the 
    // front of the resulting list (this constructs new list, 
    // so there is no mutation here!)
    current :: rest
  else 
    [] // generated all elements - return empty list once we're done

// generate list with 1, 2 and all other larger fibonaccis
let fibs = 1::2::(fibsRec 1 2)

Generating Fibonacci series in F# - f# - csharp, 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  F#. let seqInfinite = Seq.initInfinite (fun index -> let n = float (index + 1) 1.0 / (n * n * (if ( (index + 1) % 2 = 0) then 1.0 else -1.0))) printfn "%A" seqInfinite. Seq.unfold generates a sequence from a computation function that takes a state and transforms it to produce each subsequent element in the sequence.


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.

Recursive Fibonacci with F#, In case you don't know Fibonacci number, please see this article, but it can be summarized as: F(n) = F(n-1) + F(n-2) F(1) = 1. F(2) = 1. erating function for the Fibonacci sequence which uses two previous terms. The recurrence relation for the Fibonacci sequence is F n+1 = F n +F n 1 with F 0 = 0 and F 1 = 1. Let F(x) = X n 0 f nx n be the ordinary generating function for the Fibonacci sequence. Now, we will multiply both sides of the recurrence relation by xn+2 and sum it over all non-negative integers n.


let rec fibSeq p0 p1 = seq {
    yield p0
    yield! fibSeq p1 (p0+p1)
}

Recursive functions, 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  In this C# program, we are reading the limit to generate the Fibonacci series using ‘count’ variable. The numbers that precede the series are 0 and 1. The next number is found by adding up the two numbers before it. Using for loop generate Fibonacci series.


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]

The Weekly Source Code 13 - Fibonacci Edition, a function to generate the fibonacci numbers let rec fib x = match x with | 1 -> 1 | 2 -> 1 | x -> fib (x - 1) + fib (x - 2) // call the function and print the results printfn  The proof is quite simple. Let's write our sum in a compact format: 1 + z + 2 z 2 + 3 z 3 + 5 z 4 + 8 z 5 + = ∑ n = 0 ∞ F n z n. Where F n is the n th Fibonacci number, starting with F 0 = F 1 = 1, and F n + 2 = F n + F n + 1.


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]*)

F# IL generation for fibonacci sequence – Coffee, Code and Chocolate, I wanted to see what a Fibonacci number generator looked like in a number of different languages. Remember Or, if you want input and output as an F# console application: Following : Code that generated this number A Fibonacci sequence of order n is an integer sequence in which each sequence element is the sum of the previous elements (with the exception of the first elements in the sequence). The usual Fibonacci numbers are a Fibonacci sequence of order 2.


Sequences, Here is how the fibonacci series can be implemented in F#. If this was an executable, it would have generated the main method and told the  Example 2: Fibonacci Sequence Up to a Certain Number // program to generate fibonacci series up to a certain number // take input from the user let number = parseInt(prompt('Enter a positive number: ')); let n1 = 0, n2 = 1, nextTerm; console.log('Fibonacci Series:'); console.log(n1); // print 0 console.log(n2); // print 1 nextTerm = n1 + n2; while (nextTerm <= number) { // print the next term


Fibonacci sequence, Learn how to use F# sequences, when you have a large, ordered collection of For example, to generate a sequence of only prime numbers, assuming Because each element in the Fibonacci sequence is the sum of the  2. Fibonacci Series using while loop. There are various methods of getting the Fibonacci series and in this section, we will see how the Fibonacci series can be developed using the while loop. In the below program everything is similar to that of what we have used in the above program.


Fibonacci Fun with F#, Write a function to generate the nth Fibonacci number. Solutions can This is a fast [tail-recursive] approach using the F# big integer support: Outside India, the Fibonacci sequence first appears in the book Liber Abaci (1202) by Fibonacci. using it to calculate the growth of rabbit populations. Fibonacci considers the growth of an idealized (biologically unrealistic) rabbit population, assuming that: a newly born breeding pair of rabbits are put in a field; each breeding pair mates at the age of one month, and at the end of their