Method for array of arrays

I’d like to write a method for an array of arrays, for example

simple(g::Array{Array{Float64}}) = g

should be an identity function.

But if try

A = [1. 2.; 3. 4.]
B = [5. 6. 7.; 8. 9. 0.]
g = [A, B]

simple(g)

I get

ERROR: MethodError: no method matching simple(::Array{Array{Float64,2},1})
Closest candidates are:
  simple(::Array{Array{Float64,N} where N,N} where N) at REPL[1]:1

If I change the method to

simple(g::Array{Array{Float64, 2}, 1}) = g

I get the expected result, but I’d like to generalize this method to any dimension size. How do I modify my method to do this?

As general as possible on Array (of course, this could be extended to AbstractArray as well).

julia> simple(g::Array{Array{T,N},N2}) where {T,N,N2} = g
simple (generic function with 1 method)

julia> A = [1. 2.; 3. 4.]
2×2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> B = [5. 6. 7.; 8. 9. 0.]
2×3 Array{Float64,2}:
 5.0  6.0  7.0
 8.0  9.0  0.0

julia> g = [A, B]
2-element Array{Array{Float64,2},1}:
 [1.0 2.0; 3.0 4.0]
 [5.0 6.0 7.0; 8.0 9.0 0.0]

julia> simple(g)
2-element Array{Array{Float64,2},1}:
 [1.0 2.0; 3.0 4.0]
 [5.0 6.0 7.0; 8.0 9.0 0.0]
2 Likes

Or more succinctly: f(g::Array{<:Array}) = ...

Or if you want to accept general array-like containers: f(g::AbstractArray{<:AbstractArray}) = ...

Note that all of these suggestions will only work in Julia 0.6 or higher (making this possible was a major feature of the 0.6 release)

2 Likes

Thanks @ChrisRackauckas!

Thanks @rdeits! Where can I find the documentation about this?

There’s some documentation about this feature here: https://docs.julialang.org/en/stable/manual/types/#UnionAll-Types-1 and in the section above on “Parametric Types”