The If
data constructor (If BoolType Expr Expr
) should evaluate the Boolean expression (first argument) and return the value of the second argument if it is true or return the third argument. I can construct an evaluation of the expression Expr
but I don't understand how to incorporate the nested expression BoolType
in order to evaluate an expression. A bit too twisty, I can't get my head around it.
Here's two data types:
data Expr = Val Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
| If BoolType Expr Expr
data BoolType = Lit Bool
| Or BoolType BoolType
| EqualTo Expr Expr
| LessThan Expr Expr
I wrote an expression that evaluates the type:
eval :: BoolType -> Bool
eval (Lit n) = n
eval (Or e1 e2) = eval e1 || eval e2
eval (EqualTo e1 e2) = num e1 == num e2
eval (LessThan e1 e2) = num e1 < num e2
num :: Expr -> Int
num (Val n) = n
num (Add e1 e2) = num e1 + num e2
num (Sub e1 e2) = num e1 - num e2
num (Mul e1 e2) = num e1 * num e2
num (Div e1 e2) = num e1 `div` num e2
It should evaluate out to any normal equation but how do I even incorporate an If
boolean data type into the total equation?
value
that handles theIf
case. Did you encounter any specific problems with that? Also, why did you duplicate the code betweennum
andvalue
? – Fyodor SoikinIf
statement? My confusion is on the actual syntax. I'm unsure how to include anIf
. – user11340751If
case as well should be almost trivial. – Robin ZigmondIf
which I thought had to be handled differently but I was way overthinking it. – user11340751