Haskell:实例参数化类型一个单一类型
我正在编写一些解析器代码,其中涉及一个参数化类型:Haskell:实例参数化类型一个单一类型,haskell,instance,typeclass,Haskell,Instance,Typeclass,我正在编写一些解析器代码,其中涉及一个参数化类型: data Power i=Power1{charges::i}Power2{charges::i} 其中我知道类型I将始终是Int(但被参数化,因为我需要它用于另一个类型类)。 现在我想让我的Power类型派生自Show(以特定的格式,所以我需要自己重写它)。我知道,I只会是Int,所以我尝试了: 实例显示(Power Int)其中 显示(Power1 0)=“” show(Power1 i)=“某些涉及i的格式设置\n” 显示(Power2
data Power i=Power1{charges::i}Power2{charges::i}
其中我知道类型I
将始终是Int
(但被参数化,因为我需要它用于另一个类型类)。现在我想让我的
Power
类型派生自Show
(以特定的格式,所以我需要自己重写它)。我知道,I
只会是Int
,所以我尝试了:
实例显示(Power Int)其中
显示(Power1 0)=“”
show(Power1 i)=“某些涉及i的格式设置\n”
显示(Power2 0)=“”
show(Power2 i)=“其他一些涉及i的格式设置\n”
但是,这不会编译,因为消息
• Illegal instance declaration for ‘Show (Power Int)’
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
• In the instance declaration for ‘Show (Power Int)’
|
22 | instance Show (Power Int) where
为什么这不可能
为什么这与编译器的不同
instance(Show i)=>Show(Power i)其中
您不能对类型使用类型约束,而只能对类型类使用类型约束。在您的示例中,可以为Integral
类型类实例化Show。然后为幂整数
和幂整数
定义show
instance Integral a => Show (Power a) where
show (Power1 0) = ""
show (Power1 i) = "some formatting involving i\n"
show (Power2 0) = ""
show (Power2 i) = "some other formatting involving i\n"
GHC说
所有实例类型的形式必须是(ta1…an),其中a1。。。变量是*不同类型的变量*
。这是在中定义的。要将具有具体类型的数据类型作为类参数,需要FlexibleInstances
扩展。因为存在覆盖实例问题
例如:
newtype Foo a=Foo a
a级酒吧在哪里
baz::a->a
实例栏(Foo Int),其中
baz=。。。
实例Show a=>Bar(Foo a)其中
baz=。。。
当您调用baz 1
时,编译器会混淆版本是否应该调用<代码>1是Int
但也属于Show
类!写在纸上的细节,你应该在有时间的时候读