How to pass NamedTuples as arguments to a function?

I have the following function defined.
f(a::Int64,r::Float64,q::Float64,p::Int64) = a + r + q + p

t1 = (a=1,c=3,r=5.3)
t2 = (d=3,q=6.2,p=8)

How do I pass the namedtuples as function arguments?
e.g.
_f(t1,t2) = f(a,r,q,p)
Desired output:
_f(a=1,c=3,r=5.3,d=3,q=6.2,p=8) = f(a,r,q,p)

1 Like

Define f with keyword arguments and splat after ;.

4 Likes

But wouldn’t this fail in the above given that the named tuple includes names that aren’t kwargs?

One can always do some version of

_f(t1, t2) = f(t1.a, t1.r, t2.q, t2.p)

but generally it is a somewhat brittle design (and no, I would not use introspection to extract the argument names for f).

Just to clarify: I was suggesting

f(; a::Int64, r::Float64, q::Float64, p::Int64, _...) = a + r + q + p
f(; merge(t1, t2)...)

I assume that this is for quick prototyping — for everything else I would recommend putting parameters in structs, and using

2 Likes

Aren’t you looking for something like this

t1 = (a=1,c=3,r=5.3)
t2 = (d=3,q=6.2,p=8)

function f(a1::@NamedTuple{a::Int64, c::Int64, r::Float64}, a2::@NamedTuple{d::Int64, q::Float64, p::Int64})::Float64
    return a1.a + a1.r + a2.q + a2.p
end
f(t1, t2)
1 Like