Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the Show class

Tags:

haskell

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

like image 930
MathematicalOrchid Avatar asked Jan 31 '12 15:01

MathematicalOrchid


1 Answers

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])"
like image 88
hammar Avatar answered Oct 04 '22 01:10

hammar