c# - C# 中的 Exception 或 Either monad

标签 c# monads

我正在尝试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);
}

(我们的代码有更多辅助方法,但它们是可选的)

要点是

  • 您只能设置LeftRight
  • 有隐式运算符使实例化更容易
  • 有一个用于模式匹配的Match方法

我还描述了如何 we use this Either type for data validation .

关于c# - C# 中的 Exception 或 Either monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10772727/

相关文章:

c# - 检测到 Entity Framework 自引用循环

haskell - 如何通过隐藏 'state'更改以sig类型编写没有IO的haskell函数

scala - 要么,选项和理解

c# - 将 'Which branch?' 字段添加到 TFS 中的工作项

c# - 如何检查是否存在隐式或显式转换?

c# - 如何合并2本词典

Haskell UI do子句,如何打印?

functional-programming - 我如何在 kind 的 monads 中重复 monadic 指令?

haskell - 将 monad 限制为类型类

c# - 是否可以在 C# 中覆盖分配 "="