Julia Code Generation
Code generation is building code as data and then running it with eval at top level. The new definition is ready to call right after eval runs.
Eval defines a function at top level
Eval runs quoted code at top level. The new function is ready to call right after it.
eval(:(g(x) = x + 10))
println(g(5))Eval can define a second function
Eval can define a second function in the same way. The new function triples its input.
eval(:(triple(x) = 3 * x))
println(triple(4))Eval can also set a top level value
The quoted assignment runs at top level. The value is then ready to print.
eval(:(answer = 42))
println(answer)Example
eval(:(add5(x) = x + 5))
eval(:(double(x) = 2 * x))
println(add5(10))
println(double(6))
println(double(add5(3)))Key points
- Code generation: build code as data, then run it with eval.
- Eval: eval runs a quoted expression at top level.
- Definition: eval of a quoted function definition makes that function ready to call.
- Top level: the new name lives at top level, not inside another function.
- Order: define with eval first, then call the new function.
In this example, eval defines add5 and double at top level. The calls then show 15, 12, and 16 in order.
Note
eval runs code, so use it only on code you wrote or trust.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
After eval(:(g(x) = x + 10)), what is g(5)?