Numbers

hex.pm versionBuild StatusInline docs

Numbers is a tiny Elixir package that facilitates the creation of libraries that want to be able to use any kind of Numberlike type.

Some known custom numeric types that implement Numbers' protocols:

Just add one (or multiple) of these libraries to your project, together with Numbers, and you're good to go!

How does it work?

Starting at version 5, Numbers contains a set of protocols that can be independently implemented for your data structures.

Each protocol maps to a single arithmetical operation that your data structure might support.

Because protocols are used, Numbers can dispatch quite fast! Also, Numbers does not restrict your modules to any special naming schemes (as was the case with older versions of Numbers that used a Behaviour).

The following operations are supported:

Coercion

Numbers does not automatically transform numbers from one type to another if one of the functions is called with two different types.

Frequently you do want to use other data types together with your custom data type. For this, a custom coercion can be specified, using Coerce.defcoercion as exposed by the Coerce library that Numbers depends on.

The only coercion that ships with Numbers itself, is a coercion of Integers to Floats, meaning that they work the same way as when using the standard library math functions with these types.

Examples:

Using built-in numbers:

iex> alias Numbers, as: N

iex> N.add(1, 2)
3

iex> N.mult(3,5)
15

iex> N.mult(1.5, 100)
150.0

Using Decimals: (requires the Decimal library.)

iex> d = Decimal.new(2)
iex> N.div(d, 10)
#Decimal<0.2>
iex> small_number = N.div(d, 1234)
#Decimal<0.001620745542949756888168557536>
iex> N.pow(small_number, 100)

Installation

The package can be installed as:

  1. Add numbers to your list of dependencies in mix.exs:
```elixir
def deps do
  [{:numbers, "~> 5.0.0"}]
end
```

Changelog