I must come up with a function that evaluates an abstract syntax tree and returns the result of its evaluation.
evaluate will have type Exp -> int option
evaluate (Prod(Num 5, Diff(Num 6, Num 1)));;
val it : int option = Some 25
@John Palmer
How do i go about doing this? Can I use pattern matching? if so how would I do it in order to identify the operation that needs to be done.
Here is what i have come up with? I still dont understand the code per say.
let rec evaluate = function
| Num n -> Some n
| Neg e -> match evaluate e with
|Sum (a,b) -> evaluate(a) + evaluate(b)
|Diff(a,b) -> evaluate(a) - evaluate(b)
| Prod (a,b) -> evaluate(a) * evaluate (b)
|Quot (a,b) -> evaluate(a) / evaluate(b)
Here are some hints to get started
EDIT
So I assume your data type looks like
so you set up your AST (presumably you are parsing this from somewhere – which is a whole other question) with something like
then you can define evaluate as
then call it and print the result with
Note that
evaluatehas to have typeAST -> intas otherwise you will need to handle option cases – for example what is2 * Noneor2 + NoneI am not sure what you mean by
but hopefully this explains everything