Created
March 16, 2014 06:47
-
-
Save liammclennan/9579460 to your computer and use it in GitHub Desktop.
c# reader
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
void Main() | |
{ | |
var environment = new Environment(30); | |
var composed = DoSomeStuff(); | |
var extracted = composed.RunReader(environment); | |
Console.WriteLine(extracted); | |
} | |
public class Environment { | |
public int Count {get; private set;} | |
public void Log(string message) { | |
Console.WriteLine("logging: " + message); | |
} | |
public Environment(int count) { | |
Count = count; | |
} | |
} | |
public Reader<Environment,Double> DoSomeStuff() { | |
return from i in Reader<Environment,int>.Wrap(e => 65) | |
from d in DivideByCount(i) | |
select d; | |
} | |
public Reader<Environment,double> DivideByCount(int n) { | |
return Reader<Environment,double>.Wrap(e => { | |
e.Log(string.Format("Dividing {0} by {1}", n, e.Count)); | |
return Convert.ToDouble(n) / e.Count; | |
}); | |
} | |
public static class ReaderExt | |
{ | |
public static Reader<TEnv, T> SelectMany<TEnv, A, T, C>(this Reader<TEnv, A> reader, Func<A, Reader<TEnv, T>> bind, Func<A,T,C> select) | |
{ | |
return new Reader<TEnv, T>(environment => | |
{ | |
var a = reader.EnvironmentToValue(environment); | |
return bind(a).EnvironmentToValue(environment); | |
}); | |
} | |
public static T RunReader<TEnv, T>(this Reader<TEnv, T> reader, TEnv environment) { | |
return reader.EnvironmentToValue(environment); | |
} | |
} | |
public class Reader<TEnv, T> { | |
public Func<TEnv,T> EnvironmentToValue; | |
public Reader(Func<TEnv, T> environmentToValue) { | |
EnvironmentToValue = environmentToValue; | |
} | |
public static Reader<TEnv,T> Wrap(Func<TEnv, T> environmentToValue) { | |
return new Reader<TEnv, T>(environmentToValue); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment