binarypaladin

binarypaladin

I’m working on a project right now that makes heavy, heavy use of Decimal. I just hit bug today where >= was used instead of Decimal.compare/2 and it’s not the first time I’ve seen this happen.

Additionally, Decimal has some nice convenience methods (as Java-esque as they are) such as eq?/2 and gt?/2. This is nicer than having to drop into compare/2.

It seems like protocols could totally make operator overloading a thing. I would obviously really like to just be able to do %Decimal{} + %Decimal{} and have it work like Decimal.add/2. And, coming from a Ruby background, I’m, used to overloading a lot.

These are just functions, yes? I can pipe with Kernel.+/2 and Kernel.==/2.

Having said all that, this seems quite deliberate and I feel like with as much as I have read I would have come across the answer but… I don’t know. And either my Googling skills are poor or I’m asking the wrong question.

Why doesn’t Elixir support standard operator overloading?

Showing Posts 1 to 10

sodapopcan

sodapopcan

You could do something like this:

defmodule MyDecimal do
  defmacro __using__(_) do
    quote do
      import Kernel, except: [+: 2, -: 2, ...]

      def left + right do
        Decimal.add(left, right)
      end

      def left - right do
        Decimal.sub(left, right)
      end

      # ...
    end
  end
end

For me, the lack of operator overloading is part of what makes Elixir a good dynamic language as it still cares about types. It’s also part of (all of?) what is enabling the possibility of strong arrows (if we get some static typing). If you looked at a language like OCaml it goes even further. + only adds ints, you need to use +. to add floats! And you must explicitly cast one side if you want to add a float to and int.

I don’t know if this is the exact reason Elixir doesn’t overload, though.

D4no0

D4no0

I think the reason is not to make unreadable code, the example you provided shows clearly how someone can get lost when he will want to use + with non decimal values.

In this case matching or a guard would be a better solution if that is possible, I didn’t work with operators before in elixir so I have no idea about the potential limitations.

binarypaladin

binarypaladin OP

That’s an interesting example. You could contextually overload (almost like a Ruby refinement) in the current module.

With that said, I can see the argument for arithmetic operators. I almost wish I hadn’t included it because what was lost was not that potential convenience.

The pain point isn’t really arithmetic. Decimal.add/2 will chuck an ArithmeticError if you try and just use +. So I might gripe, but I can easily fix.

The real problem comes with equality operators. They won’t chuck an exception. They’ll often just be flat out wrong. (Well, “wrong” in terms of what I intended when comparing structs, because it compares just as it would a map because… it’s a map.) So instead of getting a “you can’t do this” I get something that can fail in subtle ways.

binarypaladin

binarypaladin OP

Awesome. A buddy of mine actually just pointed me to this commit.

It is indeed a conscious decision related to readability:

Note the Elixir community generally discourages custom operators. They can be hard to read and even more to understand, as they don’t have a descriptive name like functions do. That said, some specific cases or custom domain specific languages (DSLs) may justify these practices.

I guess in that case, just like structs don’t work by default with the Access behaviour, it would sure be nice if they blew up on equality operators if they hadn’t implemented compare/2 although I suspect there are issues with that.

D4no0

D4no0

You could replace == operator with a custom one that would make the necessary checks, at compile-time/runtime overhead if that is critical for business.

billylanchantin

billylanchantin

CompareChain might help with some of your use cases (shameless plug: I’m the author). I had similar headaches working with DateTime structs. It’s easier to read code like:

  • left <= right vs
  • DateTime.compare(left, right) != :gt.

CompareChain is a sort of middle ground where you can write this:

import CompareChain

a = Decimal.new(1, 42, 0)
b = Decimal.new(1, 42, -1)
compare?(a >= b, Decimal)

It’s not perfect, but I find that it helps.

binarypaladin

binarypaladin OP

I’ll take a look!

All things date and time also fall under this same pain point.

sodapopcan

sodapopcan

Sorry I’m a bit lost in your wording re: unreadable code but I’m talking more how many languages overload + to work with several data types, like: 1 + 1, "Hello" + "!", and [1, 2, 3] + [4] whereas Elixir has its own operators. But of course:

I always forget about this when thinking/talking about this and ya, that always gets me as I wish there were strict “math” versions. So, ya, it’s best to use guards and pattern matching when working with equality.

Note that is says “generally” :wink: I think if you have a lot of often-edited modules in your business domain that deal purely with decimals, it would be totally fine to write a macro like my example. You can also override per function scope too! Just don’t do it project-wide. There are very good libraries out there that overload these operators, like Image (see the Math module] and Pathex (allows you to use / as a path separator). But if it’s for some simple convenience for a module or two that don’t get changed much, I personally wouldn’t bother. It just makes it confusing later on.

sodapopcan

sodapopcan

This is a really nice middle ground. I like it.

binarypaladin

binarypaladin OP

I come from a Ruby background so… I use and abuse overloading, lol. I’m okay with a decision one way or another. At least it isn’t Java’s “you can’t overload but we selectively have one overload exception for concatenating strings.”

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews