defmodule Control do
defmacro my_if(expr, do: if_block, else: else_block) do
quote do
Control.do_my_if(unquote(expr), do: unquote(if_block), else: unquote(else_block))
end
end
defmacro my_if(expr, do: if_block) do
quote do
Control.do_my_if(unquote(expr), do: unquote(if_block), else: nil)
end
end
def do_my_if(expr, do: if_block, else: else_block) do
case (expr) do
result when result in [false, nil] -> else_block
_ -> if_block
end
end
end
iex(1)> c "control.exs"
[Control]
iex(2)> require Control
Control
iex(3)> Control.my_if(2==2, do: "true", else: "false")
"true"
What i donât like about my implementation is that i would like to keep do_my_if
as private function but this doesnât compile if i do that.
I also donât like the fact that i have to call Control.do_my_if
in the macro body, why canât i simply do do_my_if
. During the AST expansion phase do_my_if
should be totally legal shouldnât it?
I looked at the Elixir source code https://github.com/elixir-lang/elixir/blob/5feec03db6a134371d9c0f60cc8873232659005e/lib/elixir/lib/kernel.ex and the two points i mentioned seemed achievable. I donât know what i am doing wrong. Any help is appreciated, thanks in advance.