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.


In [29]:
let isEven x = x % 2 = 0

let fibsTo limit =
    Seq.unfold (fun s -> 
        if ((fst s) > limit)
        then None
        else Some(fst s, (snd s, (fst s) + (snd s)))
    ) (1,1)

fibsTo 4000000
|> Seq.filter isEven
|> Seq.sum


Out[29]:
4613732

In [2]:
// seq unfold example
// from MSDN docs @ https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/seq.unfold%5B'state,'t%5D-function-%5Bfsharp%5D

// unfold will take a function and produce a sequence - the function has a single "state" argument
// which is a tuple (x, y) where:
// - x = the value we'll return in the result sequence
// - y = the next "state" we'll call the function with

let ints20 = 
    Seq.unfold (fun state -> 
        if (state > 20) 
        then None 
        else Some(state, state + 1)
    ) 0

let pairInts20 = 
    Seq.unfold (fun state -> 
        if ((fst state) > 20) 
        then None 
        else Some((fst state, snd state), ((fst state)+1, 2))
    ) (0,0)

pairInts20


Out[2]:
seq [(0, 0); (1, 2); (2, 2); (3, 2); ...]

In [ ]: