Skip to content

Instantly share code, notes, and snippets.

@kogad
Created July 6, 2020 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kogad/711c8bf24be47dfcfbceddd469e5ff71 to your computer and use it in GitHub Desktop.
Save kogad/711c8bf24be47dfcfbceddd469e5ff71 to your computer and use it in GitHub Desktop.
using Test
abstract type AbstractNode end
struct FuncNode <: AbstractNode
func::Function
childlen::Vector{AbstractNode}
end
struct VarNode <: AbstractNode
var::String
end
struct ConstNode <: AbstractNode
value::Number
end
eval_tree(node::ConstNode, args) = node.value
eval_tree(node::VarNode, args) = args[node.var]
eval_tree(node::FuncNode, args) = node.func(eval_tree.(node.childlen, Ref(args)))
add(x) = x[1] + x[2]
sub(x) = x[1] - x[2]
mul(x) = x[1] * x[2]
div(x) = ifelse(x[2] == 0, 1, x[1] / x[2])
t = FuncNode(add, [
FuncNode(mul, [
ConstNode(5.0),
VarNode("x")]),
VarNode("y")])
args = Dict("x" => 2.0, "y" => 5.0)
@show eval_tree(t, args) # 15.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment