Tackling another Project Euler problem:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Alright, so the first thing to note is that this problem involves the Fibonacci sequence (going up to four million). We’ll go ahead and define a sequence for this using Seq.unfold:
let fib = (0,1) |> Seq.unfold (fun state ->
if fst state + snd state > 4000000 then None
else Some(fst state + snd state, (snd state, fst state + snd state)))
The notation of Seq.unfold is a bit confusing, but what it does is it takes a function which either returns some value and calls itself, or returns None. It also takes a starting value for this function, which in this case is the (0, 1) that is fed in using the pipe-forward operator.
Now that we have this sequence obtaining the result is trivial:
let result = Seq.sumBy (fun x -> if x % 2 = 0 then x else 0) fib
We use the sumBy function to only count even numbers. The final correct result is 4613732.