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 elixir/lib/elixir/lib/kernel.ex at 5feec03db6a134371d9c0f60cc8873232659005e · elixir-lang/elixir · GitHub 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

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
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
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement