I am trying to grok get a preliminary understanding of monads.
I have a data layer call whose result I would like to return monadically either as a result e
While learning a bit about monads in C#, for exercise I implemented an Exceptional
monad for myself. With this monad, you can chain up operations that might throw an Exception
like in these 2 examples:
var exc1 = from x in 0.ToExceptional()
from y in Exceptional.Execute(() => 6 / x)
from z in 7.ToExceptional()
select x + y + z;
Console.WriteLine("Exceptional Result 1: " + exc1);
var exc2 = Exceptional.From(0)
.ThenExecute(x => x + 6 / x)
.ThenExecute(y => y + 7);
Console.WriteLine("Exceptional Result 2: " + exc2);
Both expressions yield the same result, just the syntax is different. The result will be an Exceptional<T>
with the arisen DivideByZeroException
set as property. The first example shows the "core" of the monad using LINQ, the second contains a different and perhaps more readable syntax, which illustrates the method chaining in a more understandable way.
So, how it's implemented? Here's the Exceptional<T>
type:
public class Exceptional<T>
{
public bool HasException { get; private set; }
public Exception Exception { get; private set; }
public T Value { get; private set; }
public Exceptional(T value)
{
HasException = false;
Value = value;
}
public Exceptional(Exception exception)
{
HasException = true;
Exception = exception;
}
public Exceptional(Func<T> getValue)
{
try
{
Value = getValue();
HasException = false;
}
catch (Exception exc)
{
Exception = exc;
HasException = true;
}
}
public override string ToString()
{
return (this.HasException ? Exception.GetType().Name : ((Value != null) ? Value.ToString() : "null"));
}
}
The monad is completed through extension methods ToExceptional<T>()
and SelectMany<T, U>()
, that correspond to the monad's Unit and Bind functions:
public static class ExceptionalMonadExtensions
{
public static Exceptional<T> ToExceptional<T>(this T value)
{
return new Exceptional<T>(value);
}
public static Exceptional<T> ToExceptional<T>(this Func<T> getValue)
{
return new Exceptional<T>(getValue);
}
public static Exceptional<U> SelectMany<T, U>(this Exceptional<T> value, Func<T, Exceptional<U>> k)
{
return (value.HasException)
? new Exceptional<U>(value.Exception)
: k(value.Value);
}
public static Exceptional<V> SelectMany<T, U, V>(this Exceptional<T> value, Func<T, Exceptional<U>> k, Func<T, U, V> m)
{
return value.SelectMany(t => k(t).SelectMany(u => m(t, u).ToExceptional()));
}
}
And some little helper structures, that are not part of the monad's core:
public static class Exceptional
{
public static Exceptional<T> From<T>(T value)
{
return value.ToExceptional();
}
public static Exceptional<T> Execute<T>(Func<T> getValue)
{
return getValue.ToExceptional();
}
}
public static class ExceptionalExtensions
{
public static Exceptional<U> ThenExecute<T, U>(this Exceptional<T> value, Func<T, U> getValue)
{
return value.SelectMany(x => Exceptional.Execute(() => getValue(x)));
}
}
Some explanation: a method chain built with this monad is executed as long as one method of the chain throws an exception. In this case no more method of the chain will be executed and the first thrown exception will be returned as part of an Exceptional<T>
result. In this case the HasException
and Exception
properties will be set. If no Exception
occurs, HasException
will be false
and the Value
property will be set, containing the result of the executed method chain.
Note that the Exceptional<T>(Func<T> getValue)
constructor is responsible for the exception handling and the SelectMany<T,U>()
method is responsible for distinguishing if a method, that was executed before, has thrown an exception.
So - don't know if anyone is interested - I've come up with a very preliminary implementation very much following Mike Hadlow's lead. Some of it doesn't feel quite right atm but it is a start. (Having said that, I wouldn't use it - you might lose a million dollars or even kill someone - just my caveat!)
A very simple sample of the kind of code that could be written is
var exp = from a in 12.Div(2)
from b in a.Div(2)
select a + b;
Assert.AreEqual(9, exp.Value());
var exp = from a in 12.Div(0)
from b in a.Div(2)
select b;
Assert.IsTrue(exp.IsException());
with the Div method implemented as follows:
public static IExceptional<int> Div(this int numerator, int denominator)
{
return denominator == 0
? new DivideByZeroException().ToExceptional<int, DivideByZeroException>()
: (numerator / denominator).ToExceptional();
}
or
public static IExceptional<int> Div_Throw(this int numerator, int denominator)
{
try
{
return (numerator / denominator).ToExceptional();
}
catch (DivideByZeroException e)
{
return e.ToExceptional<int, DivideByZeroException>();
}
}
(Straight away I can see an potential improvement to the api but am unsure quite how to achieve it. I think that this
new DivideByZeroException().ToExceptional<int, DivideByZeroException>()
would be nicer if it were
new DivideByZeroException().ToExceptional<int>()
You'll see my implementation later and hopefully someone will be able to re-architect it for the above.)
The monadic bit is done in here (mainly)
public static class Exceptional
{
public static IExceptional<TValue> ToExceptional<TValue>(this TValue result)
{
return new Value<TValue>(result);
}
public static IExceptional<TValue> ToExceptional<TValue,TException>(this TException exception) where TException : System.Exception
{
return new Exception<TValue, TException>(exception);
}
public static IExceptional<TResultOut> Bind<TResultIn, TResultOut>(this IExceptional<TResultIn> first, Func<TResultIn, IExceptional<TResultOut>> func)
{
return first.IsException() ?
((IInternalException)first).Copy<TResultOut>() :
func(first.Value());
}
public static IExceptional<TResultOut> SelectMany<TResultIn, TResultBind, TResultOut>(this IExceptional<TResultIn> first, Func<TResultIn, IExceptional<TResultBind>> func, Func<TResultIn, TResultBind, TResultOut> select)
{
return first.Bind(aval => func(aval)
.Bind(bval => select(aval, bval)
.ToExceptional()));
}
}
The main interface is specified as
public interface IExceptional<TValue>
{
bool IsException();
TValue Value();
}
and I have an internal interface I use to get at the exception which has been thrown (more later)
internal interface IInternalException
{
IExceptional<TValue> Copy<TValue>();
}
The concrete implementations are as follows:
public class Value<TValue> : IExceptional<TValue>
{
TValue _value = default(TValue);
public Value(TValue value)
{
_value = value;
}
bool IExceptional<TValue>.IsException()
{
return false;
}
TValue IExceptional<TValue>.Value()
{
return _value;
}
}
public class Exception<TValue, TException> : IInternalException, IExceptional<TValue> where TException : System.Exception
{
TException _exception = default(TException);
public Exception(TException exception)
{
_exception = exception;
}
bool IExceptional<TValue>.IsException()
{
return true;
}
IExceptional<TOutValue> IInternalException.Copy<TOutValue>()
{
return _exception.ToExceptional<TOutValue,TException>();
}
TException GetException()
{
return _exception;
}
TValue IExceptional<TValue>.Value()
{
return default(TValue);
}
}
Just a word of explanation ... the trickiest bit, for me, was the Bind operation when an exception has arisen. If you are dealing with a pipeline of operations and an exception gets thrown early on in the process, you need to perpetuate that exception down the pipeline so that when the expression completes the returning IExceptional contains the exception which occurred earlier. This is the reason for the IInternalException. It enables me to create a new IExceptional of the same or (potentially different) type (eg IExceptional --> IExceptional) but copies across the exception to the new IExceptional without me having to know the type of the internal exception.
No doubt there are loads of improvements possible. eg I could see that you may potentially want to keep track of the error stack within the IExceptional. There is probably redundant code or better ways to achieve the ends ... but ... it was meant to be a bit of learning for me.
Any thoughts/suggestions would be gratefully received.
It's worth noting that there are C# libraries available now that contain implementations of Either
:
language-ext library is available for .Net 4.5.1 and .Net Standard 1.3
LaYumba library is available for .Net Standard 1.6 and .Net Core 1.1.
Both libraries are well documented, with LaYumba being used as the basis of the Manning book Functional Programming in C#.
C# doesn't have much support for monads (and the support that is there in the form of LINQ wasn't really meant for general monads), there are no built-in Exception or Either monads. You should throw
the exception and then catch
it.
We have implemented Either
data structure in our C# solution and we are happy using it. Here is the most simple version of such implementation:
public class Either<TL, TR>
{
private readonly TL left;
private readonly TR right;
private readonly bool isLeft;
public Either(TL left)
{
this.left = left;
this.isLeft = true;
}
public Either(TR right)
{
this.right = right;
this.isLeft = false;
}
public T Match<T>(Func<TL, T> leftFunc, Func<TR, T> rightFunc)
=> this.isLeft ? leftFunc(this.left) : rightFunc(this.right);
public static implicit operator Either<TL, TR>(TL left) => new Either<TL, TR>(left);
public static implicit operator Either<TL, TR>(TR right) => new Either<TL, TR>(right);
}
(our code has more helper methods, but they are optional)
The main points are
Left
or Right
I've also described how we use this Either type for data validation.