Macros and Operators
Learn how to override operators using macros.
We'll cover the following
We can override the unary and binary operators in Elixir using macros. To do so, we need to remove any existing definition first.
Overriding operators example
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 code 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.
Run the c "operators.ex"
command to execute the code below:
Get hands-on with 1400+ tech skills courses.