gpt4 book ai didi

haskell - 当传递给返回 Just x 的 lambda 时,Haskell 如何知道将 Nothing 保留为空?

转载 作者:行者123 更新时间:2023-12-02 02:50:24 25 4
gpt4 key购买 nike

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

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 的值.

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

因此,该表达式的结果将由运算符 >>= 的定义决定。 .一起来看看how it is defined for Maybe :

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

如您所见,当通过时 Nothing作为左参数,运算符 >>=只需返回 Nothing马上,甚至不打扰作为正确参数传递的函数。

关于haskell - 当传递给返回 Just x 的 lambda 时,Haskell 如何知道将 Nothing 保留为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com