Search documentation of Localize

# Localize.Unit.Canonical (Localize v0.39.0)

Copy Markdown View Source

Canonicalises CLDR unit identifier ASTs and names.

Provides functions to sort unit components into CLDR canonical order (as defined by the `unitQuantity` simple base unit ordering in the supplemental units data), consolidate repeated terms, cross-cancel matching terms between numerator and denominator, and format the result as a canonical unit identifier string.

## Summary

### Functions

canonicalize(arg)

Returns the canonical name and normalised AST for a parsed unit.

from_components(numerator, denominator)

Builds a canonical name and normalised AST from raw numerator and denominator component lists.

## Functions

# canonicalize(arg)

    @spec canonicalize({:unit, keyword()} | {:mixed_unit, term()}) ::
      {String.t(), {:unit, keyword()} | {:mixed_unit, term()}}

Returns the canonical name and normalised AST for a parsed unit.

The AST is normalised by sorting numerator and denominator components into CLDR canonical order.

### Arguments

- `parsed` is a `{:unit, keyword}` AST as returned by the parser.

### Returns

- `{canonical_name, normalised_ast}` where `canonical_name` is a string and `normalised_ast` has canonically ordered components.

# from_components(numerator, denominator)

    @spec from_components(list(), list()) :: {:dimensionless, nil} | {String.t(), tuple()}

Builds a canonical name and normalised AST from raw numerator and denominator component lists.

Applies consolidation of duplicate terms, cross-cancellation of matching terms, and canonical sorting before formatting.

### Arguments

- `numerator` is a list of single_unit or constant AST tuples.

- `denominator` is a list of single_unit or constant AST tuples.

### Returns

- `{canonical_name, normalised_ast}` or `{:dimensionless, nil}` when all units cancel.