Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Created June 18, 2012 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimweirich/2948710 to your computer and use it in GitHub Desktop.
Save jimweirich/2948710 to your computer and use it in GitHub Desktop.
Another expression tree evaluator
# Another version of the code at https://gist.github.com/2934374
Number = lambda { |env, num| num }
Variable = lambda { |env, var| env[var] }
Add = lambda { |env, a, b| evaluate(env, a) + evaluate(env, b) }
Multiply = lambda { |env, a, b| evaluate(env, a) * evaluate(env, b) }
def evaluate(env, exp)
op, *args = exp
op.(env, *args)
end
ExpressionTree = [Add, [Variable, :a], [Multiply, [Number, 2], [Variable, :b]]]
Env = { a: 3, b: 4, c: 5 }
puts evaluate(Env, ExpressionTree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment