In Elixir, operators are also simply functions. A unary operator takes a single argument, a binary infix operator takes two.
It is therefore possible to define our own. However, the compiler determines which strings of characters are allowed as operators, so there is only a small set of possibilities.
Most of these are already defined in one way or another in Elixir’s standard library. In the end, the only operators that can be used without overriding an operator either in Kernel
, Kernel.SpecialForms
or Bitwise
are:
\\
(which is also used to specify a ‘default’ argument in function clauses),
<-
(which is also used inside for-comprehensions)
|
(which is also used to construct/pattern match lists)
and
~>
, <~
, ~>>
, <<~
, <~>
, <|>
.
So: When you want to unequivocally define an operator in Elixir, you’re restricted to this set of squiggely arrows.
I personally think that this list is rather small. I totally agree that Haskell’s approach of letting you define any combination of non-alphanumeric symbols means that it is impossible for an outsider to comprehend the code, as operators are very implicit (you cannot find out what they do just by reading them).
On the other hand, operators ensure that code is very concise, and some types of operations are easier to read/write when written in an infix style, rather than a prefix one.
Elixir’s currently only allows a very small number of user-definable operators, I find this list to be rather short. Multiple times now, I’ve wanted to implement an operator for my library, and I was unable to find a good one.
On a related note, when two libraries both want to add an operator, and they end up using the same one, you cannot use those libraries in your module at the same time (unless you call one of the operators remotely).
So: What operators would you like to see being added (as free, user-definable operators) to Elixir?