Last active
March 25, 2017 17:05
-
-
Save mikesmullin/a6918611ed7abbab8f09d5a5001b4a00 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator (in CoffeeScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reverse Polish Notation Calculator (in CoffeeScript) | |
# authored by Mike Smullin <[email protected]> | |
# | |
# see also: | |
# https://en.wikipedia.org/wiki/Polish_notation | |
# http://www.calculator.org/rpn.aspx | |
# http://blog.reverberate.org/2013/07/ll-and-lr-parsing-demystified.html | |
# http://stackoverflow.com/questions/5975741/what-is-the-difference-between-ll-and-lr-parsing | |
# https://www.amazon.com/Definitive-ANTLR-4-Reference/dp/1934356999 | |
stack = [] | |
allClear = -> stack.splice 0 # AC | |
add = (addend, augend) -> augend + addend # = sum | |
subtract = (subtrahend, minuend) -> minuend - subtrahend # = difference | |
multiply = (multiplier, multiplicator) -> multiplicator * multiplier # = product | |
divide = (divisor, dividend) -> dividend / divisor # = quotient | |
operation = (binaryOperator) -> stack.push binaryOperator stack.pop(), stack.pop() | |
calc = (equation) -> | |
for operand in equation.split " " | |
switch operand | |
when "+" then operation add | |
when "-" then operation subtract | |
when "×", "*" then operation multiply | |
when "÷", "/" then operation divide | |
else stack.push parseFloat operand | |
return stack.pop() | |
console.log calc "3 15 7 1 1 + - ÷ × 1 1 + 2 + -" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment