From 08fb5daf0d2750a1a2230e030f00355d2b64435c Mon Sep 17 00:00:00 2001 From: fredrikr79 Date: Thu, 18 Sep 2025 06:18:54 +0200 Subject: [PATCH] interpretaux --- assignment2/main.oz | 53 +++++++++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/assignment2/main.oz b/assignment2/main.oz index 33ea6da..51af3f3 100644 --- a/assignment2/main.oz +++ b/assignment2/main.oz @@ -12,28 +12,49 @@ local [] "-" then operator(type:minus) [] "*" then operator(type:multiply) [] "/" then operator(type:divide) + [] "d" then unary(type:duplicate) + [] "i" then unary(type:negate) [] "p" then command(print) + [] "c" then command(clear) else number({String.toInt Head}) end )|{Tokenize Tail} else nil end end - fun {Interpret Tokens} - case Tokens - of number(A)|nil then A - [] number(A)|number(B)|Z|Tail then case Z - of number(C) then A|{Interpret number(B)|Z|Tail} - [] operator(type:plus) - then {Interpret number(A+B)|Tail} - [] operator(type:minus) - then {Interpret number(A-B)|Tail} - [] operator(type:multiply) - then {Interpret number(A*B)|Tail} - [] operator(type:divide) - then {Interpret number(A/B)|Tail} - end - else nil + 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 + local Result in case Op + of plus then Result = X + Y + [] minus then Result = X - Y + [] multiply then Result = X * Y + [] divide then Result = X div Y + else raise unexpectedOperator end end + {InterpretAux Tail Result|StackTail} + end + else raise stackUnderflow end end + [] unary(type:Op)|Tail then + case Stack of + X|StackTail then case Op + of duplicate then {InterpretAux Tail X|Stack} + [] negate then {InterpretAux Tail (~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 - {Show {Interpret {Tokenize {Lex "1 2 + 3 *"}}}} + + fun {Interpret Tokens} + {InterpretAux Tokens nil} + end + {Show {Interpret {Tokenize {Lex "4 d * i c"}}}} end \ No newline at end of file