I’ve been trying to teach myself F# using the Project Euler problems, and I’m starting to feel I’m getting somewhere with the language. The few Euler problems I’ve solved so far have had very straightforward and natural solutions.
Problem 8 is as follows: Find the subsequence of 5 consecutive digits that yield the greatest product when multiplied together, in the 1000-digit number:
I was able to come up with an F# solution that is one line, plus a helper line to convert the string into a sequence of digits:
let str = "731<...>" let digits = Seq.map (fun x -> int (Char.GetNumericValue x)) str let maxproduct num list = Seq.max (Seq.map (fun x -> Seq.reduce (*) x) (Seq.windowed num list))
The value digits is just a list of the digits in the string, converted into integers. The function maxproduct works the obvious way: take every subsequence of five digits (Seq.windowed), multiply them together (Seq.reduce, applied to each element of the sequence with Seq.map) and then find the maximum (Seq.max).
The only reason this needs quite so little work is the existence of Seq.windowed in the standard library, which does exactly the right thing in turning a 1000-element list into 996 arrays of subsequences of consecutive digits.
I’m not sure I like ramming all the functions into one line, and I’m sure there must be a way to combine map and reduce without the lambda, which adds a lot of clutter. If this was real code, it would need quite a lot of work to make it readable. However, the standard library is a big win, because the process of ‘windowing’ a sequence is nicely separated from the code. It’s also nice (for toy problems like this, at any rate) that the program is pretty much a definition of the problem, with little thought being necessary as to how to do the processing.