1

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?

skiboy108
  • 53
  • 3

1 Answers1

2

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.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
  • 1
    I like to emphasise this in my own code by de-indenting the `deriving` clause (not all the way to zero, obviously). Make it visually appear to be "inside" the overall `data` declaration but "outside" the list of constructors. – Ben Dec 12 '22 at 03:15