Julia’s promote function solves a common arithmetic problem: values with different types need a shared type before an operation can proceed. It returns the values converted to that common type as a tuple. section 9.1
Promoting mixed values
promote(2, 3.5) returns (2.0, 3.5). Julia’s arithmetic functions then splat that tuple into the operation, so +(2, 3.5) behaves like +(promote(2, 3.5)...). Multiple values can be promoted together: integers, rationals, booleans, and unsigned integers become Float64 values when combined with 42.5. section 9.1
Listing 9.1 Definition of arithmetic operations on numbers in Julia’s standard library
+(x::Number, y::Number) = +(promote(x,y)...) *(x::Number, y::Number) = *(promote(x,y)...) -(x::Number, y::Number) = -(promote(x,y)...) /(x::Number, y::Number) = /(promote(x,y)...)
Shows how Julia’s standard arithmetic methods delegate mixed-number handling to promote before performing the operation. section 9.1
Use promotion to keep generic operations manageable as new types are added:
- Define one generic operation for a family of related types instead of writing every pairwise combination. section 9.3.7
- Register custom type relationships with promote_rule, which receives type objects and returns the common type. section 9.3.7
- Implement conversion alongside promotion so values can participate in the shared convert and promote machinery. section 9.3.7
Listing 9.11 Simplifying arithmetic operations by utilizing promotion
+(Θ::Angle, α::Angle) = +(promote(Θ, α)...) -(Θ::Angle, α::Angle) = -(promote(Θ, α)...)
Contrasts pairwise angle-operation methods with a single generic method that promotes both operands first. section 9.3.7
Custom angle types
A promote_rule(::Type{Radian}, ::Type{DMS}) = Radian declaration tells Julia how to reconcile two angle types. Generic addition can then promote both operands, supporting expressions such as 45° + 3.14rad/4 without a separate method for every angle-type pair. section 9.3.7
