wrachwal

wrachwal

Macro to generate function with body containing an arg and var bound in outer scope?

Hi,

I am trying to define a macro with 3 arguments (name, var, body) which is to generate function name/1
a) with argument var, possibly arbitrary complex pattern-matching expression
b) besides var, other variables bound in the outer scope can be used in the body

Example:

defmodule Mac3Use do
  import Mac3
  for {g, v} <- [g1: 1, g2: 2] do 
    gen String.to_atom("#{g}_x"), a,           do: {:ok, 1, a}
    gen String.to_atom("#{g}_y"), %{y: y} = a, do: {:ok, y, a}
  # gen String.to_atom("#{g}_z"), a,           do: {:ok, v, a} # undefined function v/0
  end
end

Below the implementation satisfying a). With slight modification it can handle guards. Unfortunately it doesn’t handle b) - I get “undefined function v/0” CompileError.

defmodule Mac3 do
  defmacro gen(name, var \\ quote(do: _), do: block) do
    var = Macro.escape(var)
    block = Macro.escape(block)
    quote bind_quoted: [name: name, var: var, block: block] do
      def unquote(name)(unquote(var)) do
        unquote(block)
      end
    end
  end
end

I was trying to modify this code without luck. Inspect of binding() inside quote shows g and v variables from the example with proper values bound, but unquote(block) doesn’t want to consume v.

Just a moment ago I checked that

    @v  v
    gen String.to_atom("#{g}_z"), a, do: {:ok, @v, a}

works, but it’s rather a hack.

As you could notice, the macro resembles ExUnit.Case.test/3, and its implementation is simplified version of that from ExUnit.

Is there an easy solution to this?

Thank you,
Waldemar.

Marked As Solved

NobbZ

NobbZ

I still think unquote: true is the option you actually want… You’ll have to write unquote(v) then, but at least it should work. And as far as I remember ExUnit, you have to unquote “external” names there as well…

Also Liked

NobbZ

NobbZ

As you can see in the code, they are unquoteing contents (your body) first before escapeing it. Also they escape using the unquote: true option.

Perhaps you should evaluate those ways?

jfeng

jfeng

I think changing

    gen String.to_atom("#{g}_z"), a,           do: {:ok, v, a} # undefined function v/0

to

    gen String.to_atom("#{g}_z"), a,           do: {:ok, unquote(v), a} # should work fine this way

should work. As far as I can tell, you want to use a value of v that’s only available at compile time in the module, but as you have it, v and a are just regular variables declared in the body of a function.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
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

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
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
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
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
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement