I’ve written part of a mathematical calculator program. I’ve finished the parser of the program, so when a user types in a mathematical expression as a string, I already have a way to obtain a corresponding data structure of the following type:
type expression =
| Term of int
| Addition of expression * expression
| Multiplication of expression * expression
| Subtraction of expression * expression
All I need now is a way to evaluate these kinds of data structures.
- (a) Write the expression corresponding to the mathematical statement “3*((1 + 4)- 5).”
- (b) Extend the Ocaml datatype to include a Factorial constructor, so that it can handle expressions like “3*((1 + 4)! -5).”
- (c) Write an Ocaml function eval which takes a mathematical expression and returns its (integer) value. For example, it should return 0 as the result from the expression in part (a).
# let rec eval expr = ... val eval : expression -> int = <fun>
You may want to write a factorial Ocaml function to help out with the new Factorial constructor.
I'm confused about part a. Does it mean let expression = 3*((1 + 4)- 5);
?
For part b, should I follow the pattern |Factorial of expression * expression
?