Question

My apologies if this question has already been asked. Show is a very common keyword that makes it hard for me to cut through noise. If I have a type defined for functor composition as shown below, I can't figure out how to define Show instance for that type:

newtype FComp f g a = C { unC :: f (g a) }

--- Incomplete Show definition for FComp
instance Show (FComp f g a) where
  show (C x) = "FComp" ++ show ??? --- Given a type say FComp Maybe Maybe Int, should print out "FComp Maybe Maybe Int"

Also:

$ :t show
show :: Show a => a -> String

So, it seems show takes a value, and returns the corresponding string. Plugging x in show ??? won't work since Show instance still needs to be defined for type f (g a).

Was it helpful?

Solution

Yep, and you would just add that as a constraint for your instance

instance (Show (f (g a))) => Show (FComp f g a) where
  show (C f) = "FComp " ++ show f

This just means we have a show instance for FComp exactly when we have one for f (g a)

You also will need to enable -XFlexibleContexts for this to work, but I wouldn't worry about this, it's just relaxing the restriction on what GHC allows for contexts and is pretty noncontroversial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top