Sounds like we don’t have an explicit function to do this, but do have several
ways of achieving this result through vcat, map or ad hoc code.
I’ve used a loop like the one Samuel Jenkins describes in the past. I’ll stick
with that as part of the conversion process I use.
The reason I bring this up is that this kind of type-tightening recurs
throughout the DataArrays/DataFrames world. I’ve used it in settings in which I
allocate a Vector{Any} to store results from a source of values with unknown
type. Once all of the values are present, I tighten the vector’s type before
returning anything. This has always been somewhat ad hoc in the past, but it’s
something I’d like to do in a cleaner way going forward.
— John
On Jul 27, 2014, at 7:17 PM, Samuel Jenkins <[email protected]> wrote:
> I'd be very interested to know if this exists as well. This issue
> consistently arises when building test fixtures.
> At the moment, I use this as a workaround (this may not apply for your use
> case):
>
> ```julia
> using Base.Test
>
> # Infer tightened element type of array.
> function infer_eltype(ar::Array)
> # Determine element type by reduction loop
> el_type = None
> for el in ar
> el_type = typejoin(el_type, typeof(el))
> end
>
> # If element type cannot be determined, go with collection's element type
> if el_type == None
> el_type = eltype(ar)
> end
>
> # Return inferred element type
> return el_type
> end
>
> # Example use case
> mat = {1.0 2; 3 4.0}
> el_type = infer_eltype(mat)
> tight_mat = convert(Array{el_type}, mat)
> @test eltype(tight_mat) == Real
> @test size(tight_mat) == size(mat)
> @test isequal(tight_mat, mat)
> ```
>
> Hope this helps.
>
> On Monday, July 28, 2014 5:42:24 AM UTC+10, John Myles White wrote:
> Do we have a function that will take in an Array{Any}, compute the typejoin
> of its elements and convert the Array to the tightest possible type?
>
> — John
>