This snippet parses lisp style prefix notation:
this["+"] = function(a:Number, b:Number):Number{ return a + b; }
this["-"] = function(a:Number, b:Number):Number{ return a - b; }
this["*"] = function(a:Number, b:Number):Number{ return a * b; }
this["/"] = function(a:Number, b:Number):Number{ return a / b; }
trace(parsePrefix("(* 10 10)"));
trace(parsePrefix("(* 1 (+ 20 2 (* 2 7) 1) 2)"));
trace(parsePrefix("(/ 22 7)"));
trace(parsePrefix("(+ (/ 1 1) (/ 1 2) (/ 1 3) (/ 1 4))"));
function parsePrefix(expression:String):Number{
var ops:Array = [];
var argIndex:int = -1;
var args:Array = [];
var chars:String = "";
var output:Number;
var leng:int = expression.length;
for (var i:int = 0; i < leng; i++){
var curr:String = expression.charAt(i);
if (curr == "("){
i++;
ops.push(expression.charAt(i));
argIndex++;
args[argIndex] = []
}else if (curr == ")" || curr == " "){
if (chars.length > 0){
args[argIndex].push(Number(chars));
chars = ""
}
if (curr == ")" ){
if (argIndex > 0){
var op:String = ops.pop();
var arg:Array = args.pop();
argIndex--;
args[argIndex].push(math(op, arg));
}else{
output = math(ops[0],args[0]);
break;
}
}
}else{
chars += curr;
}
}
return output;
}
function math(op:String, args:Array):Number{
var leng:int = args.length;
var reslt:Number = args[0];
for (var i:int = 1; i < leng; i++){
reslt = this[op](reslt, args[i]);
}
return reslt;
}