skiboy108
skiboy108

Reputation: 59

Trying to add deriving(Show, Read) to an expression tree

I am fairly new to Haskell so it is probably something simple that I am missing but I have an expression tree that looks like this:

data Expression = Lit Float
                    | Add Expression Expression
                    | Mul Expression Expression
                    | Sub Expression Expression
                    | Div Expression Expression

And that code works perfectly fine but then when I try to add a deriving(Show, Read) so that Haskell automatically writes code to read and write elements of this type it throws an error. This is what I am trying to do. Lit Float deriving(Show, Read)

I get an error that reads error: parse error on input '|', and now the Add Expression Expression line doesn't work. Could someone point out to me what the error is here?

Upvotes: 1

Views: 116

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

the deriving clause has to go after the complete type definition:

data Expression = Lit Float
                    | Add Expression Expression
                    | Mul Expression Expression
                    | Sub Expression Expression
                    | Div Expression Expression
                    deriving (Read, Show)

in what you were trying, presumably

data Expression = Lit Float deriving (Read, Show)
                    | Add Expression Expression
                    | Mul Expression Expression
                    | Sub Expression Expression
                    | Div Expression Expression

Haskell comes to the deriving clause and assumes the type definition has finished and something else is coming after. And then the | character makes no sense.

You derive instances - or indeed write your own instances - for a type, not for individual constructors for that type.

Upvotes: 2

Related Questions