简体   繁体   English

在Haskell中将实例定义为受限制的类型

[英]Defining an instance to a restricted a type in Haskell

I am working with the following Data Type: 我正在使用以下数据类型:

data Exp a =
|Const a
|Simetrico (Exp a)
|Mais (Exp a) (Exp a)
|Menos (Exp a) (Exp a)
|Mult (Exp a) (Exp a)

but a is supposed to be a Numeric type. 但是a应该是数字类型。 I would define Eq like this: 我会像这样定义Eq

instance Eq (Exp a) where
         a == b | ... = True
                | otherwise = False

but I am saying nowhere that my a is a numeric type, so ghci complains, how do I solve this ? 但我说无处不在,我的a是数字类型,所以ghci抱怨,我该如何解决这个问题?

You add a type constraint to the instance clause: 您向instance子句添加类型约束:

instance Num a => Eq (Exp a) where
         a == b | ... = True
                | otherwise = False

So now you can assume (in the scope of the instance ) that a is an instance of the Num typeclass. 所以现在你可以假设(在instance的范围内) aNum类型类的一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM