[Haskell-cafe] Show me

Jonathan Cast jonathanccast at fastmail.fm
Tue Aug 5 23:41:45 EDT 2008


On Tue, 2008-08-05 at 20:28 +0100, Andrew Coppin wrote:
> Suppose we have the following:
> 
>   data Foo x
>   list_foo :: [x] -> Foo x
>   foo_list :: Foo x -> [x]
> 
> What would be the best way to write a Show instance?
> 
> The thing that I came up with is
> 
>   instance (Show x) => Show (Foo x) where
>     show foo = "list_foo " ++ show (foo_list foo)
> 
> But apparently you're supposed to use the strange "showsPrec" method 
> that I don't understand. So can somebody show me a correct instance 
> definition for this type please?

instance Show x => Show (Foo x) where
  showsPrec n foo = ("list_foo "++) . shows (foo_list foo)

You use the n parameter if you've got an infix operator in your syntax
and you want to put parentheses around an instance of it if n has the
wrong value (either too high or too low, I can never remember).

jcc




More information about the Haskell-Cafe mailing list