gpt4 book ai didi

Haskell - fmap fmap 不起作用

转载 作者:行者123 更新时间:2023-12-04 17:57:18 25 4
gpt4 key购买 nike

我正在使用 GHCi(版本 6.12.3)和 Haskell 一起玩。我最近阅读了有关仿函数和应用仿函数的文章,我想如果你不能找到类似于 <*> 的东西的话。应用仿函数的数量只能使用仿函数的原语来实现。经过一番思考,我想出了 fmap fmap这将有一个(几乎)理想的类型
Functor f => f (a -> b) -> f (f a -> f b)或更一般地
(Functor f1, Functor f2) => f1 (a -> b) -> f1 (f2 a -> f2 b)
我试过

let q = fmap fmap

我收到以下错误
<interactive>:1:8:
Ambiguous type variable `f1' in the constraint:
`Functor f1' arising from a use of `fmap' at <interactive>:1:8-16
Probable fix: add a type signature that fixes these type variable(s)

<interactive>:1:13:
Ambiguous type variable `f' in the constraint:
`Functor f' arising from a use of `fmap' at <interactive>:1:13-16
Probable fix: add a type signature that fixes these type variable(s)

按照建议编写上述类型签名没有帮助。
最疯狂的是当我输入 :t fmap fmap我得到了与上述相同的类型。

我究竟做错了什么?为什么 fmap fmap尽管 GHCi 为它找到了类型,但给出了类型错误?

最佳答案

看起来您遇到了 monomorphism restriction .

使用 -XNoMonomorphismRestriction 在 GHCi 中尝试您的示例给出你的预期结果。

你也可以通过写 let f x = fmap fmap $ x 来颠覆这个.单态限制仅适用于“看起来像”值的顶级定义,即 f = something ,因此引入显式参数会导致它不再适用。如果这不在顶层(例如在 where 子句中),它也不适用。有关更多详细信息,请参阅链接。

关于Haskell - fmap fmap 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837492/

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