🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Expressions and Quote

A quoted expression is Julia code held as data instead of run at once. Reading its parts shows how Julia sees the code.

A quote holds code as data

The quote operator turns code into a value. Its type is Expr.

ex = :(a + b)
println(typeof(ex))
println(ex.head)

The parts sit in order in args

The head names the kind of expression. The parts list holds the operator and the two names in order.

ex = :(a + b)
println(length(ex.args))
println(ex.args[1])
println(ex.args[2])
println(ex.args[3])

Interpolation places a value inside a quote

A dollar sign inside a quote places a value in place of a name. The quoted part then holds the number itself.

x = 3
ex = :($x + 2)
println(typeof(ex))
println(ex.args[2])

Example

a = 4
b = 5
ex = :($a + $b)
println(typeof(ex))
println(ex.head)
println(length(ex.args))
println(ex.args[1])
println(ex.args[2])
println(ex.args[3])

Key points

  • Quote: use :( ... ) to hold code as data.
  • Expression: a quoted piece of code has type Expr.
  • Head: ex.head names the kind of expression.
  • Parts: ex.args holds the parts in order.
  • Interpolation: use $ inside a quote to place a value into the expression.

In this example, a and b hold 4 and 5. The quote places those values into an addition expression. The printed lines show its type, its head, its part count, and its three parts in order.

Note

a quoted name on its own is a symbol, not the value of a variable with that name.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does :(a + b).head give?