I've really started to enjoy using F# over the last year and half especially with regards to doing small projects. A few years ago, I started solving some of the Project Euler questions using python. Just because I like F# so much, I wanted to demonstrate how different my solutions looked in Python vs F# for at least the first problem.
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.
Below is the python solution:
total = 0 for x in range(1, 1000): if x % 5 == 0: total += x elif x % 3 == 0: total += x print total
Below is the F# solution:
let nums = [ 0..999] nums |> List.fold(fun acc num -> if (num % 3 = 0 || num % 5 = 0) then acc + num else acc) 0
First thing that should strike you is just how short the answer is in F#. Here, I used a fold (a higher order function) that has the following type signature:
List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
It's not super important to understand everything here, but basically fold is a function that takes a function
('State -> 'T -> 'State) that updates the state given the input elements. In this case, my anonymous function that I defined with
fun acc num -> if (num % 3 = 0 || num % 5 = 0) then acc + num else acc) fulfills that role.
acc is the accumulator and
num represents the current element.
'State is the initial state, so in this case, it's 0
'T list is the input list
'State is the result we get after applying the function.
The result is a nice one line function that gets me the answer.
I'm hoping to have more posts about these problems and F# in the near future.