当Haskell传递给返回Just x的lambda时,如何知道什么都不保留?

pap*_*uck 4 haskell

我只是想了解为什么这不会出错:

Prelude> Nothing >>= (\x -> Just $ x + 3)
Nothing
Run Code Online (Sandbox Code Playgroud)

如果我将lambda分解为各个步骤:

Prelude> Nothing + 3

<interactive>:8:1: error:
    • Non type-variable argument in the constraint: Num (Maybe a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. Num (Maybe a) => Maybe a
Run Code Online (Sandbox Code Playgroud)

Prelude> Just Nothing
Just Nothing
Run Code Online (Sandbox Code Playgroud)

Fyo*_*kin 20

当您编写时Nothing >>= (\x -> Just $ x + 3),这与完全不同Just $ Nothing + 3。您实际上并没有传递Nothing的值x

相反,您要调用operator >>=,并将两个参数传递给它:Nothing左侧是lambda表达式。

因此,该表达式的结果将由operator的定义确定>>=。让我们看看它是如何定义的Maybe

(Just x) >>= f  =  f x
Nothing  >>= f  =  Nothing
Run Code Online (Sandbox Code Playgroud)

如您所见,当Nothing作为左参数传递时,运算符>>=只是立即返回Nothing,甚至不理会作为右参数传递的函数。

  • 我已经考虑过@chepner了,但是认为它可能确实令人困惑,因为现在我还需要解释下划线的含义,并且这不是魔术的一部分。 (2认同)