Suppose we have the following:
data Foo x from_list :: [x] -> Foo x to_list :: Foo x -> [x]
Suppose I want to declare instance (Show x) => Show (Foo x)
such that showing a value produces the appropriate call to from_list
. How exactly do I do that? In particular, how do I implement showsPrec
so that the trixy fiddly precedence rules are satisfied? (That is, put the expression in brackets if and only if it's necessary.)
What you want here is basically the same as what Data.Set
does, so we can just modify that a little:
instance Show x => Show (Foo x) where
showsPrec p xs = showParen (p > 10) $
showString "from_list " . shows (to_list xs)
In other words, we use the Show
instance for lists, prepend "from_list "
to that, and use showParen
to add brackets around it if the surrounding context has higher precedence than function application (which has precedence 10).
> show (from_list [1, 2, 3])
"from_list [1,2,3]"
> show (Just $ from_list [1, 2, 3])
"Just (from_list [1,2,3])"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With