interpretaux
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user