我只是想了解为什么这不会出错:
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,甚至不理会作为右参数传递的函数。