Since I’ve just – JUST – started learning F#, I thought I would post my solutions to the first couple problems on Project Euler:
Problem #1: Add all the natural numbers below 1000 which are multiples of 3 or 5.
1: let all = [1 .. 999]
2: let filtered = all |> List.filter (fun x -> x%3=0 || x%5=0)
3: let count = List.sum filtered
So, first we declare a list of all natural numbers (basically, positive integers, since it doesn’t matter here if 0 is included or not) less than 1000. Then, we take that list and filter it for everything that’s divisible by 3 or 5. And finally, sum the list. Pretty easy. Now that I’ve done it. :)
Problem #2: Find the sum of the even-valued terms of the Fibonacci sequence which are less than 4 million.
1: let fibSeq = Seq.unfold (fun (a,b) -> Some( a+b, (b, a+b) ) ) (0,1)
2: let fibList = fibSeq |> Seq.takeWhile (fun x -> x<4000000 ) |> Seq.toList
3: let filterList = List.filter (fun x -> x%2=0) fibList
4: let fibSum = List.sum filterList
By far the hardest part about this problem (for me) was figuring out how to create the Fibonacci sequence. This whole unfolding thing is *totally* new. Basically, you’re starting with (a=0,b=1) and applying (a+b, (b, a+b)) for each new element. Once we have the generating function defined, we send that to takeWhile to only grab values less than 4 million, and put those into a new list. Next, we filter the new list, for only even values. Finally, sum those up.
I would *love* feedback on the code. Or how have you done it? I only went back a couple pages, but I didn’t see a single other F# solution in the forum for those two questions!
Also, a (probably very basic) question: I’ve seen several examples where people use List.fold to sum things. Since List.sum exists, would you ever do that IRL? When *would* you use List.fold? I haven’t been able to quite wrap my head around it. Thanks!