简化Monad

Dev*_*aha 10 python monads haskell

我想了解也许 单子,但大多数的例子,我看到用一些特定的语言特征.为了确保我在概念上得到它,我想到了编写通用实现.以下是我提出的建议.

有人能说出我是否在概念上得到了它吗?有没有更好的方法来概括它?

def f():
    return 2

def g():
    return 4

def h():
    return 7

def i():
    return None

def bind(val, func):
    if val is None:
        return None
    else:
        return(func())

unit = 0

>>> bind(bind(bind(unit,f),i),h) #Returns nothing
>>> bind(bind(bind(unit,f),g),h) #Returns a value
>>>7 
Run Code Online (Sandbox Code Playgroud)

如果我想从这些函数中添加值并在其中任何一个为NULL时中止,该怎么办?有什么建议吗?

Dan*_*zer 9

你很亲密,但签名bind

m a -> (a -> m b) -> m b
Run Code Online (Sandbox Code Playgroud)

所以它是"展开" m并将包含的值传递给下一个函数.你现在有

m a -> ( () -> m b) -> m b
Run Code Online (Sandbox Code Playgroud)

因为你只是忽略了val绑定,你应该有

def bind(val, func):
    if val is None:
        return None
    else:
        return(func(val))
Run Code Online (Sandbox Code Playgroud)

这相当于>>=Haskell.以前你>>应该实现的是什么

# "ignore" bind
def ibind(val, func):
    bind(val, lambda _ : func())
Run Code Online (Sandbox Code Playgroud)

只是幸福地抛弃了价值bind传递它.

为了更进一步,你必须介绍一个课程

class Maybe():
    def __init__(v):
        self.val = v
        self.isNothing = False
Nothing = Maybe(None)
Nothing.isNothing = True

def bind(val, func):
    if val.isNothing:
        return Nothing
    else:
        return(func(val.val))
Run Code Online (Sandbox Code Playgroud)

  • @Joehillen你不能,但作为理解monads的概念性例子,我认为这很好 (2认同)
  • @DevMaha更改你的函数,这样他们就可以使用`ibind`而不是`bind`来获取参数或使用你的函数. (2认同)