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

Don Stewart dons at galois.com
Thu Sep 27 14:41:00 EDT 2007


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}"


More information about the Haskell-Cafe mailing list