Concise unpacking syntax

I have a namedtuple data = (;a=1,b=2,c=3) and a function f that takes kwargs ;a,b. I want to call f with f(;a,b)

f(;a,b) = a+b
data = (;a=1,b=2,c=3)
(;a,b) = data

But there I have to specify a and b twice: once in the unpacking and once at the call site. Is it possible to specify them only once?

I tried something like this but not right.

data2 = (;a,b) = data


f(((;a,b) = data)...)

Note that for the splatting into kwargs you need a ;.
However, your later tries also do not work with an added ; as an assignment returns the right-hand-side.

This works:

julia> f(;a,b,kw...) = a+b
f (generic function with 1 method)

julia> f(;data...)

but may not be quite what you’d like.

1 Like

That requires changing the function, which isn’t what I want.

julia> f(;((;a,b) = data)...)
ERROR: MethodError: no method matching f(; a=1, b=2, c=3)

This should work: f(; data[(:a, :b)]...).