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.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement