Welcome to MSDN Blogs Sign in | Join | Help

jaredpar's WebLog

Code, rants and ramblings of a programmer.
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

Published Thursday, September 11, 2008 8:01 AM by Jared Parsons

Filed under:

Comments

# Euler #2 : EasyCoded @ Thursday, September 11, 2008 8:11 AM

PingBack from http://www.easycoded.com/euler-2/

Euler #2 : EasyCoded

# re: Euler #2 @ Thursday, September 11, 2008 3:19 PM

Hi,

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.

Laurent

New Comments to this post are disabled
Page view tracker