Parametric types in Julia
The T in braces is chosen per use and bounded by <:.
# The T in curly braces is decided per use; constraints bound it.
struct Reading{T<:Real}
label::String
value::T
end
seeing = Reading("seeing", 2.3)
frames = Reading("frames", 48)
println(typeof(seeing))
println(typeof(frames))
# Parametric functions dispatch on the element type.
midpoint(xs::Vector{T}) where {T<:Real} = (first(xs) + last(xs)) / 2
println(midpoint([10.0, 14.0, 22.0]))
println(midpoint([3, 9]))
How it works
Reading{T<:Real}stamps a concrete type per value.typeofshowsReading{Float64}andReading{Int64}.where {T<:Real}writes the same idea on a function.
Keywords and builtins used here
ReadingRealStringTVectorendstructwhere
The run, in numbers
- Lines
- 15
- Characters to type
- 415
- Tokens
- 103
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 103 seconds.
Step 3 of 3 in Types, step 18 of 27 in Language basics.