Skip to content

Instantly share code, notes, and snippets.

@Ismael-VC
Last active August 26, 2015 18:54
Show Gist options
  • Save Ismael-VC/b9de88ae140eec87210d to your computer and use it in GitHub Desktop.
Save Ismael-VC/b9de88ae140eec87210d to your computer and use it in GitHub Desktop.
Julia Metaprogramming
julia> for sym in (:foo, :baz, :bar)
#=
$ is used to interpolate expressions (`Expr`) and symbols into other expressions
it is also used to interpolate values in strings and commands (`Cmd`)
=#
@eval $(sym)() = println($"$sym was called")
end
julia> syms = [symbol(string(:test, i)) for i in 1:5] # generate symbols
5-element Array{Symbol,1}:
:test1
:test2
:test3
:test4
:test5
julia> for sym in syms
@eval $(sym)() = println($"$sym was called") # function definitions
end
julia> for sym in syms
@eval $sym() # function calls
end
test1 was called
test2 was called
test3 was called
test4 was called
test5 was called
julia> dump( # the expression AST
quote
for sym in syms
@eval $(sym)() = println($"$sym was called")
end
end
)
Expr
head: Symbol block
args: Array(Any,(2,))
1: Expr
head: Symbol line
args: Array(Any,(2,))
1: Int32 3
2: Symbol none
typ: Any
2: Expr
head: Symbol for
args: Array(Any,(2,))
1: Expr
head: Symbol =
args: Array(Any,(2,))
typ: Any
2: Expr
head: Symbol block
args: Array(Any,(2,))
typ: Any
typ: Any
typ: Any
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment