4 ms·
Julia is dynamic. I've described this before, but the type annotations are used for multiple dispatch, not for static type checking. The quick example of why t
by JHonaker 6y ago
Julia is dynamic. I've described this before, but the type annotations are used for multiple dispatch, not for static type checking.
The quick example of why this is powerful is multiplication:
# Assume you only have addition defined
# Quick and dirty baseline
function *(l::T, r::T) where {T<:Int}
out = 0
while l > 0
out += r
l -= 1
end
out
end
# Great, now let's say you have a data type, rational numbers:
struct Rational{T<:Int}
numerator::T
denominator::T
end
# And you want to define multiplication on rational numbers
*(l::Rational, r::Rational) = Rational(l.numerator * l.numerator, l.denominator * l.denominator)
# Cool, but multiplying Ints by rational number should also be defined
*(l::Rational, r::Int) = Rational(l.numerator * r, l.denominator)
*(l::Int, r::Rational) = *(r, l)
The reason this is so cool, and why, yes it's still dynamic,
is that I can call x * y on two variables, x and y, of which I know nothing about. The most specific method defined which matches their type will be called to handle it. If there isn't one defined, that's obviously a method error just like in your favorite other language!