Index elements of a function with several outputs

I would like to access specific output elements of a function.
Here an example:

function foo()
    return 1, 2, 3, 4, 5

If I am only interested in output two and four I can use the underscore:

_, output2, _, output4, _ = foo()

If I am interested in outputs that are neighbors, I can write:

a, b = foo()[2:3]

In my case the function has 8 outputs and I am interested in the the first two and the last one, this looks as follows:

a, b, _, _, _, _, _, c = myfunction()

Is there something more elegant available?

You can index by a vector of indices:

julia> function foo()
           return 'a', 'b', 'c', 'd', 'e', 'f', 'g'

julia> foo()[[3, 5, 1]]
('c', 'e', 'a')

I am, however, not sure if this is the best design. Instead, consider splitting your function into multiple smaller ones, each producing a single output, and then call only the ones you need. It is not always possible (or worth doing) though.

1 Like

Another option would be to return a named tuple, if you have sensible names for the different outputs. For example:

function foo()
    return (a=1, b=2, c=3, d=4, e=5)

Then you can do, for example:

(; a, c, e) = foo()
1 Like

You can do something less pretty like

z = myfunction()
a,b,c = z[begin],z[begin+1],z[end]

I haven’t downloaded it yet on this machine, but as of v1.9 the following is allegedly supported (I have not verified, so it may not) thanks to #42902:

a,b,_...,c = myfunction()