Show class implementation

Suppose we have:

  data foo x
 from_list :: [x] -> Foo x
 to_list :: Foo x -> [x]

Suppose I want to declare instance (Show x) => Show (Foo x) so that showing the value, you call the corresponding from_list call. How exactly am I doing this? In particular, how to implement showsPrec so that the triddy fiddly priorence rules are followed? (That is, put the expression in parentheses if and only if necessary.)

+7
source share
1 answer

What you want here is basically the same as what Data.Set does , so we can change this a bit:

 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 it, and use showParen to add brackets around it if the surrounding context has higher priority than the function application (which has priority 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])" 
+18
source

All Articles