numbers v4.0.0 Numbers.Numeric behaviour

Any module that wants to be a Numeric type, and to be able to be called by the functions in Number, should make sure that this behaviour is followed.

Your callbacks will only ever be called with two versions of your Numeric struct. If one of the functions in Number is called with one of the arguments being an integer or float, then it is first converted to your Numeric struct by calling YourStructModule.new(the_int_or_float) on it.

Summary

Types

numeric_struct should be a struct that follows the Numeric behaviour

t()

To be used in your typespecs at any place where a Numeric type can be used

Callbacks

The absolute value of a number

Adds two numbers together

Divides the rhs by the lhs

Unary minus. Should return the negation of the number

Multiplies the two numbers together

Creates a new numeric_struct from the given built-in integer or float

Power function, x^n

Subtracts the rhs number from the lhs number

Convert the custom Numeric struct to the built-in float datatype

Types

numeric_struct()
numeric_struct() :: struct

numeric_struct should be a struct that follows the Numeric behaviour.

t()
t() :: number | numeric_struct

To be used in your typespecs at any place where a Numeric type can be used.

Callbacks

abs(numeric_struct)

The absolute value of a number.

add(numeric_struct, numeric_struct)

Adds two numbers together.

coerce(t, numeric_struct) (optional)
div(numeric_struct, numeric_struct)

Divides the rhs by the lhs.

To be clear, this division operation is supposed to keep precision.

minus(numeric_struct)

Unary minus. Should return the negation of the number.

mult(numeric_struct, numeric_struct)

Multiplies the two numbers together.

new(any) (optional)
new(any) :: numeric_struct

Creates a new numeric_struct from the given built-in integer or float.

In the case of reading a float, it is okay to lose precision.

This callback is optional, because there are data types for which this conversion is impossible or ambiguous.

If more control is needed over the creation of a datatype from a built-in type, or coercion between two custom data types, implement coerce/2 instead.

pow(numeric_struct, integer) (optional)
pow(numeric_struct, integer) :: numeric_struct

Power function, x^n.

When this optional function is not provided, Number will use the ‘Exponentiation by Squaring’ algorithm to calculate the result (which uses log(n) repeated multiplications).

Add it to your data type if it is possible to compute a power using a faster algorithm.

sub(numeric_struct, numeric_struct)

Subtracts the rhs number from the lhs number.

to_float(numeric_struct) (optional)
to_float(numeric_struct) :: float

Convert the custom Numeric struct to the built-in float datatype.

It is okay to lose precision during this conversion.

This function is optional, because there are many numeric types that cannot be (unambiguously) converted into a floating-point number.