I would like to write a Julia program that does the following:
- Build up a big, complicated Expr object using metaprogramming
- Compile that expression into a Julia function
- Call that function repeatedly with different arguments
My main reason for doing things this way is performance, so I really want the compilation step, not just repeated calls to
eval. It seemed like the following should do this, but it gives an error (below) - what is the correct way to achieve what I want?
Here’s the minimal test code:
function make_expression() return :(x+2) end function main() expr = make_expression() @eval f(x) = $expr println(f(10)) end main()
and here’s the error:
$ julia test.jl ERROR: LoadError: MethodError: no method matching f(::Int64) The applicable method may be too new: running in world age 25574, while current world is 25575. Closest candidates are: f(::Any) at [...]/test.jl:11 (method too new to be called from this world context.) Stacktrace:  main() at [...]/test.jl:13  top-level scope at none:0  include at ./boot.jl:326 [inlined]  include_relative(::Module, ::String) at ./loading.jl:1038  include(::Module, ::String) at ./sysimg.jl:29  exec_options(::Base.JLOptions) at ./client.jl:267  _start() at ./client.jl:436 in expression starting at [...]/test.jl:17
Note that the error goes away if I put the contents of the
main function in a global scope instead. But I don’t really want to do that.