Exception or Either monad in C#

后端 未结 5 655
庸人自扰
庸人自扰 2021-01-31 20:56

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

5条回答
  •  逝去的感伤
    2021-01-31 21:35

    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.

提交回复
热议问题