Expression evaluation tree in Haskell
Asked Answered
H

1

8

In an exam today I was asked to create an expression evaluation tree in Haskell. Usually the answer is as simple as:

data Expr = Value Integer
          | Add Expr Expr
          | Sub Expr Expr
          | Mul Expr Expr

And to evaluate it, you just use a function such as:

eval :: Expr -> Integer
eval (Value x) = x
eval (Add l r) = eval l + eval r
eval (Sub l r) = eval l - eval r
eval (Mul l r) = eval l * eval r

However today, we were given a data type:

data Op = Add
        | Sub
        | Mul

So I assumed to create the expression tree I could just do:

data Expr = Value Integer
          | Op Expr Expr

And use the same eval function. However, I have since written that function and loaded it into GHCI, but it does not seem to work. Could anyone explain why this doesn't work?

Hyperbola answered 20/5, 2013 at 11:10 Comment(0)
E
14

You must define a data constructor (providing a name)

data Expr = Value Integer | Compute Op Expr Expr
                            ^^^^^^^

then

eval :: Expr -> Integer
eval (Value x) = x
eval (Compute Add l r) = eval l  + eval r

and so on.

:)

Esbensen answered 20/5, 2013 at 11:41 Comment(2)
Ahhhhhh ok, thank you very much. Glaringly obvious now, but having multiple constructors already got me a bit confused.Hyperbola
Your teacher is good forcing you to think (not only remember) :DEsbensen

© 2022 - 2024 — McMap. All rights reserved.