Created
June 5, 2013 18:37
-
-
Save Fitzse/5716111 to your computer and use it in GitHub Desktop.
ExceptionSafe Monad Example
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() | |
{ | |
Func<int,ExceptionSafe<int>> first = x => (1000 - x).ToSafe(); | |
Func<int,ExceptionSafe<int>> second = x => (100/x).ToSafe(); | |
Func<int,ExceptionSafe<double>> third = x => (0.68 * x).ToSafe(); | |
Func<int,ExceptionSafe<double>> composed = first.Compose(second).Compose(third); | |
900.ToSafe().ApplyFunction(composed).Dump(); | |
} | |
public class ExceptionSafe<T>{ | |
private T _value; | |
public Exception Exception{get;private set;} | |
public ExceptionSafe(T value){ | |
_value=value; | |
} | |
public T Value{get{return _value;}} | |
public ExceptionSafe(){} | |
public void SetException(Exception ex){ | |
Exception = ex; | |
} | |
public ExceptionSafe<U> ApplyFunction<U>(Func<T,ExceptionSafe<U>> fun){ | |
var value = new ExceptionSafe<U>(); | |
try{ | |
value = fun(_value); | |
if(Exception != null){ | |
value.SetException(Exception); | |
} | |
} | |
catch(Exception ex){ | |
value.SetException(ex); | |
} | |
return value; | |
} | |
} | |
public static class MyExtensions{ | |
public static Func<T,V> Compose<T,U,V>(this Func<T,U> first, Func<U,V> second){ | |
return (T x) => second(first(x)); | |
} | |
public static Func<T,ExceptionSafe<V>> Compose<T,U,V>(this Func<T,ExceptionSafe<U>> first, Func<U,ExceptionSafe<V>> second){ | |
return (T x) => first(x).ApplyFunction(second); | |
} | |
public static ExceptionSafe<T> ToSafe<T>(this T value){ | |
return new ExceptionSafe<T>(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment