Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 11, 2016 19:49
Show Gist options
  • Save miklund/3b103e33357610ad896d to your computer and use it in GitHub Desktop.
Save miklund/3b103e33357610ad896d to your computer and use it in GitHub Desktop.
2012-06-16 Reduce - 7 higher order functions
# Title:
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/06/16/reduce-7-higher-order-functions.html
public static T Reduce<T>(Func<T, T, T> fn, IEnumerable<T> list)
{
if (list == null)
{
throw new ArgumentNullException("list", "Supplied list to Reduce is not allowed to be null");
}
if (fn == null)
{
throw new ArgumentNullException("fn", "Supplied function to Reduce is not allowed to be null");
}
IEnumerator<T> enumerator = list.GetEnumerator();
if (!enumerator.MoveNext())
{
throw new ArgumentException("Can't run reduce on an empty list", "list");
}
var result = enumerator.Current;
while (enumerator.MoveNext())
{
result = fn(result, enumerator.Current);
}
return result;
}
public static T Reduce<T>(this IEnumerable<T> list, Func<T, T, T> fn)
{
return Reduce(fn, list);
}
public int Sum(int[] numbers)
{
return numbers.Reduce((a, b) => a + b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment