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


Share Post

Google+

comments powered by Disqus