Unit.Operators (Hyper v0.1.0)

Copy Markdown View Source

Operator overloading for Unit.Quantity types.

use Unit.Operators in a module to get unit-aware +, -, <, >, <=, and >=. Operands that are not unit quantities fall straight through to Kernel, so the rest of the module's integer arithmetic and comparisons are untouched. Equality (==) is left as Elixir's native struct equality, which already does the right thing for these single-field structs.

defmodule Scheduler do
  use Unit.Operators

  def headroom(total, used), do: total - used         # Information - Information
  def fits?(avail, need), do: need <= avail           # Information <= Information
  def retries(n), do: n + 1                           # plain integers, via Kernel
end

Combining two different dimensions (Information + Time), or a quantity with a bare number, raises ArgumentError -- the whole point of the unit types is that those mistakes do not silently compute.

Summary

Functions

Sum of two quantities of the same dimension (or Kernel.+/2 for non-units).

Difference of two quantities of the same dimension (or Kernel.-/2 for non-units).

Whether left is less than right (or Kernel.</2 for non-units).

Whether left is at most right (or Kernel.<=/2 for non-units).

Whether left is greater than right (or Kernel.>/2 for non-units).

Whether left is at least right (or Kernel.>=/2 for non-units).

Functions

left + right

Sum of two quantities of the same dimension (or Kernel.+/2 for non-units).

left - right

Difference of two quantities of the same dimension (or Kernel.-/2 for non-units).

left < right

Whether left is less than right (or Kernel.</2 for non-units).

left <= right

Whether left is at most right (or Kernel.<=/2 for non-units).

left > right

Whether left is greater than right (or Kernel.>/2 for non-units).

left >= right

Whether left is at least right (or Kernel.>=/2 for non-units).