Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 11, 2016 11:21
Show Gist options
  • Save miklund/f0ed0514f54cd6d96b3d to your computer and use it in GitHub Desktop.
Save miklund/f0ed0514f54cd6d96b3d to your computer and use it in GitHub Desktop.
2012-06-06 Fold - 7 higher order functions
# Title: Fold - 7 higher order functions
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/06/06/fold-7-higher-order-functions.html
var cats = new[]
{
new Cat(name : "Miss Marple", age : 4),
new Cat(name : "Mr. Quincy", age : 12),
new Cat(name : "Darcy", age : 8)
};
cats.Fold((acc, cat) => acc + cat.Age, 0);
// => 24
public static U Fold<T, U>(Func<U, T, U> fn, IEnumerable<T> list, U init)
{
if (fn == null)
{
throw new ArgumentNullException("fn", "Supplied function to Fold is not allowed to be null");
}
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Fold is not allowed to be null");
}
var result = init;
foreach (var item in list)
{
result = fn(result, item);
}
return result;
}
public static U Fold<T, U>(this IEnumerable<T> list, Func<U, T, U> fn, U init)
{
return Fold(fn, list, init);
}
private T[] GrowArray<T>(T[] acc, T item)
{
var newArray = new T[acc.Length + 1];
acc.CopyTo(newArray, 0);
newArray[acc.Length] = item;
return newArray;
}
var list = new List<int> { 1, 2, 3 };
list.Fold(GrowArray, new int[0]);
// => [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment