liveBook · Manning

Angle type

As explained in Julia as a Second Language

An angle type is a numeric type whose values represent angles according to a particular angular unit or representation.

An angle type attaches an angular unit to a numeric value, preventing degrees, radians, and other representations from being treated as interchangeable plain numbers. This matters because mixing units can produce serious software errors; typed units make those mistakes harder to express. section 9.0 section 9.3

A practical Julia design uses an abstract Angle type with concrete Radian and DMS subtypes. Radian stores a Float64 value, while DMS represents degrees, arcminutes, and arcseconds through a seconds value. section 9.3

Listing 9.2 Defining radians and degrees as subtypes of the abstract Angle type
abstract type Angle end

struct Radian <: Angle
   radians::Float64
end

# Degrees, Minutes, Seconds (DMS)
struct DMS <: Angle
   seconds::Int
end

The definition makes the shared Angle abstraction and the distinct Radian and DMS representations immediately visible. section 9.3

A usable angle system grows through a small set of operations:

  • Construct angle values from radians or from degrees, arcminutes, and arcseconds. section 9.3
  • Add and subtract angles without writing a separate method for every pair of units. section 9.3.7
  • Convert between units, expose degree-minute-second components, and display values clearly. section 9.3
  • Extend sin and cos so calculations can accept angle values directly. section 9.3

Promotion keeps mixed-unit arithmetic manageable. Instead of defining every combination such as DMS plus Radian, register a promote_rule that selects a common representation, then define generic Angle arithmetic around promote. Multiple dispatch selects the appropriate rule as new units are added. section 9.3.7

Mixed-unit calculation

With promotion in place, expressions such as 45° + 3.14rad/4 can produce a Radian result, while 45° + 45° can remain displayed as 90° 0' 0''. Trigonometric calls can use the combined values directly. section 9.3.7

How Julia as a Second Language covers it

How deep it goes
Builds concrete angle types, constructors, operations, conversions, display, trigonometry, and promotion rules.
Examples
Demonstrates Radian and DMS values, degree-minute-second accessors, mixed arithmetic, promotion rules, and sin/cos expressions.
What you can do after
Build it from scratch as a Julia unit system with safe mixed-angle arithmetic and reusable conversion behavior.
How it connects
Connects abstract types, multiple dispatch, conversion, promotion, generic arithmetic, and trigonometric functions.

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.