How does AbstractFloat[1.0f0] work?

In the blog post Tutorial on precompilation there is a line cabs = AbstractFloat[1.0f0] . While trying to understand the syntax I found one case in the documentation, in the section Conversion there is a = Any[1 2 3; 4 5 6].

What is this syntax? Does it have anything to do with abstract types?

In this case you are initializing a vector that can contain any type of Floats:

julia> x = AbstractFloat[1.f0]
1-element Array{AbstractFloat,1}:
 1.0f0

julia> push!(x,1.e0)
2-element Array{AbstractFloat,1}:
 1.0f0  # Float32
 1.0    # Float64

If you start a vector with a concrete type signature, like:

julia> y = Float32[1.f0]
1-element Array{Float32,1}:
 1.0

julia> push!(y,1.e0)
2-element Array{Float32,1}:
 1.0
 1.0

julia> typeof(y[1])
Float32

julia> typeof(y[2])
Float32

Only elements of that type will be possible. Depending on what you want the vector to have, you can even get an error:

julia> z = Int[1]
1-element Array{Int64,1}:
 1

julia> push!(z,sqrt(2))
ERROR: InexactError: Int64(1.4142135623730951)

AbstractFloat is an abstract type of which Float32 and Float64 are subtypes:

julia> subtypes(AbstractFloat)
4-element Array{Any,1}:
 BigFloat
 Float16
 Float32
 Float64

so an AbstractFloat[] vector can contain any of those types.

It is not a good a idea to have that kind of mixed type vector, that have performance issues, because each type of number has a different representation in the memory and has to be dispatched differently to the functions that will operate on them.

And Any[] can contain anything:

julia> x = Any[1]
1-element Array{Any,1}:
 1

julia> push!(x,"abc")
2-element Array{Any,1}:
 1
  "abc"


5 Likes

Ok, thank you! Where is this documented?

There is a section in the julia documentation under performance tips named Avoid containers with abstract type parameters, which could be of help. In general, you should avoid using abstract types for arrays.

1 Like

Ok, thank you! This question is not about the performance of abstract types, it is about the syntax in the examples.

The syntax is explained here, under “Typed Array Literals”: Single- and multi-dimensional Arrays · The Julia Language

3 Likes