I was reading the docstring for NamedTuple
and I discovered something odd. You can create a named tuple using pairs, like this:
julia> (; :a=>1, :b=>2)
(a = 1, b = 2)
Trying to do the same thing with tuples instead of pairs doesn’t work:
julia> (; (:a, 1), (:b, 2))
ERROR: syntax: invalid named tuple element "(:a, 1)"
Stacktrace:
[1] top-level scope at REPL[3]:1
That’s not the surprising part. The surprising part is that splatting an array of tuples into a named tuple magically works:
julia> args = [(:a, 1), (:b, 2)];
julia> (; args...)
(a = 1, b = 2)
Given that (; (:a, 1), (:b, 2))
does not work, I would think that splatting tuples into a named tuple would not work either. Is the splatting implicitly converting the tuples to pairs? I wouldn’t think that would be the case either, since splatting tuples into a dictionary doesn’t work (i.e., the tuples are not converted to pairs):
julia> Dict(args...)
ERROR: MethodError: no method matching Dict(::Tuple{Symbol,Int64}, ::Tuple{Symbol,Int64})
Closest candidates are:
Dict(::Any) at dict.jl:127
Stacktrace:
[1] top-level scope at REPL[8]:1
Can anyone explain this apparent inconsistency?