Created
January 11, 2016 11:21
-
-
Save miklund/f0ed0514f54cd6d96b3d to your computer and use it in GitHub Desktop.
2012-06-06 Fold - 7 higher order functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Title: Fold - 7 higher order functions | |
# Author: Mikael Lundin | |
# Link: http://blog.mikaellundin.name/2012/06/06/fold-7-higher-order-functions.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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