Last active
August 26, 2015 18:54
-
-
Save Ismael-VC/b9de88ae140eec87210d to your computer and use it in GitHub Desktop.
Julia Metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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