Skip to content

Instantly share code, notes, and snippets.

@NobukazuHanada
Forked from urokuta/rpn.rb
Created May 10, 2014 13:39
Show Gist options
  • Save NobukazuHanada/958d9ca95576834f8a0b to your computer and use it in GitHub Desktop.
Save NobukazuHanada/958d9ca95576834f8a0b to your computer and use it in GitHub Desktop.
require "./rpn"
describe "rpn" do
it "" do
expect(expr(4).("+").(3).("*").(2).("-").(1).("=")).
to eq(->(){
comp1 = 3 * 2;
comp2 = 3 + comp1;
comp3 = comp2 - 1;
return comp3 }.call)
end
end
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