BEGIN { stack[0] = 0 stack_p = 0 print rpn_calc("3 19 + -2 /") print rpn_calc("3 19 + -2 / +") print rpn_calc("1 2 + 3 4 5 sum") print rpn_calc("5 4 - exp") print rpn_calc("1 2.0 +") print rpn_calc("12 5 /") print rpn_calc("2 3 4 prod") } function rpn_calc(str, i, n, q, ql, t) { ql = split(str, q) if (! is_integer(q[1])) return 0 n = q[1] init() for(i = 2; i <= ql; i++) { t = q[i] if (is_integer(t)) { push(n) n = t } else if (t == "+") { if (empty()) return 0 n += pop() } else if (t == "-") { if (empty()) return 0 n = pop() - n } else if (t == "*") { if (empty()) return 0 n *= pop() } else if (t == "/") { if (empty()) return 0 n = int(pop() / n) } else if (t == "exp") { n = exp(n) } else if (t == "sum") { while(! empty()) { n += pop() } } else if (t == "prod") { while(! empty()) { n *= pop() } } else { return "error" } } return n } function is_integer(s) { return match(s, /^-?(0|[1-9][0-9]*)$/) } function init( n) { stack_p = 0 } function push(n) { stack[stack_p++] = n } function empty( n) { return (stack_p < 1); } function pop( n) { return (empty() ? 0 : stack[--stack_p]) }