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.

Revisions

  1. scottmascio2115 created this gist Jan 8, 2017.
    34 changes: 34 additions & 0 deletions opposite.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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