Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/c552de57bb1e8c2547d4 to your computer and use it in GitHub Desktop.
Save miklund/c552de57bb1e8c2547d4 to your computer and use it in GitHub Desktop.
2012-06-10 Partition - 7 higher order functions
# Title: Partition - 7 higher order functions
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/06/10/partition-7-higher-order-functions.html
let evens, odds = [1..10] |> List.partition (fun i -> i % 2 = 0)
val odds : int list = [1; 3; 5; 7; 9]
val evens : int list = [2; 4; 6; 8; 10]
public static IEnumerable<T>[] Partition<T>(Func<T, int> fn, IEnumerable<T> list)
{
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Partition is not allowed to be null");
}
if (fn == null)
{
throw new ArgumentNullException("fn", "Supplied function to Partition is not allowed to be null");
}
// Expand the array arr to fit index i
Func<IList<T>[], int, IList<T>[]> expand = (arr, i) =>
{
var newArray = new IList<T>[i + 1];
Array.Copy(arr, newArray, arr.Length);
// Initialize new array
for (var k = arr.Length; k < newArray.Length; k++)
{
newArray[k] = new List<T>();
}
return newArray;
};
var result = new IList<T>[0];
foreach (var item in list)
{
var index = fn(item);
if (index < 0)
{
throw new IndexOutOfRangeException("Your partition function returned index less than 0");
}
// new index
if (index > result.Length - 1)
{
// expand array
result = expand(result, index);
}
result[index].Add(item);
}
return result;
}
public static IEnumerable<T>[] Partition<T>(this IEnumerable<T> list, Func<T, int> fn)
{
return Partition(fn, list);
}
var people = new List<Person>
{
new Person(name: "A", age: 12),
new Person(name: "B", age: 23),
new Person(name: "C", age: 43),
new Person(name: "D", age: 65),
new Person(name: "E", age: 33),
};
var parts = people.Partition(p => p.Age < 25 ? 0 : 1);
var under25 = parts[0]; // A, B
var over25 = parts[1]; // C, D, E
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment