Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression evaluation tree in Haskell

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?

like image 734
Matt Williams Avatar asked May 20 '13 11:05

Matt Williams


1 Answers

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.

:)

like image 75
josejuan Avatar answered Nov 11 '22 20:11

josejuan