Haskell代码行不编译:“非法数据类型上下文” [英] Haskell line of code not compiling: "Illegal datatype context"
问题描述
我不能得到这行代码在Haskell编译,但它的工作在我的教授的系统。我使用ghci版本7.6.2。
data Eq a =形状a =形状a
更准确地说,这是我得到的错误
[1 of 1]编译主(test.hs,解释)
test.hs:1:6:
非法数据类型上下文(使用-XDatatypeContexts):Eq a =>
失败,模块加载:无。
这里有什么错误?
感谢
您的教授可能使用的是旧版本的GHC。您发布的行使用最近已删除的功能。可能的解决方案是:
-
删除
Eq a =>
写数据形状a =形状a
-
如GHC所说,给予
更多详细信息,请访问:> -XDatatypeContexts 您的类型声明的 Eq a =>
部分称为数据类型上下文。它的唯一功能是限制 Shape
构造函数的类型,所以代替 Shape :: a - > Shape a
你会得到 Shape :: Eq a => a - >形成
。它不会让你不必在包含 Shape
的类型签名中写入 Eq a
,甚至要求你写,当你不会需要的时候。在数据类型中的严格字段需要类约束,但该特性很久以前就被删除时,它曾经是有用的。
I am not able to get this line of code compiled in Haskell but it works on my professor's system. I use ghci version 7.6.2.
data Eq a => Shape a = Shape a
More precisely, this is the error I am getting
[1 of 1] Compiling Main ( test.hs, interpreted )
test.hs:1:6:
Illegal datatype context (use -XDatatypeContexts): Eq a =>
Failed, modules loaded: none.
What is the mistake here?
Thanks
Your professor is probably using an older version of GHC. The line you posted uses a feature which has quite recently been removed. The possible solutions are:
Remove
Eq a =>
and writedata Shape a = Shape a
.As GHC says, give the
-XDatatypeContexts
flag to re-enable the removed feature.
In more detail: the Eq a =>
part of your type declaration is called a datatype context. Its only function is to restrict the type of the Shape
constructor, so that instead of Shape :: a -> Shape a
you get Shape :: Eq a => a -> Shape a
. It does not save you from having to write Eq a
in type signatures involving Shape
s, and indeed will even require you to write them when you wouldn't otherwise need to. It was once useful when strict fields in datatypes required a class constraint, but that feature was removed long ago.
In short, just removing the context is nearly always an improvement to your program, so they were removed from the Haskell 2011 language standard. Since GHC 7.0.1 there has been an option to turn them off and since 7.2.1 it has been the default.
这篇关于Haskell代码行不编译:“非法数据类型上下文”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!