Created
January 11, 2016 10:37
-
-
Save miklund/139c93a005595933334c to your computer and use it in GitHub Desktop.
2012-06-03 Map - 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: Map - 7 higher order functions | |
# Author: Mikael Lundin | |
# Link: http://blog.mikaellundin.name/2012/06/03/map-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
private int Double(int i) | |
{ | |
return i * 2; | |
} | |
Map(Double, new [] {1, 2, 3}); |
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 IEnumerable<U> Map<T, U>(Func<T, U> fn, IEnumerable<T> list) | |
{ | |
if (fn == null) | |
{ | |
throw new ArgumentNullException("fn", "Supplied function to Map is not allowed to be null"); | |
} | |
if (list == null) | |
{ | |
throw new ArgumentNullException("list", "Supplied list to Map is not allowed to be null"); | |
} | |
foreach (var item in list) | |
{ | |
yield return fn(item); | |
} | |
} | |
Map(i => i.ToString(), new[] {1, 2, 3}) | |
-> ["1", "2", "3"] |
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 people = new[] | |
{ | |
new Person { FirstName = "Mikael", Surname = "Lundin" }, | |
new Person { FirstName = "John", Surname = "Doe" }, | |
new Person { FirstName = "Foo", Surname = "Bar" }, | |
}; | |
var names = people.Select(p => p.FirstName + " " + p.Surname); | |
/* | |
=> new [] { | |
"Mikael Lundin", | |
"John Doe", | |
"Foo Bar" | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment