Haskell line of code not compiling: “Illegal datatype context”

我与影子孤独终老i 提交于 2019-11-30 04:36:47

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:

  1. Remove Eq a => and write data Shape a = Shape a.

  2. 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 Shapes, 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.

I think the error message is clear in what it says. You need an extension for that.

{-# LANGUAGE DatatypeContexts #-}
data Eq a => Foo a = Foo a

Although this extension used to be on by default but starting from ghc 7.6, its usage is considered deprecated and will be removed in the future. So your professor might be using an older version of ghc.

Boyd Stephen Smith Jr.

See also https://stackoverflow.com/a/22622591/2008899 which explains the "Why?" behind the language change as well as showing a GADT example that does what datatype contexts was supposed to provide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!