2017-01-27 87 views
1

我正在做一个Boolean数据的类型类实例,接受其他类型的布尔值,只是为了好玩。我创建了数据Boolean,用于表示实际的Boolean值,并且我创建了一个名为Booleanizable的类,该类表示可以转换为布尔值数据的值。问题如下:我想为属于Num类的每个类型声明一个instance声明,而不是为每个类型声明一个声明。我怎么做? 只是为了使其更清晰,代码:如何使另一种类型的类

module Boolean(
    Boolean, 
    true, 
    false, 
    Booleanizable 
) where 



data Boolean = Boolean Int 

false = Boolean 0 
true = Boolean 1 

instance Show Boolean where 
    show (Boolean 0) = "false" 
    show (Boolean 1) = "true" 

instance Eq Boolean where 
    (Boolean 0) == (Boolean 0) = True 
    (Boolean 0) == (Boolean 1) = False 
    (Boolean 1) == (Boolean 1) = True 
    (Boolean 1) == (Boolean 0) = False 



class Booleanizable a where 
    toBoolean :: (Booleanizable a) => a -> Boolean 

instance Booleanizable Boolean where 
    toBoolean (Boolean x) = Boolean x 

instance Booleanizable Bool where 
    toBoolean True = Boolean 1 
    toBoolean False = Boolean 0 

而且我想要做的事:

instance (Num a) => Booleanizable a where 
    toBoolean 0 = Boolean 0 
    toBoolean _ = Boolean 1 

这是出现错误:

Boolean.hs:37:21: 
    Illegal instance declaration for ‘Booleanizable a’ 
     (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 ‘Booleanizable a’ 
+2

请在问题中显示您的尝试出了什么问题。 (在这种情况下,我能够正确地猜出你得到了错误,但在其他问题,它可能是棘手做到这一点。) – duplode

+0

如果问题仅仅是错误'的限制是不超过实例head'较小,这里是一个很好的解释和解决方案(使用NEWTYPE) - http://stackoverflow.com/a/7198951/348716 –

+0

更新的问题。这不是那个错误。对不起,这么久了@duplode –

回答

1

我做了三让你的例子工作的东西:

1.)开始时,我添加了两个语言扩展:

{-# LANGUAGE FlexibleInstances #-} 
{-# LANGUAGE UndecidableInstances #-} 

2.)我去除在类Booleanizable的定义中的自参照Booleanizable a

代替

class Booleanizable a where 
    toBoolean :: (Booleanizable a) => a -> Boolean 

使用

class Booleanizable a where 
    toBoolean :: a -> Boolean 

3.)我在最后一个实例定义中添加了附加约束Eq a

instance (Num a, Eq a) => Booleanizable a where 
    toBoolean 0 = Boolean 0 
    toBoolean _ = Boolean 1 
相关问题