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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当传递给返回Just x的lambda时,Haskell如何知道保留Nothing为什么?相关的知识,希望对你有一定的参考价值。

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

Prelude> Nothing >>= (\x -> Just $ x + 3)
Nothing

如果我将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

Prelude> Just Nothing
Just Nothing
答案

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

相反,你正在调用运算符>>=,并且你将它传递给它两个参数:左边的Nothing和右边的lambda表达式。

因此,该表达式的结果将由运算符>>=的定义确定。我们来看看how it is defined for Maybe

(Just x) >>= f  =  f x
Nothing  >>= f  =  Nothing

正如你所看到的,当传递qazxsw poi作为左参数时,运算符qazxsw poi只是立即返回Nothing,并且甚至不打扰作为右参数传递的函数。

以上是关于当传递给返回Just x的lambda时,Haskell如何知道保留Nothing为什么?的主要内容,如果未能解决你的问题,请参考以下文章

使用lambda函数进行向量排序,当不在同一范围内时如何传递变量来捕获组?

Angular/Typescript:声明传递给“find”的lambda的返回类型

如何将事件信息从 aws API Gateway get 传递给 Lambda?

如果 x 在集合 L 中,如何使用 lambda 函数创建返回 true 的函数 L

为啥 lambda 参数在 C++11 中以只读方式传递?

理解 python 中的 lambda 并使用它来传递多个参数