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