I'm trying to build my own evaluator for mathematical expressions in ruby, and before doing that am trying to implement a parser to break the expression into a tree(of arrays). It correctly breaks down expressions with parenthesis, but I am having lots of trouble trying to figure out how to make it correctly break up an expression with operator precedence for addition.
Right now, a string like 1+2*3+4
becomes 1+[2*[3+4]]
instead of 1+[2*3]+4
. I'm trying to do the simplest solution possible.
Here is my code:
@d = 0
@error = false
#manipulate an array by reference
def calc_expr expr, array
until @d == expr.length
c = expr[@d]
case c
when "("
@d += 1
array.push calc_expr(expr, Array.new)
when ")"
@d += 1
return array
when /[\*\/]/
@d +=1
array.push c
when /[\+\-]/
@d+=1
array.push c
when /[0-9]/
x = 0
matched = false
expr[@d]
until matched == true
y = expr.match(/[0-9]+/,@d).to_s
case expr[@d+x]
when /[0-9]/
x+=1
else matched = true
end
end
array.push expr[@d,x].to_i
@d +=(x)
else
unless @error
@error = true
puts "Problem evaluating expression at index:#{@d}"
puts "Char '#{expr[@d]}' not recognized"
end
return
end
end
return array
end
@expression = ("(34+45)+(34+67)").gsub(" ","")
evaluated = calc @expression
puts evaluated.inspect