I have a function f() = (a=1, b=2, c=3) , and I can pick out one of the returned components of the tuple as
julia> f().a
1
Can I select in this way a and at the same time c? In other words, I would like to get a, c = f()???.
You could do (; a, c) = f()
Ah, that is very good. Thanks!
gdalle
June 12, 2023, 5:19am
4
Only works for Julia \geq 1.7 though
Actually, I realized I would really like to be able to collect the results in variables whose names are not the same as those in the named tuple. For example: myvar = f().c. But with an arbitrary multiple selection, myv1, myv2 = f()... (let us say, a and c).
Can this be done?
OK, found this:
julia> v1, v2 = f()[[:a, :c]]
(a = 1, c = 3)
julia> v1
1
julia> v2
3
Can this be made more succinct?
julia> f() = (; a=1, b=2, c=3, d=4)
f (generic function with 1 method)
julia> x, _, _, y = f()
(a = 1, b = 2, c = 3, d = 4)
julia> x
1
julia> y
4
here there may be something close
Eben60
June 12, 2023, 7:29pm
9
Nice! What I’m not so happy about is that one has to know the order in which the arguments have been returned.
How do you want it to look? There’s not all that much unsuccinctness to work with in the solution you found.
If this is the best, I shall be content.
Don’t blame @PetrKryslUCSD . Like all good Julians, he’s greedy .
Benny
June 13, 2023, 1:50am
14
PetrKryslUCSD:
v1, v2 = f()[[:a, :c]]
This looks good, could avoid allocating that array of symbols because named tuples support indexing with tuples of symbols f()[(:a, :c)].