Another Project Euler problem, and a List.fold example

October 15, 2011

Project Euler Problem #6

Part two in what I hope will be a series on solving some of the Project Euler problems just to learn F# (part 1 here).

I skipped down to #6 next, and was able to whip out a few lines of F# pretty quickly to get the answer. Since I was just re-using List.sum and, there wasn’t much new here.

   1:  let numbers = [1..100]
   2:  let squares = numbers |> (fun x -> x*x)
   3:  let sumsquares = List.sum squares
   4:  let sums = List.sum numbers
   5:  let squaresums = sums*sums
   6:  let total = squaresums - sumsquares

Then after a short chat with Richard Minerich, whose blog post on getting started gave me the idea to work on the Project Euler problems to begin with, I decided to condense this a bit. I was able to pretty quickly rewrite lines 2 and 3, and 3 and 4 into:

   1:  let sumsqaures = numbers |> (fun x -> x*x)|> List.sum
   2:  let squaresums = numbers |> List.sum |> (fun x -> x*x)

Around this point, I found Dustin Campbell’s #6 solution, which helped me realize the teensiest (but ridiculously major) thing that you can replace:

   1:  (fun x -> x*x)

with a new square function:

   1:  let square x = x*x

and just call that, instead. Also, there’s no reason not to condense the subtraction to one line – except maybe readability :p – so I end up with:

   1:  let numbers = [1..100]
   2:  let square x = x*x
   3:  let total = (numbers |> List.sum |> square)-(numbers |> square |> List.sum)

Fun! I decided to stop there, and not continue to what ultimately would have been pretty close to his solution (check it out, it’s delightful) because that felt somehow like accidental cheating. :)

List.fold Example

Since #6 was a little easy, I thought I’d add a small thing – I was flipping through Chris Smith’s Programming F# this afternoon, and saw that both he and Chris Ammerman (in the comments last night) provided the same example: using List.fold to take an array of strings into a single comma-delimited string (must be a people-named-Chris-thing to come up with that example.. *shrug*). You can see Chris Smith’s code from the bookhere. Thanks for helping me make sense of that one, folks. :)

tags: ,
posted in F# by rach

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

Powered by Wordpress and MySQL. Theme by Shlomi Noach,