Code
julia
# 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