liveBook · Manning

Promote_rule

As explained in Julia as a Second Language

promote_rule is a Julia function whose methods specify the common type to which two types are promoted.

When several angle units should work in one expression, writing a separate operator for every type pair quickly becomes unmanageable. promote_rule provides the shared promotion decision that lets generic arithmetic handle those combinations. section 9.3.7

promote_rule takes two type objects and returns the type to which both values should be promoted. Its methods use multiple dispatch to select a rule based on the supplied types, rather than inspecting individual values. section 9.3.7

Promoting radians and DMS angles

Register the function from Base, then declare that Radian is the common type for Radian and DMS: import Base: promote_rule; promote_rule(::Type{Radian}, ::Type{DMS}) = Radian. A generic method can then delegate addition and subtraction to promote(Θ, α), allowing expressions such as 45° + 3.14rad/4. section 9.3.7

A custom promotion design follows this pattern:

  • Choose the common result type for each supported pair of types. section 9.3.7
  • Define promote_rule methods whose arguments are type objects. section 9.3.7
  • Use generic operations that call promote instead of multiplying pairwise operator methods. section 9.3.7
Listing 9.12 Defining type promotion of Radian and DMS
import Base: promote_rule

promote_rule(::Type{Radian}, ::Type{DMS}) = Radian

Inspect the compact Julia definition that registers Radian as the promotion target for DMS and Radian values. section 9.3.7

How Julia as a Second Language covers it

How deep it goes
Explains type-object dispatch and generic arithmetic, stopping short of a broader implementation theory.
Examples
Uses Radian and DMS values, mixed-angle arithmetic, REPL promotion queries, and generic addition and subtraction.
What you can do after
Build interoperable custom types by defining promote_rule methods and routing generic operations through promote.
How it connects
Connects type promotion with convert, multiple dispatch, generic arithmetic, and custom numeric types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.