From a5026d325484c53fca75a561da5fcd39cbc84239 Mon Sep 17 00:00:00 2001 From: fredrikr79 Date: Thu, 18 Sep 2025 06:54:06 +0200 Subject: [PATCH] expressiontree --- assignment2/main.oz | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/assignment2/main.oz b/assignment2/main.oz index a5697e4..e2279c8 100644 --- a/assignment2/main.oz +++ b/assignment2/main.oz @@ -30,7 +30,7 @@ local [] number(N)|Tail then {Aux Tail N|Stack} [] operator(type:Op)|Tail then % operators are binary (arity 2) - case Stack of Y|X|StackTail then + case Stack of X|Y|StackTail then {Aux Tail (case Op of plus then X + Y [] minus then X - Y @@ -57,4 +57,29 @@ local end in {Aux Tokens nil} % this is where Interpret starts end + + + % this is just a stripped down Interpret. it resembles the shunting-yard algorithm + fun {ExpressionTree Tokens} + fun {ExpressionTreeInternal Tokens ExpressionStack} + case Tokens of + nil then ExpressionStack + [] number(N)|Tail then + {ExpressionTreeInternal Tail N|ExpressionStack} + [] operator(type:Op)|Tail then + case ExpressionStack of X|Y|ExpressionStackTail then + {ExpressionTreeInternal Tail (case Op + % return the tree records rather than the arithmetic result of the operators + of plus then plus(X Y) + [] minus then minus(X Y) + [] multiply then multiply(X Y) + [] divide then divide(X Y) + else raise unexpectedOperator end end + )|ExpressionStackTail} + else raise stackUnderflow end end + else raise unexpectedToken end end + end + in {ExpressionTreeInternal Tokens nil} % this is where ExpressionTree starts + end + {Show {Interpret {Tokenize {Lex "3 10 9 * - 7 +"}}}} end \ No newline at end of file