Julia Type Stability
Type stability is when a function returns the same type of value for the same type of input. It lets Julia plan the work ahead of time.
A stable function returns a plain value
double_it doubles a number. @inferred returns its value when the return type is stable.
using Test
function double_it(x)
return x * 2
end
println(@inferred double_it(3))The same function stays stable for a decimal input
The input type changes, but the return type still follows it. @inferred returns the decimal result.
using Test
function double_it(x)
return x * 2
end
println(@inferred double_it(2.5))An unstable function fails the check
pick returns a number on one path and text on another. The check is caught, and a fixed word is printed.
using Test
function pick(x)
if x > 0
return 1
else
return "no"
end
end
try
println(@inferred pick(-1))
catch
println("unstable")
endExample
using Test
function area_of_square(side)
return side * side
end
function describe(side)
value = @inferred area_of_square(side)
return value
end
println(describe(4))
println(describe(2.5))Key points
- Stable return: a stable function returns one type for a given input type.
- Same input type: the same input type always gives the same return type.
- Check with @inferred: @inferred returns the value when the return type is stable.
- Unstable return: a function that returns a number on one path and text on another is unstable.
- Use one return type to keep a function easy for Julia to plan.
In this example, area_of_square multiplies a side by itself, describe checks that call with @inferred, and the two printed values show a whole result and a decimal result.
Note
@inferred is provided by Test, so the code loads Test before using it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Which function is type-stable?