這樣的乙個直譯器幾乎沒用,不過只是為了學習一下直譯器的知識,有空繼續學習。
支援純變數的解釋,直譯器第乙個引數為純變數的字串,第二個引數為解釋上下文,也就是變數的值。支援四則運算,括號
function
context
(map)
context.prototype.getcontext = function
() var context;
function
abstractexpression
() abstractexpression.prototype.interpret = function
() function
terminalexpression
(val)
terminalexpression.prototype = new abstractexpression();
terminalexpression.prototype.interpret = function
(israw)
var result = context.getcontext()[this.val];
if (!result)
return result;
}function
nonterminalexpression
(left, right)
nonterminalexpression.prototype = new abstractexpression();
nonterminalexpression.prototype.interpret = function
() function
addexpression
(left, right)
addexpression.prototype = new nonterminalexpression();
addexpression.prototype.interpret = function
() function
subexpression
(left, right)
subexpression.prototype = new nonterminalexpression();
subexpression.prototype.interpret = function
() function
mulexpression
(left, right)
mulexpression.prototype = new nonterminalexpression();
mulexpression.prototype.interpret = function
() function
divexpression
(left, right)
divexpression.prototype = new nonterminalexpression();
divexpression.prototype.interpret = function
() function
bracketexpression
(val)
bracketexpression.prototype = new nonterminalexpression();
bracketexpression.prototype.interpret = function
() return root.interpret();
}function
interpreter
(expression, contextenv)
interpreter.prototype.run = function
() var result = this.interpret();
console.log(result);
}interpreter.prototype.interpret = function
() function
parser
() parser.prototype.parse = function
(expression) ;
while(iterator.hasnext())
switch(current)
if (current === '(')
if (current === ')') else
}tmp += current;
}if (root === null) else
break;
case
'+':
case
'-':
case
'*':
case
'/':
left = root;
if (left === null)
next = iterator.nexttoken(/[^\s]/);
if (next === false)
if (next === '(') else
if (/[0-9]/.test(next)) else else
}right = new terminalexpression(right);
}if ( (current === '*' || current === '/')
&& (left instanceof addexpression || left instanceof subexpression)
) root = new map[current](left, right);
break;
default:
root = new terminalexpression(current);
}i++;
}return root;
}function
iterator
(val)
iterator.prototype.next = function
() iterator.prototype.hasnext = function
() iterator.prototype.rollback = function
() iterator.prototype.nexttoken = function
(regexp)
}return
false;
}
new interpreter('( ((a +b) + (c * a + (a* cc- bx )))) ',).run();
實現四則運算
總結最近在看資料結構,遇到第乙個實際棧的應用,記錄 將平時的四則運算表示式又稱為中綴表示式轉化為字尾表示式。遇數字輸出,遇符號進棧,符號優先順序低於棧當前符號則輸出,輸出直到同等優先順序符號。例 9 3 1 2 輸出 棧 9 in 9 in 9 3 9 3 in 9 3 1 9 3 1 in 右括號...
四則運算的實現
繼續溫習資料結構.實現用到了兩個棧 運算元棧與操作符棧。主要過程是將中序表示式轉換為後續表示式,然後按順序進行運算。簡單過程 1 8 7 中序 1 8 7 後序 1 1 運算8 7 2 運算1 1 原始碼 include stack.h 利用到了前一篇文章實現的棧 define size 256 d...
java實現四則運算
最近在考慮乙個問題 公司專案可能會使用運算模板來計算相應的值,模板freemarker velocity都是不錯的選擇。那通過模板將計算公式字串組裝出來後,就需要解析字串得到計算結果,以下是我的實現 public class arithmetic public static void main st...