Unpack vector of tuples from broadcasted function

Hello,

I think this is really simple but I can’t figure it out.

I have a function which I broadcast, something like:

function gives3(x)
    return x^2, x^3, x^4
end

inputs = [1, 2, 3, 4, 5]

output = gives3.(inputs)

output is a Vector{Tuple{Int64, Int64, Int64}}. I want to unpack these tuples and have them in separate vectors, so that when I write (or something similar):

v1, v2, v3 = gives3.(inputs)

I’d like:

julia> v2
5-element Vector{Int64}:
   1
   8
  27
  64
 125

Any idea on how to make this happen? I’m OK changing how gives3() returns stuff as long as I can return 3 elements.

Thanks!

One way:

julia> v1, v2, v3 = [getindex.(output, i) for i ∈ 1:3]
3-element Vector{Vector{Int64}}:
 [1, 4, 9, 16, 25]
 [1, 8, 27, 64, 125]
 [1, 16, 81, 256, 625]

Thanks! I’d like to simply change the syntax without calling another function or looping over output.

try defining new method for arrays, using broadcast internally not externally to the function:

julia> function gives3(x::Array)
           return x.^2, x.^3, x.^4
       end
gives3 (generic function with 2 methods)
julia> inputs = [1, 2, 3, 4, 5]
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> v1,v2,v3 = gives3(inputs)
([1, 4, 9, 16, 25], [1, 8, 27, 64, 125], [1, 16, 81, 256, 625])

julia> v2
5-element Vector{Int64}:
   1
   8
  27
  64
 125

The Unzip package implements this:

using Unzip

v1, v2, v3 = unzip(gives3.(inputs))

Ditto for the SplitApplyCombine package via the invert() function