Created
November 19, 2013 22:48
-
-
Save timmyshen/7553983 to your computer and use it in GitHub Desktop.
http://davesquared.net/2013/04/side-effect-free-csharp.html
Side-effect free programming in C#
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
namespace SideEffect | |
{ | |
using System; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// SideEffecty(); | |
var prog1 = NotSoSideEffecty(); | |
var prog2 = NotSoSideEffecty(); | |
var prog3 = NotSoSideEffecty(); | |
prog3(); | |
// var program = IO.ReadLine().Then(name => IO.WriteLine("Nice to meet you " + name)); | |
Console.ReadKey(); | |
} | |
static void SideEffecty() | |
{ | |
Console.WriteLine("What's your name?"); | |
var name = Console.ReadLine(); | |
Console.WriteLine("Nice to meet you, " + name); | |
} | |
public static Action NotSoSideEffecty() | |
{ | |
return () => | |
{ | |
Console.WriteLine("What's your name?"); | |
var name = Console.ReadLine(); | |
Console.WriteLine("Nice to meet you, " + name); | |
}; | |
} | |
} | |
public sealed class Unit | |
{ | |
} | |
public sealed class IO<T> | |
{ | |
private readonly Func<T> ioAction; | |
public IO(Func<T> ioAction) | |
{ | |
this.ioAction = ioAction; | |
} | |
public IO<TNext> Then<TNext>(Func<T, IO<TNext>> useVal) | |
{ | |
return new IO<TNext>( | |
() => | |
{ | |
var val = ioAction(); | |
var next = useVal(val); | |
return next.ioAction(); | |
}); | |
} | |
} | |
public static class IO | |
{ | |
public static IO<Unit> WriteLine(string s) | |
{ | |
return new IO<Unit>( | |
() => | |
{ | |
Console.WriteLine(s); | |
return new Unit(); | |
}); | |
} | |
public static IO<string> ReadLine() | |
{ | |
return new IO<string>(Console.ReadLine); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment