Last active
December 16, 2016 00:07
-
-
Save alisinabh/9a6b7adcf3ee1097750c2afe32ea76b3 to your computer and use it in GitHub Desktop.
Creating a macro with elixir to vice versa nested math operations
This file contains 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
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