Skip to content
Julia

Macros & Expressions

Manipulate Julia syntax trees as first-class data via :expr and macro.

By EZ4Code Team
macrosmetaprogrammingexpressions

Code

# Expressions are first-class values (quoted with : or quote)
ex = :(1 + 2 * 3)
typeof(ex)            # Expr
ex.head               # :call
ex.args               # [:+, 1, :(2 * 3)]

# Evaluate an expression
eval(ex)              # 7

# Macros operate on syntax at parse time
macro @time_it(expr)
    return quote
        local t0 = time()
        local val = $(esc(expr))
        local t1 = time()
        println("elapsed: ", t1 - t0, " s")
        val
    end
end

@time_it begin
    s = 0.0
    for i in 1:1_000_000
        s += sqrt(i)
    end
    s
end

# code generation: build expressions programmatically
ops = [:+, :-, :*, :/]
funs = [ Expr(:function, Expr(:call, Symbol("op_$op"), :a, :b),
              Expr(:return, Expr(:call, op, :a, :b))) for op in ops ]
for f in funs
    eval(f)
end
op_*(3, 4)   # 12

Explanation

Julia code is represented as Expr objects (head + args), so programs can generate and eval code at run time — this is the basis of broadcasting, autodiff, and many DSLs. Macros (declared with 'macro') run at parse time and receive the unparsed expression; esc() prevents hygiene from renaming variables the user wrote. Together they let libraries like Flux and DifferentialEquations.jl feel like built-in syntax.

More Julia Snippets