Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell line of code not compiling: "Illegal datatype context"

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

like image 358
Goutham Avatar asked Sep 21 '13 16:09

Goutham


2 Answers

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.

like image 74
Ben Millwood Avatar answered Nov 04 '22 06:11

Ben Millwood


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.

like image 7
Satvik Avatar answered Nov 04 '22 05:11

Satvik