Dacleoz
Dacleoz

Reputation: 57

Illegal datatype context

I have to do some exercises on BST and I need to use this implementation for the tree:

data ( Ord a , Show a , Read a ) => BST a = Void | Node {
  val :: a ,
  left , right :: BST a
  } 
   deriving ( Eq , Ord , Read , Show )

But the compiler gives me:

Illegal datatype context (use DatatypeContexts): (Ord a,
                                                      Show a,
                                                      Read a) =>

Can someone help me?

Upvotes: 2

Views: 188

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120751

Data type contexts are generally considered useless, and were for this reason removed from standard Haskell at some point. (There hasn't been an official standard document since 2010, which still contained them, but GHC which is the de-facto standard now does not allow them by default anymore.)

These contexts don't really accomplish anything, except forcing anybody who mentions BST a to also require Ord a, Show a, Read a – but these constraints could not actually be used then anywhere else. So, everything you could do with your constrained version, can also be done with the simpler

data BST a = Void
           | Node { val :: a, left, right :: BST a } 
   deriving (Eq, Ord, Read, Show)

Note that the derived e.g. Ord instance will automatically add Ord a to its context, but without also requiring Read a.

Any function you define for this datatype may also need to impose some of the constraints, but it will need only those that are actually needed for the implementation, not indiscriminately all of them.

Upvotes: 5

Related Questions