Created
November 10, 2010 22:14
-
-
Save petejohanson/671639 to your computer and use it in GitHub Desktop.
ResultComparison<T> 'monad'
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
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"; |
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
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; | |
} | |
} |
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
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