Skip to content

Instantly share code, notes, and snippets.

@scottmascio2115
Created January 8, 2017 15:37
Show Gist options
  • Save scottmascio2115/d360a9f645f91b478bc0e1ab08ca7a78 to your computer and use it in GitHub Desktop.
Save scottmascio2115/d360a9f645f91b478bc0e1ab08ca7a78 to your computer and use it in GitHub Desktop.
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