Skip to content

Instantly share code, notes, and snippets.

@altitude
Last active August 29, 2015 14:00
Show Gist options
  • Save altitude/11395561 to your computer and use it in GitHub Desktop.
Save altitude/11395561 to your computer and use it in GitHub Desktop.
Ruby Prefix Notation Parser
class Prefix
def initialize
@expression_regex = /\([\w+*\-]+ (\w+ ?)+\)/
@operators = {}
@operators["+"] = lambda {|args| return args.map{|x| x.to_i}.inject(:+) }
@operators["*"] = lambda {|args| return args.map{|x| x.to_i}.inject(:*) }
@operators["-"] = lambda {|args| return args.map{|x| x.to_i}.inject(:-) }
end
def process(expression)
while fragment = @expression_regex.match(expression) do
stack = fragment.to_s.gsub('(','').gsub(')','').split(' ')
expression.sub!(@expression_regex, @operators[stack.shift].call(stack).to_s)
end
return expression.to_i
end
end
prefix = Prefix.new
tests = [
'(+ 3 3)',
'(* 2 6)',
'(* 2 2 2)',
'(- 5 4)',
'(+ (* 2 3) 4)',
'(+ (* 2 3) (- 9 8))',
]
tests.each do |test|
print test + " => "
print prefix.process(test).to_s + "\n"
end
# puts tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment