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
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
{
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(Func leftFunc, Func rightFunc)
=> this.isLeft ? leftFunc(this.left) : rightFunc(this.right);
public static implicit operator Either(TL left) => new Either(left);
public static implicit operator Either(TR right) => new Either(right);
}
(our code has more helper methods, but they are optional)
The main points are
- You are only able to set
Left
or Right
- There are implicit operators to make instantiation easier
- There is a Match method for pattern matching
I've also described how we use this Either type for data validation.
- 热议问题