如何创建另一个类型类

时间:2017-01-27 15:17:23

标签: haskell typeclass

我正在制作一个Boolean数据,它接受其他类型作为布尔值,只是为了好玩。我创建了数据Boolean,用于表示实际的Boolean值,我创建了一个名为Booleanizable的类,它表示可以转换为布尔数据的值。问题如下:我想为属于instance类的每个类型创建一个Num语句,而不是为每个类型创建一个语句。我怎么做? 为了更清楚,代码:

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’

1 个答案:

答案 0 :(得分: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