【发布时间】:2018-03-09 19:00:09
【问题描述】:
我正在编写一个基因程序来测试随机生成的表达式的适应度。这里显示的是生成表达式的函数以及主函数。 DIV 和 GT 在代码的其他地方定义:
function create_single_full_tree(depth, fs, ts)
"""
Creates a single AST with full depth
Inputs
depth Current depth of tree. Initially called from main() with max depth
fs Function Set - Array of allowed functions
ts Terminal Set - Array of allowed terminal values
Output
Full AST of typeof()==Expr
"""
# If we are at the bottom
if depth == 1
# End of tree, return function with two terminal nodes
return Expr(:call, fs[rand(1:length(fs))], ts[rand(1:length(ts))], ts[rand(1:length(ts))])
else
# Not end of expression, recurively go back through and create functions for each new node
return Expr(:call, fs[rand(1:length(fs))], create_single_full_tree(depth-1, fs, ts), create_single_full_tree(depth-1, fs, ts))
end
end
function main()
"""
Main function
"""
# Define functional and terminal sets
fs = [:+, :-, :DIV, :GT]
ts = [:x, :v, -1]
# Create the tree
ast = create_single_full_tree(4, fs, ts)
#println(typeof(ast))
#println(ast)
#println(dump(ast))
x = 1
v = 1
eval(ast) # Error out unless x and v are globals
end
main()
我正在根据某些允许的函数和变量生成随机表达式。从代码中可以看出,表达式只能有符号 x 和 v,以及值 -1。我将需要使用各种 x 和 v 值来测试表达式;这里我只是使用 x=1 和 v=1 来测试代码。
表达式被正确返回,但是,eval() 只能与全局变量一起使用,因此除非我将 x 和 v 声明为全局变量,否则它将在运行时出错(错误:LoadError:UndefVarError:x 未定义) .如果可能的话,我想避免使用全局变量。有没有更好的方法来使用本地定义的变量生成和评估这些生成的表达式?
【问题讨论】:
-
也许可以使用输入参数创建函数的 AST(而不是表达式的 AST)?
标签: julia metaprogramming