Qqwy

Qqwy

TypeCheck Core Team

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

Most Liked

Qqwy

Qqwy

TypeCheck Core Team

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):

  • Instead of one Numeric behaviours 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).
  • Using protocols also means that libraries are no longer forced to use the (semi-arbitrarily) function names that Numbers uses for the different operations.
  • Dispatching based on (consolidated!) protocols also means that the library should be a lot more performant. Although I have not done any benchmarks, in the old version of the library there were a lot of extra run-time checks going on that are now unnecessary.
  • A new library called coerce now handles the optional coercion of data types. Previously, coercion was something that was completely handled at runtime. Now, most of it already happens at compile-time, meaning that coercion is probably a lot faster too. coerce also has a lot clearer, more explicit way to define coercions, which I am very happy about as well.
  • No longer ‘ad hoc’ Decimal support. Decimal is now an optional dependency with an explicit version number, and a Decimal-implementation of the protocols is made conditionally using Code.ensure_loaded?, so you’ll only need to add Numbers to 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 for Decimal itself.

I am very eager for feedback! I feel Numbers is getting quite mature now. :grin:

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, Rational and FunLand at the same time to support the new version as well.

Qqwy

Qqwy

TypeCheck Core Team

Version 5.2 has been released which performs better operator overloading:

Calling use Number, overload_operators: true no longer breaks operators that are used in guard clauses.
To clarify:

defmodule An.Example do
  use Numbers, overload_operators: true

  def foo(a, b) when a + b < 10 do  # Uses the normal guard-safe '+' operator (e.g. Kernel.+/2)
    42
  end
  def foo(c, d) do 
    c + d # Uses the overloaded '+' operator.
  end
end
Qqwy

Qqwy

TypeCheck Core Team

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 :stuck_out_tongue_winking_eye: )

OvermindDL1

OvermindDL1

Looks great as always. ^.^

Qqwy

Qqwy

TypeCheck Core Team

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.

Where Next?

Popular in Libraries Top

RobertDober
Earmark is a pure-Elixir Markdown converter. It is intended to be used as a library (just call Earmark.as_html), but can also be used as...
239 11851 134
New
Crowdhailer
Raxx is an alternative to Plug and is inspired by projects such as Rack(Ruby) and Ring(Clojure). 1.0-rc.1 is now available. To use it re...
New
kelvinst
Hey everyone! Well, we made this lib a while ago and now we decided to finally go out and public with it! It’s a tool for creating and m...
New
michalmuskala
Hello everybody. I have just released Jason - a new JSON library. You might be wondering, why do we need a new library? The primary foc...
New
tmbb
I’ve published the first version of my Makeup library. It’s a syntax highlighter for Elixir in the spirit of Pygments, Currently it highl...
New
woylie
Flop is an Elixir library that applies filtering, ordering and pagination parameters to your Ecto queries. offset-based pagination with...
New
zorbash
I created Kitto a framework for dashboards inspired by Dashing. [demo] The distributed characteristics of Elixir and the low memory foo...
New
vic
Expat is a tiny experiment I did for extracting patterns and being able to reuse them (compose and share patterns between elixir librarie...
New
maltoe
Hello! Came here to announce ChromicPDF, a pet project PDF generator I’ve been working on for the past few months. Why another PDF gener...
New
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Sub Categories:

We're in Beta

About us Mission Statement