Created
January 8, 2017 15:37
-
-
Save scottmascio2115/d360a9f645f91b478bc0e1ab08ca7a78 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Creation of an opposite macro | |
We want opposite 1 + 1 | |
to return to 0 or essentially run 1 - 1 | |
opposite 1 + 1 | |
Transforms 1 + 1 into an AST | |
opposite({:+, [], [1,1]} | |
Our macro would then transform that AST (Abstract syntax tree) | |
The macro accepts an AST as an agruement | |
defmacro opposite({:+, context, [a, b]}) do | |
{:- , context, [a, b]} | |
end | |
We can use the quote operator to generate the final AST: | |
defmodule Math.Opposite do | |
defmacro opposite({:+, _, [a, b]}) do | |
quote do | |
unquote(a) - unquote(b) | |
end | |
end | |
end | |
Think of unquote as string interpolation for macros | |
Usage | |
import Math.Opposite | |
opposite 1 + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment