Macros & Expressions
Manipulate Julia syntax trees as first-class data via :expr and macro.
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) # 12Explanation
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
Broadcasting & Vectorization
Apply a function element-wise over arrays with dot syntax and @.
Multiple Dispatch
Select methods by the runtime types of all arguments, not just the receiver.
Parametric Types & Performance
Define generic, type-stable containers that compile to specialized code.
Multi-threading & Distributed Compute
Parallelize loops with @threads and offload tasks with @spawn / pmap.
DataFrame Operations (DataFrames.jl)
Filter, transform, group, and join tabular data with DataFrames.jl.
Performance Tips: @inbounds, @fastmath, views
Write Julia that runs at C speed by removing bounds checks, avoiding allocations, and using views.