How to fix “Illegal datatype context” (use -XDatatypeContexts)?

≯℡__Kan透↙ 提交于 2019-12-29 07:17:17

问题


I am a new learner of Haskell, my code is as follows:

data Num a=>Units a = Units a (SymbolicManip a )

      deriving (Eq)

I am not sure how to fix it?

Anyone can help me?


回答1:


Typeclass contexts in datatypes are now regarded as a not so useful feature. The problem is that the following does not compile:

foo :: Units a -> a
foo (Units x _) = x+x

This intuitively should compile, since the Units a argument can only be constructed for a type a satisfying Num a. So, on destruction (pattern matching) one should be able to access the Num a instance. However this is not the case, and a Num a must be counterintuitively provided on destruction as well:

foo :: Num a => Units a -> a
foo (Units x _) = x+x

The standard suggestion is therefore to remove the constraint Num a from the Units a datatype declaration, and add it instead to every function involving Units a.

Another option is to enable GADTs and change the datatype to:

data Units a where
   Units :: Num a => a -> SymbolicManip a -> Units a

This does the "right" thing: a Num a instance is required to construct a value, and is instead provided on destruction. In this way, the first foo declaration above will be well-typed.


I almost forgot the "quick & dirty" option, which is to enable the obsolescent datatype context feature: this is done by adding at the beginning of your file the line

{-# LANGUAGE DatatypeContexts #-}

Still, I would rather modify the code than to enable this language extension.



来源:https://stackoverflow.com/questions/22622399/how-to-fix-illegal-datatype-context-use-xdatatypecontexts

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