refactor interpretaux to not pollute global scope
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user