Hello !
How do you achieve type stability with handwritten structures?
For example, in the following code example, what do I need to return in the second return for the function test to be type stable? It return (true, s1) if a<b and “just” false if not.
struct S1
x::Float64
y::Vector{Float64}
end
function test(a ,b, c)
if a<b
s1 = S1(a, [a,b,c])
return(true, s1)
end
return(false, ???)
Could we define a “neutral element” of structure S1?
Thank you for your insight!
There is not much point in using a separate boolean indicator for success, you can use Union{S1, Nothing} as an optional type.
function test(a ,b, c)::Union{S1, Nothing}
if a<b
s1 = S1(a, [a,b,c])
return s1
end
return nothing
end
As the documentation of InteractiveUtils.code_warntype writes:
Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. In particular, unions containing either missing or nothing are displayed in yellow, since these are often intentional.
Using such optional types is quite common, and Julia handles them quite well, I don’t think you need to worry about them particularly.