A while ago I found a wonderful website called Project Euler, which provides a steady stream of interesting mathematical/algorithmic problems to solve. If you are sufficently clever you can potentially solve most problems symbolically with pen and paper. I, however, have been sticking to C# 🙂
With the latest news about baking F# into Visual Studio I figured re-solving the problems from Project Euler would be a great way to learn F# and hopefully come up with cleaner solutions. This post will go over my solution for problem 1 in F#. Since I am still learning, this might not be the best way to solve it; so if you can think of a better way let me know.
Problem 1 is defined as follows:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Solution in F#
let problem1 =
let Mod35 x =
if x % 3 = 0 then true
else if x % 5 = 0 then true
let numbers = [1 .. 999]
numbers |> Seq.fold
(fun acc x -> if Mod35(x) then
acc + x
printfn “Problem 1 = %d” problem1
This may look strange to some of you, but the code is actually straightfoward. Let’s walk through it line by line.
First, we start by defining a function ‘problem1’. Within that function, we define a new function ‘Mod25’ which takes a parameter x. Mod35 simple returns whether or not the parameter modulus three of five retuns zero. So far so good.
Next, I create a list of integers from one to 999.
Finally I use the ‘Seq.fold’ operation. I’ll probably devote an entire blog post to cool things you can do with Seq.fold later, but for now think of it is summerizing a list. It performs some computation over every element in a list and keeps track of a variable. In the code I am looping through all integers 1 to 999 and if they are divisible by three of five then I add it to the ‘acc’ accumulator variable, otherwise I just pass the current accumulator variable onward. That trailing 0 simply initializes acc.
Notice the lack of a ‘return’ statement. The last computation preformed is the Seq.fold operation, which summed up the list of integers divisible by three or five. So on the last line we print whatever number is returned by function ‘problem1’.
If after reading this F# still doesn’t make sense don’t worry! I’ll be posting more problems / solutions in the future to give you some more examples; but in the mean time I would strongly encourage you to download the latest build and start playing with it.
Again, thanks to the folks at Project Euler. Once the
easy less-challenging problems are out of the way I’ll be sure to tweak the problems slightly.
Edit: Added ‘#light’ declaration at top of code
Edit2: Please check out the ‘comments’ for this post if you haven’t already, Robert Pickering posted two much more elegant alternatives to my solution. I don’t feel too bad, since everything I know about F# I read in his book Foundations of F#.