Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia parametric function for Array of Array with multiple dispatch

Tags:

arrays

julia

I am trying to write two functions with same name that can make use of multiple dispatch facility of Julia and involved Arrays and Arrays of Array.

Suppose there are these three input variables

# typeof(a) => Array{Array{T,N},1}
a=Array[[1,2,3],[4,5,6]]

# typeof(b) => Array{Int64,1}
b=[1,2,3]

# typeof(c) => Array{Array{Float64,1},1}
c=[rand(10) for i in 1:2]

And I write the two functions like this

function test(x::Array{Array})
    println("received an array of array => $(typeof(x))")
end

function test{T<:Number}(x::Array{T,1})
    println("received a vector. converting.....")
    nx = Array[x]
    test(nx)
end

The above approach works for a and b but not c.

test(a)
# received an array of array => Array{Array{T,N},1}

test(b)
# received a vector. converting.....
# received an array of array => Array{Array{T,N},1}

test(c)
# LoadError: MethodError: `test` has no method matching test(::Array{Array{Float64,1},1})
# while loading In[37], in expression starting on line 1

Now if I change the function definition to x::Array{Array{Float64,1},1} this would work. But my question is isn't Array{Array} supposed to take any kind of Arrays of Array?

How should one work with inner type parameter on an array of arrays?

like image 951
datafig Avatar asked Jan 09 '16 02:01

datafig


1 Answers

is isn't Array{Array} supposed to take any kind of Arrays of Array?

yes and no... it is supposed to but not in this way.

i guess you've already known that Julia’s type parameters are invariant.

note that Array itself is a parametric type, so you should use Array{T} where T<:Array instead of Array{Array}:

function test{T<:Array}(x::Array{T})
    println("received an array of array => $(typeof(x))")
end
like image 88
Gnimuc Avatar answered Sep 21 '22 16:09

Gnimuc