haskell - 如何创建另一个类型类的类型类实例

标签 haskell typeclass

我正在制作一个 Boolean 数据,它接受其他类型作为 bool 值,只是为了好玩。我创建了数据 Boolean,用于表示实际的 Boolean 值,并且创建了一个名为 Booleanized 的类,它表示可以转换为 bool 数据。问题如下:我想为属于 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’

最佳答案

我做了三件事来使你的示例正常工作:

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

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

2.) 我在 Booleanized 类的定义中删除了对 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

关于haskell - 如何创建另一个类型类的类型类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41897248/

相关文章:

haskell - 从 Haskell 中的两个列表复制文件

haskell - 为列表创建新的 Ord 实例

haskell - 类型类和重载,有什么联系?

haskell - 由于使用 `Control.Exception.catch' 而产生

haskell - 当前关于记录全局命名空间的最佳实践

haskell - 将 unsafeCoerce 用于有效等式总是安全的吗?

haskell - 任何人都可以为 Haskell 推荐一个好的约束库吗?

scala - 关于类型类的问题

haskell - Haskell 如何为类型类的实例选择方法?

haskell : Illegal type synonym family application in instance