So I thought maybe a stack could solve this
So first I can convert one.add.one to 1+1 and that one can be solved by
using eval
Is this a good way to solve it.
Roelof
You can do it without explicit stack :use call stack…
====================================
class Op
attr_accessor :op,:fv,:lv
def initialize(op,firstValue)
self.op,self.fv,self.lv=op,firstValue,nil
end
def self.calculate(calc=false,&b)
a=Op.new(:+,0)
a.instance_eval(&b)
calc ? eval(a.string) : a.string
end
def self.tst_error &b
Op.calculate(true,&b) rescue puts “Ok, error detected: #{$!}”
raise “error not detected!”
end
def operande(n)
if self.lv==nil
raise “double operande” if self.op==:num
self.lv=Op.new(:num,n)
else
raise “double operande”
end
end
def operator(ope)
if self.op==:num
self.op=ope
self
else
raise “double operator”
end
end
def string()
return(self.fv.to_s) unless self.lv && self.op!=:num
if self.fv==0 && self.op==:+
“#{self.lv.respond_to?(:string) ? self.lv.string() : self.lv}”
else
“#{self.fv} #{op} #{self.lv.respond_to?(:string) ?
self.lv.string() : self.lv}”
end
end
def one() operande(1) end
def two() operande(2) end
def par(&b) operande(’(’+Op.calculate(false,&b)+’)’) end
0.upto(1000) {|v| define_method(“i#{v}”) { operande(v) } }
def add() operator(:+) end
def sub() operator( end
def mult() operator(:*) end
def div() operator(:/) end
end
p Op.calculate { one }
p Op.calculate { one.add }
p Op.calculate { one.add.one }
p Op.calculate { one.add.i100.sub.one}
p Op.calculate { two.mult.par { one.add.i100 } }
p Op.calculate { two.mult.par { one.add.i100 }.add.one }
p Op.tst_error { one.add.add.one }
I try to make a function which can calculate
one.add.one
if I do it step by step I cannot solve it because im on
the add I still have 1+
So I thought maybe a stack could solve this
So first I can convert one.add.one to 1+1 and that one can
be solved by using eval
Is this a good way to solve it.
My
initial reaction is: no. `eval` is never a good way to do
anything.
???
However the general idea -- of building up a "stack" of
symbols, and then evaluating them -- is good. And I admit,
building a string and using `eval` is temptingly
simple...
My initial reaction is: no. eval is never a good way to do anything.
However the general idea – of building up a “stack” of symbols, and
then
evaluating them – is good. And I admit, building a string and using eval
is temptingly simple…