[Haskell-cafe] Data types and field labels and "Show"

bbrown bbrown at botspiritcompany.com
Thu Sep 27 14:43:05 EDT 2007


On Thu, 27 Sep 2007 11:41:00 -0700, Don Stewart wrote
> bbrown:
> > I am trying to print the data from a data type and also get the field 
> > values.  How would I reference those values if I am declaring a Show 
function.
> > 
> > I should probably use a class for this, but so far it is working.
> > 
> > I have something along the lines of this.
> > 
> > data SimplePlayer = SimplePlayer { 
> >       shape :: MechShape,
> >       angle :: GLfloat,
> >       posX :: GLfloat,
> >       posY :: GLfloat
> >     }
> > 
> > and then to use "Show", I was declaring this.
> > 
> > instance Show SimplePlayer where
> > 	show a = "<Simple> posX [" ++ show a{posX} ++ "]"
> > 
> > Of course, this didn't compile.
> > 
> > How should I change this code to get the field label values of the type.
> > 
> > Tests/GLTests.hs:20:42: parse error on input `}'
> 
> Just derive Show. Types with records will be printed with their labels.
> You can then also derive Read, and get serialisation for free.
> 
>     data SimplePlayer = SimplePlayer
>             { shape :: MechShape
>             , angle :: GLfloat
>             , posX  :: GLfloat
>             , posY  :: GLfloat }
> 
>        deriving (Read,Show)
> 
>     *M> show $ SimplePlayer "square" pi 1.0 (exp 1)
> 
>     "SimplePlayer {shape = \"square\"
>                   , angle = 3.1415927
>                   , posX = 1.0
>                   , posY = 2.7182817}"

I did this too:

instance Show SimplePlayer where
	show simpleEntity = "<Simple> posX [" ++ show (posX simpleEntity) ++ 
						"] posY [" ++ show (posY 
simpleEntity) ++ "]"


--
Berlin Brown
[berlin dot brown at gmail dot com]
http://botspiritcompany.com/botlist/?



More information about the Haskell-Cafe mailing list