Partition - 7 higher order functions
Here's my third blog post in my serie about higher order functions. Partition is one of those higher order functinos that I always forget about and unnecessarily reinvent the wheel.
This higher order function splits a list into several lists using a function to discriminate what list item goes in what list. It is basically a bucket sort. This doesn't exist in the .NET Framework by default, as far as I know. If you want this functionality you may copy/paste my implementation below.
You have a list of people and want to display them in age groups.
var parts = people.Partition(p => p.Age < 25 ? 0 : 1);
var under25 = parts; // A, B var over25 = parts; // C, D, E
This function is build into F# and there returns a touple. This makes it extremely slick to handle the partition result.
val odds : int list = [1; 3; 5; 7; 9] val evens : int list = [2; 4; 6; 8; 10]
What happens, is that partition returns a tuple of the two parts, and F# automatically divides the tuple into two values for us. Not only beautiful, but also very useful.
With C# I find it more useful to return an array with parts, instead of a tuple, because the tuple isn't very well implemented in C#.
The real problem here is expanding the array, because we don't know how many parts we're intending to return. We could use a predicate function and lock the result down to two parts, but that wouldn't be as useful as this.
When you need to split a list into several lists by some discriminating value, the partition function is your friend, simply because it is shorter than throwing out the foreach. It communicates the purpose of your code and makes it clearer to your readers.