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

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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
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
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
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
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
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

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement