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
letas if it was a statement to mutate a variable, but that’s not the case. In F#,letis 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: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
Addmember!). If you wanted to write this using mutation, you could write: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: