本质上我有一个 evaluate 方法,它需要类似的东西
['+','2','3']
这将评估为 5。
目前是这样设置的,
def evaluate(exp)
f = exp[0]
if f == '+' then
return exp[1].to_i + exp[2].to_i
elsif f == '-' then
return exp[1].to_i - exp[2].to_i
elsif f == '*' then
return exp[1].to_i * exp[2].to_i
elsif f == '/' then
return exp[1].to_i / exp[2].to_i
end
end
这工作正常,但必须有更好的方法来做到这一点,而无需巨型 if。有没有办法让我转换符号并使用它? lisp 解释器通常如何处理这个问题?
最佳答案
Ruby 是关于动态规划的。事实上,这会使您的代码简单得离谱:
def evaluate(exp)
exp[1].to_i.send(exp[0], exp[2].to_i)
end
如果这些 token 在途中被转换,那就更容易了:
exp.map! do |token|
case (token)
when /\A\-?\d+\z/
token.to_i
else
token
end
end
然后你得到这个:
def evaluate(exp)
exp[1].send(exp[0], exp[2])
end
现在这假定您只提供有效的操作,您没有做任何荒谬的事情,但对于微不足道的情况,它工作得很好。
如果您已经转换了所有内容并且希望使其更具可扩展性:
def evaluate(exp)
op, *args = exp
args.reduce(&op.to_sym)
end
然后你可以在任意列表上这样做:
evaluate([ '+', 2, 1, 3, 4 ])
关于Ruby Lisp 解释器转换算术符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711084/