Haskell Expression Evaluation Tree

In the 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 appreciate this, you simply use a function such as:

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

However, today we were assigned a data type:

 data Op = Add | Sub | Mul 

So, I decided to create an expression tree that I could just do:

 data Expr = Value Integer | Op Expr Expr 

And use the same eval function. However, since then I wrote this function and loaded it into GHCI, but it does not seem to work. Can someone explain why this is not working?

+7
source share
1 answer

You must define a data constructor (with a name)

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

then

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

etc.

:)

+13
source

All Articles