Last active
August 29, 2015 14:01
-
-
Save urokuta/b0b2812687465660974c to your computer and use it in GitHub Desktop.
rpn
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
def expr(e, stack=[], rpn=[]) | |
case e | |
when "=" | |
rpn += stack.reverse | |
return rpn.inject([]) do |arr, token| | |
case token.to_s | |
when /[-+*\/]/ then arr << arr.pop(2).inject($&) | |
when /\d+/ then arr << $&.to_f | |
end | |
end.shift | |
when /[\-+*\/]/ | |
case e | |
when /[*\/]/ then stack << e | |
else rpn += stack.reverse ;stack = [e] | |
end | |
else rpn << e | |
end | |
->(e){expr(e, stack, rpn)} | |
end | |
puts expr(4).("+").(3).("*").(2).("-").(1).("=") | |
puts expr(1).("*").(2).("+").(6).("/").(3).("=") | |
puts expr(1).("+").(2).("+").(6).("/").(3).("=") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://melborne.github.io/2012/06/19/rpn-with-inject/
参考にしました