[Haskell] Overloading show

Marius Nita marius at cs.pdx.edu
Fri Sep 10 18:51:27 EDT 2004


On Sep 10, 2004, at 3:37 PM, Stephan Zaubzer wrote:
> Hello Everyone!
>
> I am relatively new to Haskell (actually it's my second day) and I 
> have the following problem:
> If I define a new datatype, for example a Binary tree, how can i use 
> the show function to put an instance of my datatype into a String 
> representation. I have seen in different Tutorials that there is a way 
> for overloading the show function for my own type, and I tried out, 
> what was presented in the tutorials, but it didn't work. Does somebody 
> know, how to manage this?
>
> Here my attempts:
>
> data Entry a  = EmptyEntry | MakeEntry a a

You could make use of the default show by simply deriving Show:

   data Entry a = EmptyEntry | MakeEntry a a
     deriving Show

Otherwise you need to provide an instance of Show for your type, as 
such:

   instance Show a => Show (Entry a) where
     show EmptyEntry = "Empty"
     show (MakeEntry x y) = show x ++ ": " ++ show y

(untested code)

-marius



More information about the Haskell mailing list