-
-
Save wk-j/e2d8e641b000b54bc2c23e67bc9fd4a8 to your computer and use it in GitHub Desktop.
Compiling SelectMany Linq without System.Linq. Also a List Monad.
This file contains 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
using System; | |
using System.Collections.Generic; | |
public static class ExtensionMethods | |
{ | |
public static IEnumerable<T> ToList<T>(this T value) { | |
yield return value; | |
} | |
public static IEnumerable<U> SelectMany<T, U>(this IEnumerable<T> m, Func<T, IEnumerable<U>> k) | |
{ | |
foreach (var x in m) | |
foreach (var y in k(x)) | |
yield return y; | |
} | |
public static IEnumerable<V> SelectMany<T, U, V>(this IEnumerable<T> id, Func<T, IEnumerable<U>> k, Func<T,U,V> s) | |
{ | |
return id.SelectMany(x => k(x).SelectMany(y => s(x, y).ToList())); | |
} | |
} | |
public class ListMonad | |
{ | |
public static void WithExtensions() | |
{ | |
IEnumerable<string> list1 = new string[] {"1", "2", "3"}; | |
IEnumerable<string> list2 = new string[] {"c", "d"}; | |
var r = list1.SelectMany( | |
x => list2, (x, y) => x + y); | |
foreach (var i in r) | |
Console.WriteLine(i); | |
} | |
public static void WithLinq() | |
{ | |
IEnumerable<string> list1 = new string[] {"1", "2", "3"}; | |
IEnumerable<string> list2 = new string[] {"c", "d"}; | |
var r = from x in list1 | |
from y in list2 | |
select x + y; | |
foreach (var i in r) | |
Console.WriteLine(i); | |
} | |
public static void Main() | |
{ | |
Console.WriteLine("With Extension Methods"); | |
WithExtensions(); | |
Console.WriteLine(""); | |
Console.WriteLine("With Linq"); | |
WithLinq(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment