Euler #2 with F#
Published on Wednesday, July 20, 2011I'm in the process of learning F#, too, and I somehow managed to make a functional solution to problem two take more lines of code than what I wrote in C#. There must be a more elegant way to tackle this one.
let rec fib x =
match x with
| 1 -> 1
| 2 -> 1
| x -> fib (x - 1) + fib (x - 2)
let newList = []
let rec fibSeqConstructor fibSeq i limit=
let nextFib = (fib i)
if nextFib < limit then
let fibSeq = fibSeq @ [nextFib]
let i = i + 1
fibSeqConstructor fibSeq i limit
else
fibSeq
let problem2 =
(fibSeqConstructor newList 1 4000000)
|> Seq.filter (fun x -> x % 2 = 0)
|> Seq.fold (+) 0
printfn "The sum of all Fibonacci sequence numbers below 4,000,000 is %i" problem2