a-maze-d

a-maze-d

Capturing anonymous functions in macros

Hi,

I’m trying to create some syntactic sugar through a macro. The basic function should look like the following:

f :name do
  data.something + 10
end

The macro will transform the body to an anonymous function. Yes the somewhat undefined data is intentional, it will be used to capture the argument that will be passed to the function.

I didn’t manage to create a macro that resolves the data correctly. I found now a solution that works by using the anonymous function of the capture operator. The downside is that I need to capture the argument through &1.something which does not look nice :frowning: (note the real code looks more complicated since it uses a compile hook, but the following is working)

defmodule F do
  defmacro f(name, options, do: block) do
    func = quote do
      &(unquote(block))
    end
    quote do
      register(unquote(name), unquote(options), unquote(func))
    end
  end

  def register(name, options, func) do
    result = func.(%{something: 10})
    IO.puts("#{inspect name}, #{inspect options}, #{inspect func}, #{inspect result}")
  end
end

defmodule G do
  def run() do
    import F
    F.f :name, [] do
      &1.something-10
    end
  end
end

And call it with:

import G
G.run

If I convert the capturing operator to an anonymous function it should work just fine. The doc does state:

In other words, &(&1 * 2) is equivalent to fn x -> x * 2 end.

But, whenI change my macro to look like this:

defmacro f(name, options, do: block) do
    func = quote do
      fn(data) -> unquote(block) end
    end
    quote do
      register(unquote(name), unquote(options), unquote(func))
    end
  end

I get the error:

warning: variable "data" does not exist and is being expanded to "data()", please use parentheses to remove the ambiguity or change the variable name
  lib/f.ex:21: G.run/0


== Compilation error in file lib/f.ex ==
** (CompileError) lib/f.ex:21: undefined function data/0 (expected G to define such a function or for it to be imported, but none are available)

Why is this? Can someone please help me to understand this?

Marked As Solved

christhekeele

christhekeele

What you’re struggling with is called macro hygiene.

This macro would indeed expand this call:

f(:name, [option: :option]) do
  data.something + 10
end

into this code:

register(:name, [option: :option], fn(data) -> data.something + 10 end)

However, the compiler recognizes that the variable data has two different providences, and treats them as different variables; it sees things more like this:

register(:name, [option: :option], fn(data1) -> data2.something + 10 end)
#                                     ▲         ▲
# your macro's `data` ────────────────┘         │
# your user code's `data` ──────────────────────┘

Macro hygiene allows macro authors to not worry about their generated code stepping on other variables in scope, but requires more work when injecting user-provided code with your own variables.

You should be able to follow the guide linked above to decorate your macro’s data with a call to var! to escape hygiene.

Alternatively, and perhaps more idiomatically, you could allow the user code to dictate the variable name by having your macro expect clauses, similar to a case statement. Untested code snippet, that I’ve gotten to work with macros before; IIRC you have to build the AST for the fn by hand instead of using quote/unquote as there is no analog to unquote_splicing that works for clauses:

defmacro f(name, options, do: clauses) do
    func_ast = {:fn, [], clauses}
    quote do
      register(unquote(name), unquote(options), unquote(func_ast))
    end
  end
end

Then in user-code:

f(:name, [option: :option]) do
  data -> data.something + 10
end

This has the added benefit of letting users pattern-match and provide multiple clauses to handle different cases.

At this point though, you may well want them to just pass in a function–depending on your use-case.

Also Liked

a-maze-d

a-maze-d

Thanks for your swift help. It is indeed what you are stating. Thus the use of Kernel.var! solves that problem.

The reason why I didn’t manage to resolve it myself, because I didn’t realize the difference between Macro.var and Kernel.var!.

Thanks again for your help.

Ps: Your suggestion to allow the user to select the binding, is definitely something I wanted to allow, in a later version.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
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
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
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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

We're in Beta

About us Mission Statement