Arithmetic evaluation: Difference between revisions

Updated D entry
(Updated D entry)
Line 799:
auto top = data.back;
static if (discard)
data.popBack();
return top;
}
Line 841:
 
void joinXP(XP x) pure {
x.RHS = num.pop();
x.LHS = num.pop();
num.push(x);
}
Line 857:
return token;
default: // Should be number.
if (token[0].isDigit()) {
while (xpTail < xpr.length && xpr[xpTail].isDigit())
xpTail++;
Line 877:
root = null;
opr.push(new XP); // CBkt, prevent evaluate null OP precedence.
while ((token = nextToken()) !is null) {
XP tokenXP = new XP(token, xpHead);
if (expectingOP) { // Process OP-alike XP.
switch (token) {
case ")":
while (opr.pop!false().type != Type.OBkt)
joinXP(opr.pop());
opr.pop();
expectingOP = true;
break;
case "+", "-", "*", "/":
while (tokenXP <= opr.pop!false())
joinXP(opr.pop());
opr.push(tokenXP);
Line 915:
 
while (opr.length > 1) // Join pending Op.
joinXP(opr.pop());
} catch(Exception e) {
writefln("%s\n%s\n%s^", e.msg, xpr, " ".replicate(xpHead));
Line 923:
 
if (num.length != 1) { // Should be one XP left.
writefln("Parse Error...").writefln;
root = null;
} else {
root = num.pop();
}
return this;
Line 939:
while (s[l].length < p + v.length + 1)
s[l] ~= " ";
s[l][p .. p + v.length] = v[];
}
 
Line 967:
}
foreach (const t; c.Tree)
writefln(t).writefln;
writefln("\n%s ==>\n%s = %s", a.xpr, c.resultStr, c.result);
} else
writefln("Evalute invalid or null Expression.").writefln;
}
 
Line 979:
if (xp.type == Type.Num) {
resultStr ~= xp.str;
result = to!int(xp.str).to!int;
} else {
resultStr ~= "(";
Line 1,002:
immutable exp0 = "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5" ~
" - 22/(7 + 2*(3 - 1)) - 1)) + 1";
immutable exp = (args.length > 1) ? args[1 .. $].join(" ") : exp0;
(new AST().parse(exp).CalcVis(); // Should be 60.
}</lang>
{{out}}