Julia Parametric Types
A parametric type takes other types as parameters, written in curly braces. You've already used several: Vector{Int64}, Dict{String, Float64}, Complex{Int64}. Defining your own lets one type definition work for many element types while staying fast.
A parametric struct
struct Pair2D{T}
x::T
y::T
end
a = Pair2D(1, 2)
b = Pair2D(1.5, 2.5)
c = Pair2D("left", "right")
println(typeof(a), " ", typeof(b), " ", typeof(c))
println(a.x + a.y, " ", b.x + b.y)
d = Pair2D{Float64}(1, 2) # explicit parameter: arguments are converted
println(d)
try
Pair2D(1, 2.5) # T can't be both Int64 and Float64
catch e
println(typeof(e))
endPair2D{Int64} Pair2D{Float64} Pair2D{String}
3 4.0
Pair2D{Float64}(1.0, 2.0)
MethodError
T is a type parameter. When you call Pair2D(1, 2), Julia infers T = Int64 from the arguments. Each concrete instance, like Pair2D{Int64}, has fully concrete fields, so code using it is as fast as if you had written a separate IntPair type by hand.
Restricting parameters
{T <: Real} limits which types may be used:
struct Interval{T <: Real}
lo::T
hi::T
end
width(i::Interval) = i.hi - i.lo
contains_value(i::Interval, x) = i.lo <= x <= i.hi
r = Interval(2, 9)
println(width(r), " ", contains_value(r, 5))
println(width(Interval(0.5, 0.75)))
try
Interval("a", "z")
catch e
println(typeof(e))
end7 true
0.25
MethodError
Several parameters
struct Measurement{V <: Number, U}
value::V
unit::U
end
m1 = Measurement(9.81, "m/s^2")
m2 = Measurement(3, :kg)
println(typeof(m1))
println(typeof(m2))
println(m2.value, " ", m2.unit)Measurement{Float64, String}
Measurement{Int64, Symbol}
3 kg
Methods with type parameters
Functions can have type parameters too, using where. This lets a method refer to "the element type of the argument" or require that two arguments share a type:
first_and_type(v::Vector{T}) where {T} = "first element $(v[1]) of type $T"
println(first_and_type([1, 2]))
println(first_and_type(["a"]))
same_type(a::T, b::T) where {T} = "both are $T"
same_type(a, b) = "different types"
println(same_type(1, 2))
println(same_type(1, 2.0))
total(v::AbstractVector{<:Real}) = sum(v)
println(total([1, 2, 3]), " ", total([0.5, 0.25]))first element 1 of type Int64
first element a of type String
both are Int64
different types
6 0.75
AbstractVector{<:Real} is shorthand for AbstractVector{T} where T <: Real: any vector whose element type is some kind of real number.
Parametric types are invariant
An important subtlety: even though Int64 <: Real, a Vector{Int64} is not a subtype of Vector{Real}. Type parameters are invariant. Use Vector{<:Real} to mean "a vector of some real type":
println(Int64 <: Real)
println(Vector{Int64} <: Vector{Real})
println(Vector{Int64} <: Vector{<:Real})
mean_bad(v::Vector{Real}) = sum(v) / length(v)
mean_good(v::Vector{<:Real}) = sum(v) / length(v)
println(mean_good([1, 2, 3, 4]))
try
mean_bad([1, 2, 3, 4])
catch e
println(typeof(e))
endtrue
false
true
2.5
MethodError
The reason is memory layout: a Vector{Int64} stores raw 64-bit integers next to each other, while a Vector{Real} stores pointers to boxed values of possibly different types. They really are different things.
Abstract parametric types
Abstract types can be parametric too. Base defines AbstractArray{T, N} (element type T, N dimensions); Vector{T} is just an alias for Array{T, 1}:
println(Vector{Int} == Array{Int, 1})
println(Matrix{Float64} == Array{Float64, 2})
println(ndims(zeros(2, 3, 4)), " ", eltype(zeros(Float32, 2)))
println(Array{Int, 2} <: AbstractMatrix{Int})true
true
3 Float32
true
Test yourself
Given struct Box{T} v::T end, what is typeof(Box(2.0))?
- Box
- Box{Float64}
- Box{Real}
- Box{T}
Is Vector{Int64} <: Vector{Real}?
- Yes, because Int64 <: Real
- No, type parameters are invariant
- Only on 64-bit systems
- It is an error to ask
What does f(a::T, b::T) where {T} = ... require?
- a and b are numbers
- a and b have the same type
- a and b are vectors
- Nothing