Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Last active December 18, 2015 17:49
Show Gist options
  • Save dtchepak/5820815 to your computer and use it in GitHub Desktop.
Save dtchepak/5820815 to your computer and use it in GitHub Desktop.
my attempt at reader in c#
using System;
using NUnit.Framework;
namespace Workshop
{
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 SelectMany(reader, f, (a, b) => b);
}
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 t =>
{
var a = reader(t);
var b = f(a)(t);
return selector(a, b);
};
}
}
public class Reader
{
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