Julia Parametric Types
A parametric type is a type name that includes another type inside braces. It states what kind of values a container holds.
Vector{Int} names whole-number arrays
An array of whole numbers has a full type name. The element type is part of that name.
numbers = [1, 2, 3]
println(typeof(numbers))
println(eltype(numbers))One generic function works for many arrays
The letter T stands for any element type. The same function works for numbers and for text.
function firstitem(v::Vector{T}) where {T}
return v[1]
end
println(firstitem([10, 20, 30]))
println(firstitem(["a", "b"]))The element type makes the type different
Whole numbers and decimal numbers give different array types. The check below prints false for equality.
println(typeof([1, 2]))
println(typeof([1.0, 2.0]))
println(typeof([1, 2]) == typeof([1.0, 2.0]))Example
function firstitem(v::Vector{T}) where {T}
return v[1]
end
scores = [7, 9, 4]
words = ["red", "blue"]
println(eltype(scores))
println(firstitem(scores))
println(firstitem(words))Key points
- Vector{Int}: a name for an array whose items are whole numbers.
- Braces: the type inside the braces is the element type.
- eltype: a function that gives the element type of an array.
- Generic function: a function written for a general element type so it works with many arrays.
- Different element types: Vector{Float64} and Vector{Int} are different types.
- typeof: a function that shows the full type of a value.
In this example, firstitem is written once with the general element type T. The call with scores gives 7 because T is the whole number type there. The call with words gives red because T is the text type there.
Note
Julia writes whole numbers as Int64 in full type names on most computers.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does eltype(["a", "b"]) give?