我正在通过UPENN Haskell讲义学习Haskell类型类,用示例代码创建自己的类型类:
我该如何修复这个问题?
class Listable a where
toList :: a -> [Int]
instance Listable Int where
toList x = [x]
instance Listable Bool where
toList True = [1]
toList False = [0]
它适用于Int
和Bool
,但是当我添加一个[Int]
的实例时,ghci
会出现错误:
instance Listable [Int] where
toList = id
错误:
‘Listable [Int]’的非法实例声明
(所有实例类型必须为(T a1 ... an)的形式,
其中a1 ... an是不同的类型变量,
每个类型变量在实例头中最多出现一次。
如果要禁用此功能,请使用FlexibleInstances。)
在‘Listable [Int]’的实例声明中
我尝试了几次但都失败了:
toList x = id x
toList x = x
toList = \x -> x
我该如何修复这个问题?
Use FlexibleInstances if you want to disable this
吗?纯 Haskell 在类型类方面相当严格;现代大多数程序都使用了多个扩展,因此编译器通常会建议你需要打开哪个扩展。 - chighci
希望我用FlexibleInstances
替换关键字instance
,但事实证明这是错误的。 - Rahninstance Foldable t => Listable (t Int) where toList = Data.Foldable.toList
- user2297560