Created
March 10, 2020 15:37
-
-
Save metanest/1b4ea73841ca1ec4cb598765fa18e0ab to your computer and use it in GitHub Desktop.
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
#! /usr/local/bin/ruby27 | |
module Expr2RPN | |
class Node | |
def method_missing mname, *args | |
unless [:+, :*].include? mname then | |
super | |
end | |
args_length = args.length | |
if args_length != 1 then | |
raise ArgumentError, "#{mname}: wrong number of arguments (given #{args_length}, expected 1)" | |
end | |
NodeRPN.new "#{self.to_rpn} #{args[0].to_rpn} #{mname}" | |
end | |
end | |
class NodeRPN < Node | |
attr :val | |
def initialize arg | |
@val = arg | |
end | |
def to_rpn | |
@val | |
end | |
end | |
class Term < Node | |
attr :val | |
def initialize arg | |
@val = arg | |
end | |
def to_rpn | |
"#{@val}" | |
end | |
end | |
class Runner < BasicObject | |
def term arg | |
Term.new arg | |
end | |
end | |
def self.run &c | |
Runner.new.instance_eval &c | |
end | |
end | |
print(Expr2RPN.run{ | |
a = term 3 | |
b = term 4 | |
c = term 5 | |
d = term 6 | |
"#{(a*b + c*d).to_rpn}\n" | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment