🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Code Transformation

Code transformation is building or rewriting code as data, then running it. It builds expressions piece by piece and changes their parts before they run.

A built call can add two names

The built call names addition and the two names, and eval runs it.

a = 10
b = 20
ex = Expr(:call, :+, :a, :b)
println(eval(ex))

Rewriting a part changes the result

The second number changes from 2 to 10, and the printed form shows the change.

ex = :(2 + 3)
ex.args[2] = 10
println(ex)
println(eval(ex))

A built call can multiply two numbers

The built call names multiplication and the two numbers, and eval runs it.

ex = Expr(:call, :*, 6, 7)
println(ex)
println(eval(ex))

Example

ex = Expr(:call, :+, 1, 2, 3, 4)
println(ex)
println(eval(ex))
ex.args[2] = 10
println(ex)
println(eval(ex))

Key points

  • Built call: An Expr value with a call head builds a call from its operator and its arguments.
  • Rewritten parts: Changing a part of an expression changes what the code will do when it runs.
  • Run step: Eval runs a built or rewritten expression.
  • Operator piece: The first part of a call expression names the operation.
  • Use code transformation to build code from values known only while a program runs.

In this example, the built sum prints and runs to 10, the first number changes to 10, and the rewritten sum prints and runs to 19.

Note

A built expression is still data until it is run, so it can be printed and checked first.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

In a built call expression, what does the first part name?