I'm currently trying to write an OCaml function that will evaluate expressions and return a Boolean value. I've tried to do research online, and the closest answer that I could find is this one. However, I'm still having trouble which led me to ask my own question.
Here's the basic code:
type equation =
| True
| False
| Equal of exp * exp
and exp =
| Val of int
| Add of exp * exp
| Sub of exp * exp
let rec eval : equation -> bool
= fun f ->
match f with
| True -> true
| False -> false
| Equal (x, y) -> match (x, y) with
| (Val a, Val b) -> if (x = y) then true else false
| ((Add (Val a, Val b), c) -> eval (Equal (Val (a + b), c))
The program is incomplete, and the recursive call to eval
in the last line is where I got stuck. A specific input example that I've thought of is:
eval (Equal (Add (Add (Val 1, Val 2), Val 3), Val 6))
This should evaluate to true
, since the two Add
's add up to 6, and Equal
compares Val 6
with Val 6
. The trouble that I'm experiencing is how to recursively call the function to evaluate the second Add
inside the expression, so that Add (Val 2, Val 2)
first evaluates to Val 3
, then the first Add
adds Val 3
with Val 3
. The program that I've written right now only evaluates one of the two Add
's.
Is there anything that I should be thinking of or keeping in mind? Any feedback is welcome. Thank you.
Equal (x, y) -> eval_exp(x) == eval_exp(y)
? Doing both in one is uncomfortable, as you're finding... – Amadaneval
. – Amadan