Last active
August 29, 2015 13:57
-
-
Save dtchepak/9581781 to your computer and use it in GitHub Desktop.
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 class ReaderExtensions | |
{ | |
public static Func<T, B> Select<T, A, B>(this Func<T, A> reader, Func<A, B> f) | |
{ | |
return t => f(reader(t)); | |
} | |
public static Func<T, B> SelectMany<T, A, B>(this Func<T, A> reader, Func<A, Func<T, B>> f) | |
{ | |
return t =>f(reader(t))(t); | |
} | |
public static Func<T, C> SelectMany<T, A, B, C>(this Func<T, A> reader, Func<A, Func<T, B>> f, Func<A, B, C> selector) | |
{ | |
return reader.SelectMany(a => f(a).Select(b => selector(a, b))); | |
} | |
} |
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 class ReaderExamples | |
{ | |
Func<int, int> add1 = x => x + 1; | |
Func<int, string> show = x => x.ToString(); | |
[Test] | |
public void Example1() | |
{ | |
var incAndShow = add1.Select(show); | |
Assert.AreEqual("2", incAndShow(1)); | |
} | |
[Test] | |
public void Example2() | |
{ | |
var incAndShow = from next in add1 | |
select show(next); | |
Assert.AreEqual("2", incAndShow(1)); | |
} | |
[Test] | |
public void Example3() | |
{ | |
var incAndShow = add1.SelectMany<int, int, string>(a => t => show(a)); | |
Assert.AreEqual("2", incAndShow(1)); | |
} | |
[Test] | |
public void Example4() | |
{ | |
var incPlusShow = from next in add1 | |
from shown in show | |
select (next + " " + shown); | |
Assert.AreEqual("2 1", incPlusShow(1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment