我正在尝试grok 初步了解monad。
我有一个数据层调用,我想单次返回其结果,例如没有更新的行/数据集等,或者是异常。我认为我需要使用 Exception monad,我可以将其视为 Either monad 的特例
我查看了各种样本 - 大量的 Maybe 样本,我不太确定如何或是否将其概括为 Either monad - 但我找不到任何不在 haskell 中的 - 并且,不幸的是,我绝对不会理解 haskell!
我想知道是否有人可以向我指出任何示例。
最佳答案
我们已经在我们的 C# 解决方案中实现了 Either
数据结构,我们很高兴使用它。这是此类实现的最简单版本:
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);
}
(我们的代码有更多辅助方法,但它们是可选的)
要点是
- 您只能设置
Left
或Right
- 有隐式运算符使实例化更容易
- 有一个用于模式匹配的Match方法
关于c# - C# 中的 Exception 或 Either monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10772727/