O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

macros/operators.ex
 
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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required