Skip to content

Instantly share code, notes, and snippets.

@yukitos
Created November 19, 2015 06:28
Show Gist options
  • Save yukitos/67912d9629ae1c685ae5 to your computer and use it in GitHub Desktop.
Save yukitos/67912d9629ae1c685ae5 to your computer and use it in GitHub Desktop.
class Program
{
static void Main()
{
var result =
Expr.If(DateTime.Now.Second % 2 == 0)
.Then(() =>
{
Console.WriteLine("Then clause handled.");
return 0;
})
.Else(() =>
{
Console.WriteLine("Else clause handled.");
return 1;
});
Console.WriteLine("Result: " + result.Value);
}
}
class Expr
{
public static ExprIf If(bool cond)
{
return new ExprIf { Condition = cond };
}
}
class ExprIf
{
public bool Condition { get; set;}
}
class ExprThen<T>
{
public T Value { get; set; }
public bool Handled { get; set;}
}
class ExprElse<T>
{
public T Value { get; set;}
}
static class Extensions
{
public static ExprThen<T> Then<T>(this ExprIf expr, Func<T> body)
{
if (expr.Condition)
{
return new ExprThen<T> { Value = body(), Handled = true };
}
return new ExprThen<T> { Value = default(T), Handled = false };
}
public static ExprElse<T> Else<T>(this ExprThen<T> expr, Func<T> body)
{
if (expr.Handled)
return new ExprElse<T> { Value = expr.Value };
return new ExprElse<T> { Value = body() };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment