Hello,
I would like to initialize multiple variables in one line.
The following code does not work:
a = b = c = Set{Symbol}()
If I do:
push!(a, :test)
all three variables get the same value.
I just want to initialize all of them as empty set of Symbols, but later they shall contain different values.
Any idea how to achieve this in one line?
julia> a, b, c = repeat([Set{Symbol}()], 3)
3-element Array{Set{Symbol},1}:
Set([])
Set([])
Set([])
julia> a
Set(Symbol[])
julia> b
Set(Symbol[])
julia> c
Set(Symbol[])
julia>
The proposed solutions still seem to violate DRY (a bit ) because the number of the variables on the left-hand side of the assignment must match the number on the right-hand side. Unfortunately I don’t see a way to fix this without a macro. Perhaps the following:
macro multidef(ex)
@assert(ex isa Expr)
@assert(ex.head == :(=))
vars = ex.args[1].args
what = ex.args[2]
rex = quote end
for var in vars
push!(rex.args, :($(esc(var)) = $what))
end
rex
end
Here it is for the record. I find it super useful, also to learn about writing macros, thanks for sharing!
macro multidef(ex)
@assert(ex isa Expr)
@assert(ex.head == :(=))
vars = ex.args[1].args
what = ex.args[2]
rex = quote end
for var in vars
push!(rex.args, :( $(esc(var)) = $(esc(what)) ))
end
rex
end
Vectors are not of an unchangeable length, so we can add elements to them; they are stored indirectly. Tuples are fixed in size and other ways, so they are stored directly (immediately in very fast microprocessor-accessible memory).