我正在制作一个 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/