[Haskell-beginners] showing user defined data types
Sean Bartell
haskell at yotann.org
Fri Apr 5 22:31:44 CEST 2013
Hello,
Dan Lior on 2013-04-05:
> data Pixel = Black | White deriving (Eq, Show)
>
> and would like to "show" it as
>
> show :: Pixel -> String
> show Black = "#"
> show White = "."
>
> Apparently, ghc finds this ambiguous. That seems strange to me since Pixel is my own custom type and I don't imagine that ghc has another definition for showing it. Isn't this what "overloading" is supposed to enable?
The normal show function is part of the Show typeclass, which is what
allows you to have different definitions of it for different types.
You're defining a new, separate "show" that only works on Pixels, and
when you try to call it later GHC doesn't know which "show" you mean.
Instead, you want to extend the normal "show" to work with Pixel by
making Pixel an instance of Show, like this:
instance Show Pixel where
show Black = "#"
show White = "."
You also need to remove "Show" from the "deriving" clause--it's causing
GHC to automatically make Pixel a Show instance by returning "Black" or
"White", and you want "#" or "." instead.
Sean Bartell
More information about the Beginners
mailing list