gpt4 book ai didi

haskell - 为什么 `pure`的 `Applicative Maybe`定义为 `pure = Just`而忽略 `Nothing`?

转载 作者:行者123 更新时间:2023-12-02 06:27:31 27 4
gpt4 key购买 nike

source code of GHC.Base , Applicative Maybe 定义为:

instance Applicative Maybe where
pure = Just
...

我想知道为什么 pure 的定义忽略了 Nothing

根据这个定义,我期待

pure Nothing 应该减少到 Just Nothing 因为 pure = Just

Prelude> Just Nothing
Just Nothing

而不是实际上:

Prelude> pure Nothing
Nothing

为什么这么神奇?我的错是什么?谢谢!

最佳答案

不会忽略Nothing , 但您需要为 which 指定 Applicative你运行 pure函数,如果我们用 -XTypeApplications 运行它, 我们可以指定 Applicative 的类型,然后我们得到:

$ ghci -XTypeApplications
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Prelude> pure @Maybe Nothing
Just Nothing

如果不指定类型,解释器将“默认”为某个Applicative (在本例中为 IO )变体,这意味着它将返回值,并且解释器的标准行为是在 IO 中打印值“包装”外壳。

为什么Applicative的原因需要 pure = Just , 是因为它必须与 Functor 一致实例。这个仿函数实例定义为:

instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap _ Nothing = Nothing

现在需要满足的定律之一是:

fmap f x = pure f <*> x

如果我们定义 pure _ = Nothing , 那么这将意味着 fmap f x = Nothing <*> x这意味着我们“丢失了”关于 f 的信息.因此,唯一合理的解决方案可能是 fmap总是返回 Nothing ,但作为仿函数,这没有多大意义。它将进一步违反仿函数级别的另一个约束,即 fmap id x应该总是返回 x .

关于haskell - 为什么 `pure`的 `Applicative Maybe`定义为 `pure = Just`而忽略 `Nothing`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021094/

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