Created
July 6, 2020 03:25
-
-
Save kogad/711c8bf24be47dfcfbceddd469e5ff71 to your computer and use it in GitHub Desktop.
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
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