Macros and Operators

(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 ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.