Skip to content

Instantly share code, notes, and snippets.

@petejohanson
Created November 10, 2010 22:14
Show Gist options
  • Save petejohanson/671639 to your computer and use it in GitHub Desktop.
Save petejohanson/671639 to your computer and use it in GitHub Desktop.
ResultComparison<T> 'monad'
string val;
int comp = Comparer<int>.Default.Compare (0, 1);
if (comp > 0)
val = "greater than";
else if (comp < 0)
val = "less than";
else
val = "equal";
public static class Comparison
{
public static ResultComparison<TResult> ToComparison<TSource, TResult> (this IComparer<TSource> comparer, TSource, x, TSource y)
{
if (comparer == null) throw new ArgumentNullException ("comparer");
return new ResultComparison<TResult> (comparer.Compare (x, y));
}
}
public class ResultComparison<T>
{
T Result
{
get;
private set;
}
int _comparison;
public ResultComparison<T> Equal (Func<T> func)
{
if (_comparison == 0)
Result = func ();
return this;
}
public ResultComparison<T> LessThan (Func<T> func)
{
if (_comparison < 0)
Result = func ();
return this;
}
public ResultComparison<T> GreaterThan (Func<T> func)
{
if (_comparison > 0)
Result = func ();
return this;
}
public ResultComparison (int comparison)
{
_comparison = comparison;
}
}
string val = Comparer<int>.Default
.ToComparison<int, string> (0, 1))
.GreaterThan (() => "greater than")
.LessThan (() => "less than")
.Equal (() => "equal")
.Result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment