Last active
August 29, 2015 13:57
-
-
Save badmotorfinger/9618765 to your computer and use it in GitHub Desktop.
Use LINQ query expressions without requiring IEnumerables, to compose 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
// Full credit goes to Wes Dyer http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx | |
// Explanation of how query expressions are translated in to extension method syntax. | |
public class Identity<T> | |
{ | |
public T Value { get; private set; } | |
public Identity(T value) { this.Value = value; } | |
public static implicit operator Identity<T>(T value) { | |
return new Identity<T>(value); | |
} | |
} | |
static class MonadicExtensions | |
{ | |
// "Hijack" LINQ query expressions so that IEnumerable<T> isn't a requirement. | |
public static Identity<Z> SelectMany<T,R,Z>( | |
this Identity<T> source, | |
Func<T, Identity<R>> function, | |
Func<T,R,Z> s) { | |
T unwrapped = source.Value; | |
Identity<R> result = function(unwrapped); | |
return s(unwrapped, result.Value); | |
} | |
public static Identity<T> ToIdentity<T>(this T value) { | |
return value; | |
} | |
} | |
void Main() | |
{ | |
// Returns Identity<int>, not IEnumerable or IQueryable. | |
var results = | |
from x in 5.ToIdentity() | |
from y in 10.ToIdentity() | |
select x + y; | |
Console.WriteLine (results); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment