Skip to content

Instantly share code, notes, and snippets.

@alisinabh
Last active December 16, 2016 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alisinabh/9a6b7adcf3ee1097750c2afe32ea76b3 to your computer and use it in GitHub Desktop.
Save alisinabh/9a6b7adcf3ee1097750c2afe32ea76b3 to your computer and use it in GitHub Desktop.
Creating a macro with elixir to vice versa nested math operations
defmodule OppositeMath do
@moduledoc """
This module helps with oppositting nested math formuals like 2 + 5 * 4 + 6 => 2 - 5 / 4 - 6 for sake of learning elixir macros
"""
@doc """
This macro opposites all math symbols in a formula
## Examples
iex> OppositeMath.opposite 1+1
0
iex> OppositeMath.opposite 2 * 2 + 5
-4.0
"""
defmacro opposite(operation) do
build_opposite(operation)
end
###
# Macro Helpers
###
defp build_opposite({op, kern, [a, b]}) do
case op do
:+ -> {:-, kern, [build_opposite(a), build_opposite(b)]}
:- -> {:+, kern, [build_opposite(a), build_opposite(b)]}
:* -> {:/, kern, [build_opposite(a), build_opposite(b)]}
:/ -> {:*, kern, [build_opposite(a), build_opposite(b)]}
end
end
defp build_opposite(arg), do: arg
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment