gpt4 book ai didi

haskell - 为什么 "instance Monad (Gang String) where "编译错误

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

在我编写以下代码的地方,Haskell 无法编译。

data Gang b a=Gang{getGang::(a,b)}
instance Monad (Gang String) where
return x = Gang (x,"")
(Gang(x,log)) >>=f = let Gang(x1,log1)= f x in Gang(x1,log++log1)

编译器输出:

Illegal instance declaration for `Monad (Gang String)'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Monad (Gang String)'

在我使用“ghci -XFlexibleInstances”启动 ghci 并加载文件后,它编译成功。为什么?

最佳答案

The Haskell Report restricts类型类实例中允许出现的内容(默认情况下)

(Section 4.3.2) ... The type (T u1 … uk) must take the form of a type constructor T applied to simple type variables u1, … uk; furthermore, T must not be a type synonym, and the ui must all be distinct.

松散地翻译,允许实例应用于类型构造函数(不是同义词,所以像 ListMaybe 甚至像 Int) 只要传递给构造函数的所有参数都是唯一的类型变量。

在您的例子中,Gang 是一个类型构造器,但 String 不是一个类型变量。它甚至不是类型构造函数!它是具体类型 [Char] 的类型同义词。

事实证明这是过度限制。放宽对所有传递的参数都是变量的要求是有意义的。允许类型同义词甚至是有意义的。但是,由于这些放宽不是标准化的,因此需要您传递 LANGUAGE 编译指示或编译器标志,以表明您使用的是非标准扩展。

{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}

通常这些 pragma 注释是非常可取的,因为非标准的 Haskellisms 的使用发生在特定的文件中。您也可以在旁边标明所需的 Haskell 扩展。

关于haskell - 为什么 "instance Monad (Gang String) where "编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276570/

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