From 131112372f7724cb5e5a29c13de8023bef58909d Mon Sep 17 00:00:00 2001 From: fredrikr79 Date: Thu, 18 Sep 2025 06:36:27 +0200 Subject: [PATCH] refactor interpretaux to not pollute global scope --- assignment2/main.oz | 65 +++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 32 deletions(-) diff --git a/assignment2/main.oz b/assignment2/main.oz index 2543539..a5697e4 100644 --- a/assignment2/main.oz +++ b/assignment2/main.oz @@ -5,6 +5,7 @@ local {String.tokens Input & } end + fun {Tokenize Lexemes} case Lexemes of Head|Tail then (case Head @@ -21,39 +22,39 @@ local else nil end end - fun {InterpretAux Tokens Stack} - case Tokens of - nil then Stack - [] number(N)|Tail then - {InterpretAux Tail N|Stack} - [] operator(type:Op)|Tail then - case Stack of Y|X|StackTail then - {InterpretAux Tail (case Op - of plus then X + Y - [] minus then X - Y - [] multiply then X * Y - [] divide then X div Y - else raise unexpectedOperator end end - )|StackTail} - else raise stackUnderflow end end - [] unary(type:Op)|Tail then - case Stack of X|StackTail then - {InterpretAux Tail (case Op - of duplicate then X|Stack - [] negate then (~X)|StackTail - else raise unexpectedOperator end end - )} - else raise stackUnderflow end end - [] command(print)|Tail then - {Show Stack} - {InterpretAux Tail Stack} - [] command(clear)|Tail then - {InterpretAux Tail nil} - end - end fun {Interpret Tokens} - {InterpretAux Tokens nil} + fun {Aux Tokens Stack} % create auxiliary function to surrogate the stack + case Tokens of + nil then Stack + [] 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 + {Aux Tail (case Op + of plus then X + Y + [] minus then X - Y + [] multiply then X * Y + [] divide then X div Y + else raise unexpectedOperator end end + )|StackTail} + else raise stackUnderflow end end + [] unary(type:Op)|Tail then % arity 1 + case Stack of X|StackTail then + {Aux Tail (case Op + of duplicate then X|Stack + [] negate then (~X)|StackTail + else raise unexpectedOperator end end + )} + else raise stackUnderflow end end + % handle commands separately, as they deal with the stack in unique ways + [] command(print)|Tail then + {Show Stack} + {Aux Tail Stack} + [] command(clear)|Tail then + {Aux Tail nil} + end + end + in {Aux Tokens nil} % this is where Interpret starts end - {Show {Interpret {Tokenize {Lex "4 2 /"}}}} end \ No newline at end of file