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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
rlipscombe
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used? I’ve got two Github accoun...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews