Reinterpret a vector of tuples that contain heterogenous types

Viewed 78

Julia's reinterpret function makes it convenient to reinterpret a block of memory (e.g. a vector of tuples into a matrix). However, I can only get this to work when all the data types in the tuple are of the same type.

For instance:

t = [(1, "a"), (2, "b"), (3, "c")]
reinterpret(reshape, Any, t)  # ERROR!!!

The error message is:

ERROR: ArgumentError: cannot reinterpret `Tuple{Int64, String}` as `Any`, type `Any` is not a bits type 

I've also tried replacing Any with Union{Int, String}, but I still get an error. My target is to get a matrix like [1 "a"; 2 "b"; 3 "c"]:

3×2 Matrix{Any}:                                                                                                         
 1  "a"                                                                                                                  
 2  "b"                                                                                                                  
 3  "c" 

Eventually, I would like to reinterpret vectors of more complex types, such as Tuple{Matrix{Float64}, String, Vector{Int}}.

Is there a way to get around this error?

1 Answers

reinterpret works on bitstypes only.

You could do however:

julia> Vector{NTuple{2, Union{Int,String}}}(t)
3-element Vector{Tuple{Union{Int64, String}, Union{Int64, String}}}:
 (1, "a")
 (2, "b")
 (3, "c")

Related