Created
July 16, 2010 03:37
-
-
Save manveru/477890 to your computer and use it in GitHub Desktop.
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
# Simple RPN calculator with stack. | |
# Example usage: | |
# >> 400 400 400 * | |
# Top of stack: 64000000 | |
# >> 40 40 * | |
# Top of stack: 102400000000 | |
# >> 40 | |
# Top of stack: 40 | |
# >> 30 | |
# Top of stack: 30 | |
# >> + | |
# Top of stack: 102400000070 | |
require 'readline' | |
require 'strscan' | |
stack = [] | |
while line = Readline.readline('>> ', true) | |
next if line.empty? | |
scanner = StringScanner.new(line) | |
until scanner.eos? | |
if scanner.scan(/([+-]?[0-9]+\.[0-9]+)/) | |
stack << scanner[1].to_f | |
elsif scanner.scan(/([+-]?(?:0|[1-9])[0-9]*)/) | |
stack << scanner[1].to_i | |
elsif scanner.scan(%r(([*/+-]))) | |
operand = scanner[1] | |
stack = [stack.inject{|sum, value| sum.send(operand, value) }] | |
elsif scanner.scan(/\s+/) | |
end | |
end | |
puts "Top of stack: %p" % [stack.last] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment