(This is definitely dangerous ground.)
We can override the unary and binary operators in Elixir using macros. To do so, we need to remove any existing definition first.
For example, the operator + (which adds two numbers) is defined in the Kernel module. To remove the Kernel definition and substitute our own, we’d need to do something like the following (which redefines addition to concatenate the string representation of the left and right arguments).
| defmodule Operators do |
| defmacro a + b do |
| quote do |
| to_string(unquote(a)) <> to_string(unquote(b)) |
| end |
| end |
| end |
| |
| defmodule Test do |
| IO.puts(123 + 456) #=> "579" |
| import Kernel, except: [+: 2] |
| import Operators |
| IO.puts(123 + 456) #=> "123456" |
| end |
| |
| IO.puts(123 + 456) #=> "579" |
Note that the macro’s definition is lexically scoped—the + operator is overridden from the point when we import the Operators module through the end of the module that imports it. We could also have done the import inside a single method, and the scoping would be just that method.