Qqwy
Numbers: A generic wrapper to use *any* custom Numeric type!
Hey, everyone!
Today I started writing a small library to perform computations with Complex Numbers. (ComplexNum, it is still very much unfinished). While working on that, I realized that I did not only wanted to be able to specify the real and imaginary parts as Integers or Floats, but also Decimals, Rationals or other numeric data types.
This made me realize that it was possible to create a more general ‘dispatching’ module, as long as each of the numeric data types followed the same API (i.e. the same Behaviour):
And thus Numbers was born.
What does it do?
It allows you to call Numbers.add, Numbers.sub, Numbers.mult, etc. regardless of what data types you are performing arithmetic with. As long as they are the same type (or one of them is a built-in data type such as an integer or float, in which case they will be attempted to automatically be converted to the custom data type), it will Just Work™.
Some Examples:
iex> alias Numbers, as: N
iex> N.add(1, 2)
3
iex> N.mul(3,5)
15
iex> N.mul(1.5, 100)
150.0
Using Decimals: (requires the Decimal package)
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)
Using Rationals: (requires the Ratio package)
iex> use Ratio, operators: false
iex> res = N.add(1 <|> 2, 3 <|> 5)
11 <|> 10
iex> N.mult(res, 10)
How does it work?
Simply put, the Numbers module accepts for most functions two arguments that should be of the same struct type (optionally, one of them could be an integer or float which is automatically converted by Numbers to the struct of the other argument). It will extract the module name of the struct, and call the functions named add, sub, etc. on that module.
So Numeric is a Behaviour, to follow. Numbers dispatches that behaviour, which means that you can build functions and data types that wrap any kind of number, including custom-built ones.
Some libraries that now use Number in practice, meaning that they can contain any kind of number and be able to perform mathematical operations on their contents, are Tensor and ComplexNum.
What data types are supported right now?
Right now, I know of the following data types that follow the behaviour:
- built-in Integers
- built-in Floats
- Ratio for rational numbers.
- Decimal for decimal numbers. (Does not yet formally implement the Numeric behaviour using
@behaviour, I’ll create a Pull Request on its repository adding just that shortly. In the meantime, as it already informally follows the behaviour, it already simply works!).
One of the things I like the most, is that the following structures both dispatch using Numbers internally as well as implement the Numeric Behaviour, meaning that they can be used as composite Numeric types, when the type they contain follow the Numeric Behaviour. (So you can do elementwise addition of multiple Vectors of Decimals, or even a Matrix filled with Vectors of Complex numbers of Floats). The possibilities are endless!
- ComplexNum for complex numbers. (as long as the data type used for the real/imaginary parts itself follows Numeric.
- Tensor for Vectors, Matrices and higher-order Tensors.
Tl;Dr: Numbers is a wrapper exposing the generic functionality all kinds of (custom or built-in) numeric datatypes have. So you can use it to make your code number-agnostic!
I look forward to any and all feedback from you!
Thanks,
~Wiebe-Marten/Qqwy
Trending in Announcing
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #elixirconf-us
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 10 of 11 Posts!
Qqwy
Note that I have published ComplexNum now as well, as its basic API is now finished and stable. (Although there might be some functionality missing, I don’t know
)
Qqwy
I have added some more documentation to the library, as well as some better error handling when conversions happen.
I am of course eager to hear any feedback, especially on the way
Numberswraps other modules, and on the error handling it performs.dom
I am curious why it uses a behaviour. Wouldn’t this be a natural use case for protocols?
Qqwy
There are two reasons for using a behaviour:
Protocolname.Structname.methodnamebecause this is how protocols are defined underwater in Elixir right now, but as this might change in future versions, this is not a proper strategy.Numbersas direct dependency, or having many more auxillary packages that include the different protocols.I am not sure if my reasoning is sound, but this is why Numeric is a Behaviour instead of a Protocol.
OvermindDL1
Looks great as always. ^.^
Qqwy
Hey guys! I am back from vacation, during which I had some great new ideas.
Numbers has been completely overhauled!
A release candidate for version five (
v5.0.0-rc0) is now available on Hex. Please give it a whirl and let me know if you find any rough edges.This is a major version release because the internal structure is completely changed (and some old exceptions that used to be thrown at certain times no longer exist):
Numericbehaviours as previously, a whole set of Protocols is now used, so types are no longer required to implement all of the operations if only some of them make sense for a certain numeric type (and when you get into more niche mathematical realms like the realm of elliptic curves for instance, these things do happen very frequently).coercealso has a lot clearer, more explicit way to define coercions, which I am very happy about as well.Code.ensure_loaded?, so you’ll only need to addNumbersto e.g. your Phoenix project to get started. Since Numbers will automatically coerce integers and floats to decimals if the other number in an operation is a decimal, this might really increase the readability of your mathematical algorithms. Thanks to @ericmj for telling me about optional dependencies, and also forDecimalitself.I am very eager for feedback! I feel Numbers is getting quite mature now.
A full-fledged version will be released as soon as I’m convinced there are no glaring oversights anymore, and I’ll update
ComplexNum,Tensor,RationalandFunLandat the same time to support the new version as well.Qqwy
All right!
The full version has been released, and we’re now at 5.1.0, because optional, explicit opt-in support has been added for overloaded arithmetical operators.
Tensor, ComplexNum and Ratio have been updated to work with the new version as well.
OvermindDL1
I’ve not really benchmarked elixir protocols to my protocol_ex implementation, but I whipped up a quick mini-Numbers protocol with
add/2andmult/2and implemented it for integers, floats, Decimal, and MyDecimal (a Decimal-like thing I whipped up that duplicates Decimal’s functionality for add/mult but uses tagged tuples instead of maps, because screw maps for math-heavy code, and yes it includes the huge amount of:infand so forth checks that the Decimal library does, to use as an accurate comparison, it’s internal format is{MyDecimal, s, c, e}), just for testing the comparison between elixir protocols and a more powerful protocol (not necessarily better, the more constrained elixir protocols may be easier for beginners, but they have a cost):That is of course with Benchee complaining that everything is way too fast to test accurately so the numbers themselves are not really accurate, however the comparisons should be accurate (the
#.##% slowerparts).OvermindDL1
The earlier one was not ‘coercing’ either like Numbers was, here are some benches with and without coerce’ing, mine uses my own version of coerce using a single tuple protocol dispatch instead of nested protocols as Numbers uses.
OvermindDL1
Also what on earth is going on with the syntax highlighting on this forum? o.O

Last Post!
Qqwy
Version 5.2 has been released which performs better operator overloading:
Calling
use Number, overload_operators: trueno longer breaks operators that are used in guard clauses.To clarify: