Overbryd

Overbryd

Decimal arithmetic - using 'defmacro' gives me ArithmeticError

I am implementing an application that deals with monetary values. Therefore I use the excellent Decimal library to handle such values.

Now arithmetic is supported by the various functions provided by the module, e.g. Decimal.add/2.

But this results in very hard to read and write code, take this for an example:

# I would love to write: distance = price / order_price
# But I have to write:
distance = Decimal.div(price, order_price)

# This gets even more messy when dealing with multiple values
multiplier = 0.2
sale = Decimal.add(price, Decimal.mult(price, Decimal.new(multiplier)))

So, defmacro to the rescue?
Yea, I thought I really have a clean solution with a prefix macro that deals with decimal arithmetic.

Now, in my tests writing this prefix-macro I could do this:

a = Decimal.new(1)
b = Decimal.new(2)
result = decimal a + b
assert result == Decimal.new(3)
# Tests passed, hooray!

But as soon as I used this code in my application, suddenly I got lots of (ArithmeticError) bad argument in arithmetic expression

Why is this happening? Is Elixir inlining the arithmetic expressions and therefore falling back to the Kernel defaults?
I thought I explicitly loaded the Decimal.Prefix macros in the enclosed/0 function.
The weird thing, tests pass just fine, but I don’t get why errors appear when the application runs.
And I double checked the inputs, they are all of Decimal type.

Help in this matter (also the original thing, dealing with monetary values doing arithmetic with these) is highly appreciated.

Kind regards,

Lukas

Marked As Solved

Qqwy

Qqwy

TypeCheck Core Team

There is only one reason to define operators as macros, which is that inside a macro you can find out if it is called as part of a guard clause, or outside of one. So outside of a guard clause you could have fancy logic, while inside a guard clause you could fall back to the built-in operators that work on the built-in data types.

Also Liked

NobbZ

NobbZ

Instead of doing some juggling with the kernel import inside of a single block, you should instead transform the given block by traversing the AST:

defmacro decimal({:+, _, [a, b]}), do: quote do Decimal.add(unquote(a), unquote(b)) end
defmacro decimal({:-, _, [a, b]}), do: quote do Decimal.sub(unquote(a), unquote(b)) end
...

I’m not sure though how well this plays with more complex expressions that have more than a single argument :wink: It might be necessary to deep-traverse the AST to ensure proper transformation.

Besides of that, I think a |> Decimal.add(b) |> Decimal.div(c) reads pretty well. One has to remember that operations are applied left to right this way and one has to sort them.

Qqwy

Qqwy

TypeCheck Core Team

You might like the Numbers library, which allows you to work with any numeric types, as well as automatically converting integer and float arguments to the Decimal type when the other argument is one, which removes the Decimal.new(x) clutter:

alias Numbers, as: N

distance = N.div(price, order_price)
multiplier = 0.2
sale = N.add(price, N.mult(price, multiplier))

Numbers on purpose does not export overloaded operators (but might do so in an explicit opt-in way in the near future).

EDIT: The new version 5.1.0 Has support for exporting overloaded operators as well.

Overbryd

Overbryd

Thank you all for the insightful replies. I learned a lot today.

Last Post!

Qqwy

Qqwy

TypeCheck Core Team

Heh, quite the interesting idea.


Actually, I am currently considering upgrading the Numeric library so that it will (when using the overload_operators: true option) switch between the built-in Kernel functionality and the overloaded functionality depending on if we are in a guard-clause or not.

Maybe providing proper error messages when doing it like that is possible as well… :smiley:

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New

Other popular topics Top

vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42576 114
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New