Strange outcome for the Julia list with different type of elements

miniskar
Thu, 30 Jan 2025 22:14:05 +0000
New to Julia

Here is the minimum working example.

julia> f= rand(Float32, 8)
8-element Vector{Float32}:
 0.31442094
 0.31442094
 0.2593087
 0.2593087
 0.11091578
 0.11091578
 0.14340413
 0.14340413

julia> i = rand(Int32, 8)
8-element Vector{Int32}:
 -1010112671
   346170778
   668418952
   -50293529
  1151894370
   208560393
 -1186865689
 -1973369622

julia> v_fi = [f, i]
2-element Vector{Vector{Float32}}:
 [0.31442094, 0.31442094, 0.2593087, 0.2593087, 0.11091578, 0.11091578, 0.14340413, 0.14340413]
 [-1.01011264f9, 3.4617078f8, 6.6841894f8, -5.029353f7, 1.1518944f9, 2.085604f8, -1.1868657f9, -1.9733696f9]

julia> any_v_fi = Any[f, i]
2-element Vector{Any}:
 Float32[0.31442094, 0.31442094, 0.2593087, 0.2593087, 0.11091578, 0.11091578, 0.14340413, 0.14340413]
 Int32[-1010112671, 346170778, 668418952, -50293529, 1151894370, 208560393, -1186865689, -1973369622]

julia> scalar_v_fi = [20, f, i]
3-element Vector{Any}:
 20
   Float32[0.31442094, 0.31442094, 0.2593087, 0.2593087, 0.11091578, 0.11091578, 0.14340413, 0.14340413]
   Int32[-1010112671, 346170778, 668418952, -50293529, 1151894370, 208560393, -1186865689, -1973369622]

In the above example, I am expecting Julia to preserve the data type of f and i in the v_fi same like any_v_fi. It should have used “Any” by default to the list for v_fi. Surprisingly, it applies “Any” to scalar_v_fi when there is one scalar element in the list. This behavior is not consistent.

6 posts - 5 participants