binarypaladin

binarypaladin OP

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?

First 10 of 20 Posts Switch mode

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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New

We're in Beta

About us Mission Statement