I'm working with this custom data type, and I would to be able to show it if the type of a
is showable.
data NonEmpty a = NonEmpty a (Array a)
So I created this type class instance with the dependency that a be showable...
instance showNonEmpty :: (Show a) => Show (NonEmpty a) where
show (NonEmpty c d) = c
But when I try and run this, the compiler says "Could not match type a0 with type String." I'm not sure why this wouldn't work, because if a
has an instance of Show
and the first argument to NonEmpty
(pattern matched to c
) is of type a
, then c
should be a string...
c
's kind is Show, meaning that is can be shown with the show
function. c
being of kind Show should not be confused with saying that c
is a string. It's not a string. In order for c
to become a string, you have to pass it into the show
function. So what you're looking for is...
instance showNonEmpty :: (Show a) => Show (NonEmpty a) where
show (NonEmpty c d) = show c
To further illustrate, here is an instance of Show that will show NonEmpty, and combine the values contained within it.
instance showNonEmpty :: (Monoid a, Show a) => Show (NonEmpty a) where
show (NonEmpty c d) = show $ append c (foldl (\e v -> append e v) mempty d)