-
-
Save ckirkendall/2948876 to your computer and use it in GitHub Desktop.
Another expression tree evaluator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn evaluate [env [op & args]] | |
(apply op env args)) | |
(defn number [env num] num) | |
(defn variable [env var] (env var)) | |
(defn add [env a b] (+ (evaluate env a) (evaluate env b))) | |
(defn multiply [env a b] (* (evaluate env a) (evaluate env b))) | |
(def expression-tree [add [variable :a] [multiply [number 2] [variable :b]]]) | |
(def env {:a 3, :b 4, :c 5}) | |
(evaluate env expression-tree) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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