I have a type defined like this:
newtype PrimeSet a = P Integer
deriving Eq
I have also defined a function which converts a prime set to a list, given that its type parameter is an Integral
.
toList :: Integral a => PrimeSet a -> [a]
I now what to give PrimeSet
a Foldable
instance, so this was my first attempt (after importing fold
from Data.Foldable
):
instance Foldable PrimeSet where
foldMap f = fold . map f . toList
This didn't work, however, and the compiler told me that it Could not deduce (Integral a) arising from a use of ‘toList’
. My understanding of this message is that toList
requires its argument to be an Integral a => PrimeSet a
type, but this isn't necessarily the case in the Foldable
instance.
The message also said that a possible fix would be to add Integral a
to the context of the type signature for my foldMap
implementation, but of course I was then told that I'm not allowed to provide my own type definitons for class methods unless I use InstanceSigs
, so I tried that but that didn't seem to work either.
So my question is this: is it possible to add a type constraint to a class instance if the type parameter of the type I'm writing the class instance for is hidden - or, to reiterate, can I do something like this?
instance (Integral a) => Foldable (PrimeSet a) where
(This of course doesn't work because PrimeSet a
has the kind *
whereas Foldable
requires * -> *
)