问题描述
data数字a =>单位a =单位a(SymbolicManip a)
派生(Eq)
我不是确定如何解决它?
任何人都可以帮助我? >数据类型中的类型类上下文现在被认为是一个不太有用的特性。问题是,以下内容不能编译:
foo ::单位a - > a
foo(Units x _)= x + x
只能为 a
类型构造单元a
参数,满足 Num a
。因此,在销毁(模式匹配)时,应该可以访问 Num a
实例。但是,情况并非如此,在销毁时, Num a
必须违反直觉地被提供:
foo :: Num a =>单位a - > a
foo(Units x _)= x + x
标准建议是从 Units a
数据类型声明中删除约束 Num a
,并将其添加到每个涉及<$ c $的函数中c>单元a 。
另一个选项是启用GADT并将数据类型更改为:
数据单位a其中
单位:: Num a => a - > SymbolicManip a - >单位a
这就是正确的事情:a Num a 实例构造值,而不是 destroy 提供。通过这种方式,上面的第一个
foo
声明将是很好的类型。
我几乎忘记了quick& dirty选项,即启用过时数据类型上下文功能:通过在文件的开头添加行
{ - #LANGUAGE DatatypeContexts# - }
不过,我宁愿修改代码,也不愿意启用此语言扩展。
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?
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.
这篇关于如何解决“非法数据类型上下文” (使用-XDatatypeContexts)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!