laiboonh

laiboonh

Trying to define my own if macro

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.

Most Liked

NobbZ

NobbZ

unquote does not execute anything.

But, lets try to expanding your macro by hand. Perhaps we can enlighten you that way!

Your intitial version:

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

In the wollowing steps, I wont use the AST, but the human readable representation of the AST to simplify things a bit.

And now lets expand Controlö.my_if(false, do: IO.inpsect true, then: IO.inspect false:

First lets fill in the gaps of the Macro:

quote do
  Control.do_my_if(unquote(false, do: unquote(IO.inspect true), then: unquote(IO.inspect false)))
end

Now lets do the unquote:

Control.do_my_if(false, do: IO.inspect true, then: IO.inspect false)

As you can see, we have finished expanding and compiling the macro. We have left a plain function call in the BEAM-byte code. Its arguments will be evaluated at runtime.

Now lets try the version of @OvermindDL1 which I won’t paste again, using the same snippet as above:

The first thing to mention is, that there is no quote in the macro definition, therefore the function is called at compile time! In that function is a quote, therefore wi will look at that now:

quote do
  case unquote(false) do
      result when result in [false, nil] -> unquote(IO.inspect false)
      _ -> unquote(IO.inspect true)
  end
end

And now unquote this:

case false do
    result when result in [false, nil] -> IO.inspect false
    _ -> IO.inspect true
end

As you can see, this version expands into a case-expression and not a function call. Also since do_my_if is called from inside Control during compiletime (not from another module during runtime as in your version), you should be able to even defp it in Overminds version.


Somewhere burried in the Macro module, there was a function or macro which was able to print the expanded sourcecode of a macro-call. That is very nice when debugging them.

NobbZ

NobbZ

That never happened :wink:

Where Next?

Popular in Questions Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New

We're in Beta

About us Mission Statement