I'm very new at F#, and am using Project Euler to help me learn. Question #2 kept me going for a while, as my initial attempt at an answer was very slow and inelegant. Then I learnt about Seq.unfold, and a whole new vista unfolded in front of me!
The problem statement is as follows (source):
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.
Please can you comment on this code. Bear in mind I'm very new at this, so I may be doing it completely wrong!
let fibEvenSum max = let rec fibEven n = match n with | 0 -> 0 | 1 -> 2 | n -> 4 * (fibEven (n - 1)) + (fibEven (n - 2)) 1 |> Seq.unfold (fun n -> Some(fibEven n, n+1)) |> Seq.takeWhile (fun n -> n < max) |> Seq.sum
If I run it like this, I get the right answer:
Is there a better way to do it?