Member-only story
Creative Applications Of Parametric Typing In Julia
Showing off the many interesting possibilities of Julia’s parametric typing.
In In the long list of compelling features in the Julia language, a cornerstone of its design is often overlooked. Julia’s robust type system, combined with multiple dispatch, redefines abstraction in an entirely novel paradigm. This powerful combination allows developers to define multiple methods for the same function, each tailored to different argument types or combinations, enabling a unique level of flexibility and expressive typing.
# any sub-type of Number. Note the use of <::
function all_values(vec::Vector{<:Number})
sum(vec)
end
# just strings:
function all_values(vec::Vector{String})
join(s, ";")
end
On top of this, Julia features a unique constructor system for these types. Alongside this robust system comes Julia’s parametric typing system. In Julia, a type parameter is a distinction in type that is provided when that type is constructed. This is sometimes provided directly or implicitly provided, depending on the nature of the constructor.
# constructor def/ type name | parameters
mutable struct ParametricType{T <: Integer}
# fields:
n::T
# ^ parameter as field type annotation
# inner constructors:
# to use this…