Created
August 14, 2013 17:48
-
-
Save mattknox/6233577 to your computer and use it in GitHub Desktop.
two different versions of an RPN calculator
This file contains hidden or 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
OPERATORS = %w{ + - * / } | |
def tokenize(s) | |
s.split.map do |x| | |
if OPERATORS.member? x | |
x.to_sym | |
else | |
x.to_i | |
end | |
end | |
end | |
def evaluate(s) | |
stack = [] | |
tokenize(s).each do |x| | |
y = x | |
if x.is_a? Symbol | |
y = stack[1].send x, stack[0] | |
stack.shift 2 | |
end | |
stack.unshift y | |
end | |
stack | |
end | |
puts "evaluate: #{evaluate('1 2 +')}" | |
def evaluate2(s) | |
tokenize(s).inject([]) do |stack, x| | |
if x.is_a? Symbol | |
x = stack[1].send x, stack[0] | |
stack.shift 2 | |
end | |
stack.unshift x | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment