Skip to content

Instantly share code, notes, and snippets.

@urokuta
Last active August 29, 2015 14:01
Show Gist options
  • Save urokuta/b0b2812687465660974c to your computer and use it in GitHub Desktop.
Save urokuta/b0b2812687465660974c to your computer and use it in GitHub Desktop.
rpn
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).("=")
@urokuta
Copy link
Author

urokuta commented May 10, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment