Few questions on usage of (convert) and (promote) in dual.jl

I’m looking at conversion-and-promotion documentation and also dual.jl implementation and need help the following lines. (I apologize that I’m asking several questions in the same topic).

Unclear, why we need the following conversion. Not clear what else could it be and then why we need it:

Base.convert(::Type{Dual{T}}, z::Dual{T}) where {T<:ReComp} = z

Following is also not clear. I thought that Dual by itself is not a type, so why is this not something like Dual{S} (or is there difference between Dual and Dual{S})?

Base.convert(::Type{Dual{T}}, z::Dual) where {T<:ReComp} = Dual{T}(convert(T, value(z)), convert(T, epsilon(z)))

So we define promote_rules for for a Number to become Dual, but why then we define addition between Number and Dual. Is this for better performance?

Base.:+(z::Dual, w::Dual) = Dual(value(z)+value(w), epsilon(z)+epsilon(w))
Base.:+(z::Number, w::Dual) = Dual(z+value(w), epsilon(w))
Base.:+(z::Dual, w::Number) = Dual(value(z)+w, epsilon(z))

Thank you very much in advance for helping.

I think it is a fallback for the no-op, otherwise the other methods would kick in.

It is a UnionAll type, see

https://docs.julialang.org/en/v1.7-dev/manual/types/#UnionAll-Types

2 Likes