TExcelTAD
Home › Julia › Julia Expressions & Metaprogramming

Julia Expressions & Metaprogramming

Julia code is itself a Julia data structure. Before a program runs, its text is parsed into expressions: objects of type Expr that you can inspect, build and change from Julia code. Writing code that generates code is called metaprogramming. It's what powers macros like @show, @printf and @time.

Symbols

A Symbol is an interned name, written with a leading colon. Symbols represent identifiers (variable and function names) in code, and are also handy as cheap dictionary keys:

julia · try it yourself
s = :temperature
println(s, " ", typeof(s))
println(Symbol("temp", 2))
println(:abc === Symbol("abc"))
println(String(:hello) * "!")
temperature Symbol
temp2
true
hello!

Quoting code

:( ... ) or a quote ... end block quotes code: instead of running it, Julia gives you the expression object.

julia · try it yourself
ex = :(a + b * 2)
println(ex)
println(typeof(ex))
println(ex.head)
println(ex.args)
dump(:(x^2))
a + b * 2
Expr
call
Any[:+, :a, :(b * 2)]
Expr
  head: Symbol call
  args: Array{Any}((3,))
    1: Symbol ^
    2: Symbol x
    3: Int64 2

An Expr has a head describing the kind of expression (:call, :if, :(=), :block, ...) and args, its parts. a + b * 2 is a call to + with arguments a and the nested expression b * 2.

Evaluating expressions

eval runs an expression in the global scope of the current module:

julia · try it yourself
ex = :(3 * 4 + 1)
println(eval(ex))

a, b = 10, 5
println(eval(:(a - b)))

# Build an expression piece by piece
call = Expr(:call, :max, 4, 9, 2)
println(call, " = ", eval(call))

parsed = Meta.parse("sqrt(81) + 1")
println(typeof(parsed), " ", eval(parsed))
13
5
max(4, 9, 2) = 9
Expr 10.0

Meta.parse turns a string into an expression. Note that eval always works at global scope; it can't see a function's local variables.

Interpolation into quoted code

Inside a quote, $ inserts a value (or another expression) instead of a name — the same character used in strings:

julia · try it yourself
n = 5
ex1 = :(x + n)        # refers to the name n
ex2 = :(x + $n)       # inserts the value 5
println(ex1, "   |   ", ex2)

op = :*
args = [2, 3, 7]
product = :($op($(args...)))   # splatting into an expression
println(product, " = ", eval(product))
x + n   |   x + 5
2 * 3 * 7 = 42

Generating code

Metaprogramming shines for removing repetition. Here a loop generates several similar functions:

julia · try it yourself
for (name, factor) in [(:to_km, 1.609344), (:to_cm, 2.54), (:to_kg, 0.45359237)]
    @eval $name(x) = round(x * $factor, digits=3)
end

println(to_km(26.2))
println(to_cm(12))
println(to_kg(150))
42.165
30.48
68.039

@eval expr is shorthand for eval(quote expr end), with $ interpolating the loop variables. Base uses this technique to define many operators for many number types at once.

Walking an expression tree

Because expressions are just data, ordinary recursive functions can analyse them. This one counts the function calls in an expression:

julia · try it yourself
count_calls(x) = 0
count_calls(ex::Expr) = (ex.head == :call ? 1 : 0) + sum(count_calls, ex.args; init=0)

ex = :(sin(x)^2 + cos(x) * f(g(1)))
println(count_calls(ex))

replace_sym(x, from, to) = x == from ? to : x
replace_sym(ex::Expr, from, to) = Expr(ex.head, (replace_sym(a, from, to) for a in ex.args)...)
println(replace_sym(:(x^2 + 3x), :x, :(y + 1)))
7
(y + 1) ^ 2 + 3 * (y + 1)

The 7 calls are +, ^, sin, *, cos, f and g.

Note: Metaprogramming is powerful but makes code harder to read. Prefer ordinary functions, multiple dispatch and higher-order functions; reach for eval and macros when they genuinely remove a lot of boilerplate.

Test yourself

What is the type of :(1 + 2)?

  1. Int64
  2. Symbol
  3. Expr
  4. String

What is :(x + $y) when y = 4?

  1. :(x + y)
  2. :(x + 4)
  3. x + 4 evaluated
  4. an error

In which scope does eval run code?

  1. The enclosing function's local scope
  2. The global scope of the current module
  3. A new temporary module
  4. The scope of the caller's caller