I'm learning Haskell type classes through UPENN Haskell lecture notes, making my own type class with example code:
class Listable a where
toList :: a -> [Int]
instance Listable Int where
toList x = [x]
instance Listable Bool where
toList True = [1]
toList False = [0]
It works with Int
and Bool
but ghci
fails when I add an instance of [Int]
:
instance Listable [Int] where
toList = id
Errors:
Illegal instance declaration for ‘Listable [Int]’
(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 ‘Listable [Int]’
I try several time but all fail:
toList x = id x
toList x = x
toList = \x -> x
How could I fix it?
Use FlexibleInstances if you want to disable this
? Plain Haskell is fairly restrictive, especially in type classes; most modern programs make use of several extensions, so now the compiler often suggests which extension you need to turn on. – chighci
want me to replace keywordinstance
withFlexibleInstances
, which proved to be dummy. – Rahninstance Foldable t => Listable (t Int) where toList = Data.Foldable.toList
– user2297560