Created
January 11, 2016 20:23
-
-
Save miklund/6bbcb6ac19c2e444cf77 to your computer and use it in GitHub Desktop.
2012-06-21 Collect - 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: Collect - 7 higher order functions | |
# Author: Mikael Lundin | |
# Link: http://blog.mikaellundin.name/2012/06/21/collect-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 class BlogPost | |
{ | |
public IEnumerable<Comment> Comments { get; private set; } | |
public static IEnumerable<BlogPost> All() | |
{ | |
// return SELECT blogpost.* FROM db | |
} | |
} | |
var blogPosts = BlogPost.All(); | |
var comments = blogPosts.Collect(post => post.Comments); |
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> Collect<T, U>(Func<T, IEnumerable<U>> fn, IEnumerable<T> list) | |
{ | |
if (list == null) | |
{ | |
throw new ArgumentNullException("list", "Supplied list to Collect is not allowed to be null"); | |
} | |
if (fn == null) | |
{ | |
throw new ArgumentNullException("fn", "Supplied function to Collect is not allowed to be null"); | |
} | |
foreach (var item1 in list) | |
foreach (var item2 in fn(item1)) | |
{ | |
yield return item2; | |
} | |
} | |
public static IEnumerable<U> Collect<T, U>(this IEnumerable<T> list, Func<T, IEnumerable<U>> fn) | |
{ | |
return Collect(fn, list); | |
} |
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 numbers = new[] | |
{ | |
new[] { 1, 2, 3 }, | |
new[] { 4, 5, 6 }, | |
new[] { 7, 8, 9 }, | |
}; | |
var flat = numbers.Collect(arr => arr); | |
// 1, 2, 3, 4, 5, 6, 7, 8, 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment