Euler #2

Problem #2 came quite a bit faster. The yield syntax in F# is very similar to the C# iterator syntax and made translating this sample a breeze. 

As a commenter posted, in problem #1, I would've been better served to use Seq.filter as opposed to Seq.choose for the purpose of filtering list.  I've applied that here.  One downfall of learning a new language is finding the right API.  I spent a bit of time reading through the Seq documentation looking for the equivalent of the Where extension method and could only find chose.  Lesson learned

// Find the sum of all the even-valued terms in the sequence which do not exceed four million.
let problem2() =
    let rec fib prev cur = seq {
            yield prev
            if cur < 4000000 then
                yield! fib cur (prev+cur)
    fib 1 2
        |> Seq.filter (fun x -> 0 = x % 2)
        |> Seq.sum

Comments (2)

  1. Laurent says:


    I suggest this solution:

    let problem2() =

       Seq.unfold (fun (x, y) -> Some (x, (x + y, x))) (1, 0)

       |> Seq.filter (fun x -> 0 = x % 2)

       |> Seq.take_while ((>) 4000000)

       |> Seq.sum

    Today’s lesson: Seq.unfold. It’s not always easy to use, but it’s a very nice function. Here, it returns the infinite list of Fibonacci numbers.

Skip to main content