Can I invoke Julia's built-in type inference on a subarray{Any}?


#1

Given this:

julia> mat = [1 2; 3.0 4.0; 5 6.0; "seven" "eight"; :nine :ten]
4×2 Array{Any,2}:
 1        2
 3.0      4.0
 5        6.0
 "seven"  "eight"
 :nine    :ten

julia> typeof(mat[1,1])
Int64

julia> typeof(mat[2,1])
Float64

julia> typeof(mat[1,:])
Array{Any,1}

julia> typeof(mat[2,:])
Array{Any,1}

Is there a built-in function somewhere, let’s call it typeinfer(), that can do this?

julia> typeinfer(mat[1,:])
Array{Int64,1}

julia> typeinfer(mat[2,:])
Array{Float64,1}

julia> typeinfer(mat[3,:])
Array{Float64,1}

julia> typeinfer(mat[4,:])
Array{String,1}

julia> typeinfer(mat[5,:])
Array{Symbol,1}

Or do I have to roll my own?


#2

The type cannot be inferred because the container has element type Any. So it will have to be a runtime check, which (I suspect) you have to write yourself.


#3

How about this:

julia> [mat[1, :]...]
2-element Array{Int64,1}:
 1
 2

julia> v = [ [mat[i,:]...] for i in 1:size(mat, 1)]
5-element Array{Array{T,1},1}:
 [1,2]
 [3.0,4.0]
 [5.0,6.0]
 String["seven","eight"]
 Symbol[:nine,:ten]

julia> v[1]
2-element Array{Int64,1}:
 1
 2

julia> v[2]
2-element Array{Float64,1}:
 3.0
 4.0

But the real question is why would you store things like that in the first place?


#4

Brilliant! Why didn’t I think of trying a splat? Thanks!!

It’s a small part of a large optimization model (using JuMP). I have a macro that reads an external table of variable names and data and creates those variables in the local scope. And now I wanted to identify the type as well.

I know this setup would be absolutely horrible for ordinary coding projects, but for optimization the focus is on the equations, so the hack is fine. Probably. :slight_smile: