Localize.Unit.Operators (Localize v0.9.0)

Copy Markdown View Source

Overloaded arithmetic operators for Localize.Unit.t() values.

When use Localize.Unit.Operators is added to a module, the +, -, *, and / operators are overridden so that they dispatch to Localize.Unit.Math when one or both operands is a %Localize.Unit{} struct. For all other types, the standard Elixir/Erlang operators are used.

The operators raise on error (they use the bang convention internally) so they can be used in natural arithmetic expressions.

Usage

defmodule MyApp.Physics do
  use Localize.Unit.Operators

  def kinetic_energy(mass, velocity) do
    # mass and velocity are Localize.Unit structs
    half = Localize.Unit.Math.mult(mass, 0.5) |> elem(1)
    half * velocity * velocity
  end
end

Supported operations

ExpressionDelegates toNotes
unit + unitLocalize.Unit.Math.add/2Units must be convertible.
unit - unitLocalize.Unit.Math.sub/2Units must be convertible.
unit * numberLocalize.Unit.Math.mult/2Scalar multiplication.
number * unitLocalize.Unit.Math.mult/2Commutative.
unit * unitLocalize.Unit.Math.mult/2Produces compound unit.
unit / numberLocalize.Unit.Math.div/2Scalar division.
unit / unitLocalize.Unit.Math.div/2Produces compound unit.
any other typesKernel.+/2, Kernel.-/2, Kernel.*/2, Kernel.//2Standard Elixir.

Scope

The operator overrides apply only within the module that calls use Localize.Unit.Operators. They do not affect other modules or global operator behaviour.

Summary

Functions

Multiplies two values. When either operand is a %Localize.Unit{} struct, delegates to Localize.Unit.Math.mult/2. Otherwise falls through to Kernel.*/2.

Adds two values. When both are %Localize.Unit{} structs, delegates to Localize.Unit.Math.add/2. Otherwise falls through to Kernel.+/2.

Subtracts two values. When both are %Localize.Unit{} structs, delegates to Localize.Unit.Math.sub/2. Otherwise falls through to Kernel.-/2.

Divides two values. When the left operand is a %Localize.Unit{} struct, delegates to Localize.Unit.Math.div/2. Otherwise falls through to Kernel.//2.

Functions

left * right

Multiplies two values. When either operand is a %Localize.Unit{} struct, delegates to Localize.Unit.Math.mult/2. Otherwise falls through to Kernel.*/2.

left + right

Adds two values. When both are %Localize.Unit{} structs, delegates to Localize.Unit.Math.add/2. Otherwise falls through to Kernel.+/2.

left - right

Subtracts two values. When both are %Localize.Unit{} structs, delegates to Localize.Unit.Math.sub/2. Otherwise falls through to Kernel.-/2.

left / right

Divides two values. When the left operand is a %Localize.Unit{} struct, delegates to Localize.Unit.Math.div/2. Otherwise falls through to Kernel.//2.