Julia Matrix{AbstractFloat} type question

Viewed 78

Context

In Julia: what does the "<:" symbol mean?, the 2nd answer directly quoted the three Julia's documentation for the <: operator. The 3rd one puzzles me.

Problem

To make this question independent from the quoted question, I'll make a particular example.

julia> 1.3 isa AbstractFloat
true
julia> [1.3 1.3; 1.2 1.2] isa Matrix{Float64}
true
julia> [1.3 1.3; 1.2 1.2] isa Matrix{AbstractFloat}
false

From Julia's documentation, AbstractFloat is an abstract type for all floating values, e.g. Float32, Float64, etc. That's explains the first example. However, I can't understand why a matrix of Float64 isn't a matrix of AbstractFloat.

1 Answers

You have to do:

julia> [1.3 1.3; 1.2 1.2] isa Matrix{<:AbstractFloat}
true

as type parameters in Julia are invariant.

This is explained in detail here.

If the linked explanation is not clear please comment where you need additional info and I can expand on the problematic areas.

EDIT

An explanation from a different angle (maybe it will be also helpful).

  1. As is explained here in Julia:

One particularly distinctive feature of Julia's type system is that concrete types may not subtype each other: all concrete types are final and may only have abstract types as their supertypes. While this might at first seem unduly restrictive, it has many beneficial consequences with surprisingly few drawbacks.

The reason for this is that concrete types have a concrete memory layout, and in particular Matrix{Float64} and Matrix{AbstactFloat} have a different memory layout. Knowing memory layout of an object is crucial if we want the compiler to emit efficient machine code.

  1. Now both Matrix{AbstractFloat} and Matrix{Float64} are concrete types (they can have instances):
julia> Matrix{AbstractFloat}(undef,0,0)
0×0 Matrix{AbstractFloat}

julia> Matrix{Float64}(undef,0,0)
0×0 Matrix{Float64}

julia> isconcretetype(Matrix{AbstractFloat})
true

julia> isconcretetype(Matrix{Float64})
true
  1. In consequence Matrix{Float64} cannot be a subtype of Matrix{AbstractFloat} (nor vice versa)
Related