最简单的解释器应该就是逆波兰表达式了,连括号都不需要处理,用出栈,入栈就可以写完解释器。这个例子对于那些总是被栈(Stack)搞糊涂的同学做思维练习很合适。用c#写了个实现。
void Main()
{
var exps = new string[]{
"3 4 +",
"3 4 5 * -",
"3 4 - 5 *",
"5 1 2 + 4 * + 3 -"
};
foreach(var exp in exps){
exp.Dump("calculate expression:");
calculate(exp).Dump("result:");
}
}
【逆波兰表达式】// Define other methods and classes here
double calculate(string exp){
var chars = exp.Split(' ');
var i=0;
var statck = new Stack();
while(i var v = chars[i++];
if(v=="+"||v=="-"||v==""||v=="/"){
if(statck.Count<2){
throw new Exception("syntax error!");
}
var right =Convert.ToDouble(statck.Pop());
var left = Convert.ToDouble(statck.Pop());
Console.Write(" {0} ",v);
switch(v){
case "+":{
var r = left+right;
statck.Push(r.ToString());
break;
}
case "-":{
var r = left-right;
statck.Push(r.ToString());
break;
}
case "":{
var r = left*right;
statck.Push(r.ToString());
break;
}
case "/":{
var r = left/right;
statck.Push(r.ToString());
break;
}
default:
throw new Exception("syntax error:unsupported operation!");
}
Console.WriteLine();
foreach(var j in statck.ToArray().Reverse()){
Console.Write(" {0} ",j);
}
}else{
statck.Push(v.ToString());
if(i>1)
Console.WriteLine();
foreach(var j in statck.ToArray().Reverse()){
Console.Write(" {0} ",j);
}
}
}
if(statck.Count!=1)
throw new Exception("syntax error:invalid expression!");
return Convert.ToDouble(statck.Pop());
}