As promised, here are some F# solutions to my second lunchtime LINQ challenge. I’ve still got a way to go with getting familiar with all the features of F#, so thanks especially to Sehnsucht whose answers pointed me in the direction of some better ways to solve these.

Problem 1 – Motorsport Scores

For the first one, I pretty much went with the same approach as in C#: convert to int, sort, skip 3, then sum:

But in the C# solution we saw how the LINQ Query Expression Syntax makes for a cleaner way of expressing the problem that doesn’t repeat the starting position. And it turns out that we can create a very similar solution in F#:

Problem 3 – Sampling

This was one where F# surprisingly lacks the method that made it so easy in C#. F~ has a mapi function which gives an index of each item, but there is no corresponding filteri function (feature request here) . So I ended up using a mapi to create a sequence of tuples, which I could then filter and map back to a string.

But again Sehnsucht pointed me in the direction of an alternative solution, and that is to use the function keyword (not the same as the fun keyword) which allows you to use pattern matching in the function definition. What I hadn’t realised was that you are not forced to match all possible inputs, and so you can do something like this:

Problem 5 – Counting Pets

In C# we used GroupBy, but noted that a better solution would be if there was a method called countBy. And guess what, F# has one! And we can use the function keyword we just learned about to specify that we want to count dogs and cats separately but batch all other pets together. And I also learned another new F# function, the ‘destructuring’ operator ||>, letting me pass a tuple to sprintf without needing to use fst and snd explicitly.

Of course, one of the things that F# makes really easy is to create little helper functions that you can use to simplify your code, in the same way that you might declare intermediate variables in C# to make your code more readable.

So for example we might create a repeats function to decide how many times a letter should be repeated, a repeat function to construct the string with that many repeats, and a matches function to simplify performing the regex. It doesn’t make the solution shorter, but I think this style of coding does aid readability:

About Mark Heath

I'm a Microsoft MVP and software developer based in Southampton, England, currently working as a Software Architect for NICE Systems. I create courses for Pluralsight and am the author of several open source libraries. I currently specialize in architecting Azure based systems and audio programming. You can find me on: