Haskell line of code not compiling: “Illegal datat

2019-02-05 17:18发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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.