These exercises make use of a recursively defined type that models mathematical expressions:
datatype operation = Plus | Minus | Mul | Div; datatype expression = Internal of operation * expression * expression | Leaf of int;
For example, the expression ((3 + 7) * 8)
would be Internal(Mul, Internal(Plus, Leaf(3), Leaf(7)), Leaf(8))
.
Exercise 6.2.14 asks you to turn a value in the expression
datatype into a string showing how the expression would normally appear
in mathematical notation.
For example,
printExpression(Internal(Mul, Internal(Plus, Leaf(3), Leaf(7)), Leaf(8)));
should result in
((3 + 7) * 8)
We haven't done much with strings this semester, but it doesn't require very much. All you need to know is
int
into a string by using
Int.toString()
.
Compare the printTree()
function we did in class.
operation
datatype into strings:
fun printOper(Plus) = "+" | printOper(Minus) = "-" | printOper(Mul) = "*" | printOper(Div) = "/";
^
, which
works just like @
does on lists.
Also, Exercise 6.2.14 has a misprint. It isn't Section 2.5 that has information about strings but rather Section 1.7.
For Exercise 6.2.15, write a function that evaluates the expression. For example,
execute(Internal(Mul, Internal(Plus, Leaf(3), Leaf(7)), Leaf(8)));
should result in
80
I'll go one step further and give you a stub for this:
fun execute(Leaf(x)) = ?? | execute(Internal(Plus, left, right)) = ?? | execute(Internal(Minus, left, right)) = ?? | execute(Internal(Mul, left, right)) = ?? | execute(Internal(Div, left, right)) = ??