Skip to content

Instantly share code, notes, and snippets.

@tyru
Created September 10, 2010 17:10
Show Gist options
  • Select an option

  • Save tyru/574013 to your computer and use it in GitHub Desktop.

Select an option

Save tyru/574013 to your computer and use it in GitHub Desktop.
var alert = System.inform;
class RPNMachine {
var m_stack = [];
var m_ops = %[
"+" => %[
arity: 2,
fn: function (stack) {
stack.push(stack.pop() + stack.pop());
},
],
"-" => %[
arity: 2,
fn: function (stack) {
stack.push(stack.pop() - stack.pop());
},
],
"*" => %[
arity: 2,
fn: function (stack) {
stack.push(stack.pop() * stack.pop());
},
],
"/" => %[
arity: 2,
fn: function (stack) {
var r = stack.pop();
var l = stack.pop();
if (r == 0)
throw new Exception("divide by zero");
else
stack.push(l / r);
},
],
"." => %[
arity: 1,
fn: function (stack) {
alert(stack.pop());
},
],
];
function checkArity(arity) {
return m_stack.count >= arity;
}
function run(expr) {
var r_sp = /\s+/;
var r_number = /^\d+$/;
var terms = r_sp.split(expr);
for (var i = 0; i < terms.count; i++) {
var t = terms[i];
if (r_number.test(t)) {
m_stack.push(+t);
}
else if (m_ops[t]) {
if (!checkArity(m_ops[t].arity)) {
alert("[error] arity is less than arguments");
continue;
}
try {
m_ops[t].fn(m_stack);
}
catch (e) {
alert("[error] " + e.message);
}
}
}
}
}
var machine = new RPNMachine();
machine.run(System.inputString("RPNMachine", "Input RPN expression", "1 2 3 + + ."));
@tyru

tyru commented Sep 10, 2010

Copy link
Copy Markdown
Author

gist.vimで:wしてしまってつい途中で送信してしまう...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment