python - 也许 Python 中的 monad 带有方法链

标签 python exception-handling monads method-chaining option-type

我正在尝试在 python 中实现 Maybe monad。 然而,我还想要某种链接能力。

所以我有一个类:

class Maybe:
    def __init__(self, val):
        self.val = val

    def do(self, func):  # Bind function
        if self.val is None:
            return None
        else:
            return func(self.val)

我有两个功能:

def double(number):
    try:
        result = number * 2
        return Maybe(result)
    except:
        return Maybe(None)

def square(number):
    try:
        result = number * number
        return Maybe(result)
    except:
        return Maybe(None)

我是这样使用的:

 result = Maybe(5).do(double).do(square)
    print(result.val)

我正在寻找一种方法来链接多个函数,每个函数执行特定任务。每个函数都将前一个函数的输出作为输入。如果链中的任何函数抛出异常,则链应该中断。

这是对 Maybe monad 建模的正确方法吗?

这也是处理异常的正确方法吗?

这可以改进吗?

非常感谢。

最佳答案

这样做的缺点是它有意抑制错误,这在 Python 中通常被认为是一个坏主意。

但是,您可以捕获并存储在您的 Maybe 实例中发生的任何错误,并将它们报告回来。

例如:

class Maybe(object):
    def __init__(self, val, error=None):
        self.val = val
        self.error = error

    def __repr__(self):
        if self.val is not None:
            return repr(self.val)
        else:
            return repr(self.error)

    def do(self, func):
        if self.val is None:
            return self
        try:
            return Maybe(func(self.val))
        except Exception as e:
            return Maybe(None, e)

def squared(x):
    return x * x

def addone(x):
    return x + 1

result1 = Maybe(5).do(squared).do(addone)
result2 = Maybe('a').do(squared).do(addone)
print result1
print result2

这会产生:

26
TypeError("can't multiply sequence by non-int of type 'str'",)

这类似于 DanD 的回答,但具有存储发生的错误而不是完全抑制错误的优点。

无论您如何剖析它,这个习语都会让人觉得有些“非 Python 风格”,但这是一种稍微更稳健的处理方式。

关于python - 也许 Python 中的 monad 带有方法链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28607666/

相关文章:

python - 无法理解 Perl 中的正则表达式修饰符以转换为 Python

python - 如何在构建过程中安装私有(private) Python 包

python - django基础博客CSRF验证失败。请求已中止

python - 异常处理程序,用于检查变量的内联脚本是否有效

haskell - 如何使用 putStrLn 进行跟踪(Haskell)

haskell - 返回 IO 操作的后果是什么?

python - Flask-Admin (python) - 覆盖模板时遇到问题

c# - 为什么要使用特定的异常捕获 block

c++ - 我应该何时以及如何使用异常处理?

scala - 在 scala 中,为什么 list.flatMap(List) 不起作用?