A bit of explanation, list
is going to be Tuple
of expressions which I expect are of the form :((name, size...))
, so I am going to map
over that tuple to turn it into the desired form.
The function map(f, v)
takes a function f
and applies it to each element of a container v
and returns the result, e.g.
julia> map(x -> x + 1, 1:4)
4-element Array{Int64,1}:
2
3
4
5
The syntax
map(v) do x
#= stuff here =#
end
is just a fancy way to write
map(x -> #= stuff here =#, v)
so,
julia> map(1:4) do x
x + 1
end
4-element Array{Int64,1}:
2
3
4
5
Alright, so now we see what I’m doing when I write
defs = map(list) do ex
@assert ex.head == :tuple
name = ex.args[1]
size = ex.args[2:end]
:($name = $zeros($tp, $name, $(size...)))
end
This is mapping over list
, asserting that each element of that list is an expression whose head
is :tuple
(i.e. it’s something of the form :((x, y, z))
), and then taking out the first element of that tuple and saying that’s going to be our variable name, and the rest will say how big our array should be. With those pulled out, I create a new expression that :($name = $zeros($tp, $name, $(size...)))
where I have interpolated in the variables name
, tp
and size
into a expression an array definition to name
. I also interpolated in the function zeros
to ensure that the function I call zeros
gets used, not whatever some other user might have bound to zeros
.
This gives us and array of expressions for array definitions and I then stick them into an Expr(:block)
which is the construct julia uses for holding multiple expressions together, e.g.
julia> ex = quote
1 + 1
2 + 3
end
quote
1 + 1
2 + 3
end
julia> dump(ex)
Expr
head: Symbol block
args: Array{Any}((4,))
1: Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol +
2: Int64 1
3: Int64 1
2: Expr
head: Symbol call
args: Array{Any}((3,))
1: Symbol +
2: Int64 2
3: Int64 3
I then apply esc
to that function which is related to the macro hygeine stuff in this section of the docs.
This escaped expression is then returned, not eval
’d, so that it functions like a normal macro.