gpt4 book ai didi

haskell - 为什么 Haskell 不允许这种声明?

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

我知道 FunctorApplicative 应该是 Monad 的父类(super class),但由于历史原因并非如此。但是,为什么不能将 Monad 声明为 Functor 的实例?这将具有大致相同的效果,但无需修改现有代码。如果您尝试这样做,GHC 会提示:

instance Functor Monad where
fmap = liftM

Class `Monad' used as a type
In the instance declaration for `Functor Monad'

这是为什么呢?这可能是有充分理由的。

最佳答案

你的语法错误。 Monad是类型类,而不是数据类型。你可以写的是

instance Monad a => Functor a where fmap = liftM

但是,这仅适用于扩展 FlexibleInstances (允许不是 T a<sub>1</sub> a<sub>2</sub> ... a<sub>n</sub> 形式的实例,其中 a<sub>1</sub>, a<sub>2</sub>, ... a<sub>n</sub> 是类型变量并且没有上下文)和 UndecidableInstances (这允许这个特定的实例[我不知道为什么需要这个])。

关于haskell - 为什么 Haskell 不允许这种声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7595023/

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