Converts parsed unit ASTs into their CLDR base unit equivalents.
Each unit in CLDR maps to a base unit string expressed in terms of fundamental units (meter, kilogram, second, ampere, kelvin, candela, revolution, item, part, bit, pixel, em, year, night). This module decomposes any parsed unit AST into those fundamentals and reconstructs the canonical base unit string.
Powers are fully simplified across the expression. For example,
liter-per-kilometer (volume/length) simplifies to square-meter
and kilowatt-hour (power × time) simplifies to
kilogram-square-meter-per-square-second (energy).
Summary
Functions
Returns the base unit string for a parsed unit AST or a unit identifier string.
Returns the base unit string for a parsed unit AST or a unit identifier string, raising on error.
Decomposes a parsed unit AST into a map of fundamental unit powers.
Reconstructs a canonical base unit string from a powers map.
Functions
@spec base_unit(String.t() | tuple()) :: {:ok, String.t()} | {:error, Exception.t() | String.t()}
Returns the base unit string for a parsed unit AST or a unit identifier string.
Arguments
inputis either a parsed unit AST tuple or a unit identifier string.
Returns
{:ok, base_unit_string}wherebase_unit_stringis the canonical CLDR base unit identifier, or{:error, reason}if the unit cannot be resolved.
Examples
iex> Localize.Unit.BaseUnit.base_unit("foot")
{:ok, "meter"}
iex> Localize.Unit.BaseUnit.base_unit("newton")
{:ok, "kilogram-meter-per-square-second"}
iex> Localize.Unit.BaseUnit.base_unit("mile-per-hour")
{:ok, "meter-per-second"}
Returns the base unit string for a parsed unit AST or a unit identifier string, raising on error.
Same as base_unit/1 but returns the string directly or raises
ArgumentError.
Arguments
inputis either a parsed unit AST tuple or a unit identifier string.
Returns
- A canonical CLDR base unit string.
Examples
iex> Localize.Unit.BaseUnit.base_unit!("foot")
"meter"
Decomposes a parsed unit AST into a map of fundamental unit powers.
Positive powers represent numerator units and negative powers represent denominator units. Powers are fully simplified across the expression.
Arguments
astis a parsed unit AST tuple.
Returns
{:ok, powers}wherepowersis a map like%{"meter" => 1, "second" => -2}, or{:error, reason}if the unit cannot be resolved.
Examples
iex> {:ok, ast} = Localize.Unit.Parser.parse("newton")
iex> Localize.Unit.BaseUnit.decompose(ast)
{:ok, %{"kilogram" => 1, "meter" => 1, "second" => -2}}
Reconstructs a canonical base unit string from a powers map.
Arguments
powersis a map of fundamental unit name to integer power where positive values are in the numerator and negative in the denominator.
Returns
- A canonical CLDR base unit string.
Examples
iex> Localize.Unit.BaseUnit.recompose(%{"kilogram" => 1, "meter" => 1, "second" => -2})
"kilogram-meter-per-square-second"