Skip to content

Instantly share code, notes, and snippets.

@dgendill
Last active April 17, 2016 17:16
Show Gist options
  • Save dgendill/410624f16571aac177f651bf7986b1e1 to your computer and use it in GitHub Desktop.
Save dgendill/410624f16571aac177f651bf7986b1e1 to your computer and use it in GitHub Desktop.
Why does this Show instance throw "Count not match a0 with type String" (Purescript)

Why does this Show instance throw "Count not match a0 with type String" (Purescript)

Question

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...


Answer

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment