So I’ve been learning F#.
Learning a new language has never been a challenge for me. But writing idiomatic F# (those F# guys are big on idiomatic) requires a reorientation of my thinking.
With that in mind, I decided a good way to improve my skills was to solve the first 60 Project Euler problems with F#, trying to be as idiomatic as possible, while avoiding being idiotic. (See what I did there? It’s a prefix joke.)
So, without further ado, here is:
Problem 1
Sum all positive integers less than 1000 that are multiples of 3 or 5.
C# Solution
If I was writing this in C#, I would be using something like a for loop with a mutable iterator to do this.
var sum = 0;
for (var i = 1; i < 1000; ++i)
{
if (i%3 == 0 || i%5 == 0)
{
sum += i;
}
}
Console.WriteLine(sum);
F# Solution
seq { 1..999 }
|> Seq.filter (fun n -> n % 3 = 0 || n % 5 = 0)
|> Seq.sum
Right away, we’re making use of the most common F# features:
- Sequences (
seq { 1..999}
) - Expressing the problem as a pipeline
All the thinking happens on the second line, which filters out the values we don’t want. Seq.sum
gives us the answer by processing the sequence created by the previous elements in the pipeline.
But, but…
Yes, I know, you can do exactly the same thing in C# with LINQ. This is not a problem where F# particularly shines. But I’m working through all the problems anyway.
I could do it in C# and LINQ like this. It looks almost exactly like the F# solution.
var sum = Enumerable.Range(1, 999).Where(x => x%3 == 0 || x%5 == 0).Sum();
Console.WriteLine(sum);