return 1-6ren">
gpt4 book ai didi

haskell - 我想我找到了一个 "non-existent monad"

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

我发现了 Haskell 的一个奇怪特性,它让我相信我的思维方式是错误的。我认为在 Haskell 中,应该有一些“不存在”的单子(monad)。这是因为以下原因。

Prelude> return 1
1
Prelude> return 1 >>= \x -> if even x then return True else return False
False
>>=m a -> (a -> m b) -> m b 类型在哪里 m可以是任何单子(monad)。我的理论是这样的:因为 return 1计算结果仅为 1 , return 1可以认为是 1提升到包裹在“不存在的”单子(monad)中的值。 Haskell 捕捉到了这一事实并评估了整个表达式
return 1 >>= \x -> if even x then return True else return False

False因为它必须产生一个“不存在的 False”,它只是一个 False .

但是,我以前从未听说过这种“不存在”的单子(monad)。

我确定我以错误的方式对其进行理论化,因为如果“不存在 1”只是 1 ,下面的表达式必须是类型一致的,但事实并非如此。它是上述版本的修改版本。
1 >>= \x -> if even x then return True else return False

<interactive>:57:1: error:
• Could not deduce (Integral a0)
from the context: (Monad m, Integral a, Num (m a))
bound by the inferred type for ‘it’:
forall (m :: * -> *) a. (Monad m, Integral a, Num (m a)) => m Bool
at <interactive>:57:1-56
The type variable ‘a0’ is ambiguous
• In the ambiguity check for the inferred type for ‘it’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
When checking the inferred type
it :: forall (m :: * -> *) a.
(Monad m, Integral a, Num (m a)) =>
m Bool

所以,我的理论一定有矛盾。我错过了什么?

最佳答案

return 1不仅仅是1 .你认为的“不存在的单子(monad)”真的是IO .当您使用 return 1 , GHCi 假设您的意思是 IO ,然后帮助执行 IO 表达式并显示结果。 1 >>= ... 出现类型错误因为1不是单子(monad)。

@bradrn提到 in the comments , 通常 GHCi 会自动运行任何 IO a你给它的值,然后打印出它返回的值;如果你给 GHCi 一个非 IO输入值,它只会打印该值(如果可以的话)。

顺便说一句,有一个叫做 Identity 的单子(monad)。正如您所说,它本质上确实是一个“不存在的单子(monad)”,在 return xx 同构不管你在里面放了什么。但是,它不会自动使用。您需要手动包装和打开它才能使用它。

关于haskell - 我想我找到了一个 "non-existent monad",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899103/

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