augnustin

augnustin

I don't understand quote/unquote: why do we need them?

Hi,

I have been coding with Elixir for 9+ months and I encountered several time the concept of quotes and each time, I think “ok, today I shall be mature enough to understand quotes”, re-read the content I can find on the internet (starting with the getting started).

But until now, I still haven’t understood the blood out of it. :frowning:

My main question is why do we need them?

If quoting is only about changing the representation of a piece of code, then why should it be so different quoted than unquoted. I’m comfortable with the concept of AST, but as for me it only changes the representation of something, not its content.

Eg. 1 + (2 + 3) <==> add(1, add(2, 3))

Besides, it feels illogical to me that there are two worlds: the quoted one and the unquoted. If quoting is about meta-programming, then quoting quoted expressions should make sense to program meta-meta-programming, shouldn’t it?

Someone in this forum suggested that macros (that are closely related to quotes, aren’t they?) should be seen as functions that return other functions instead of expressions. This helped me a little to read some quote-using-code, but it still doesn’t explain why we need them.

I am comfortable with currying, partial application, function as references, which are the way meta-programming goes in languages I’m more comfortable with (JS, Haskell …), so what’s different here?

Finally, are quotes so hard to understand or is it just me?

Of course, I feel like this is key concept to be comfortable with Elixir, I can be patient with that, just like I was (am?) with Haskell’s monads, but nothing out there suggests that this one has to expect something hard so it may be just me…

Thanks for the help, hope this can be useful to others!

Marked As Solved

LostKobrakai

LostKobrakai

There are two worlds because there are two times when code is executed:

  • At compile time (any code, which is not a function body is executed + macros)
  • At runtime (Function bodies are executed)

Take this example:

defmodule A do
  for {i, level} <- %{1 => :err, 2 => :warn, 3 => :info} do
    def log_level(i), do: level
  end
end

For the function log_level what do you expect i and level to represent?
Basically it’s 3 times this: def log_level(i), do: level, and it would complain about unmatchable clauses (all match i) as well as crash at runtime for an undefined variable level.

This is where unquoting comes in.

defmodule A do
  for {i, level} <- %{1 => :err, 2 => :warn, 3 => :info} do
    def log_level(unquote(i)), do: unquote(level)
  end
end

At compile time this will define a module A with 3 function heads looking like that:

def log_level(1), do: :err
def log_level(2), do: :warn
def log_level(3), do: :info

The runtime will never know of i and level and therefore not fail because of undefined variables. The same thing happens in macros, where you also create AST at compile time. Macros can however also edit AST.

You might be wondering why this example doesn’t use a quote like macros do. For a module it’s clear which code is compile time executed and which isn’t (only function bodies aren’t executed at compile time), so all the quote/unquote stuff happens as part of the defmodule implementation. For macros there needs to be a distinction between code executed at compile time and the code it actually generates. To not have you manually edit AST nodes there’s quote. It takes its body and converts the contents into AST. It’s basically a AST generator. quote has the same problem as I explained above for the module body, therefore it uses unquote as well, to put data you have at compile time “hard coded” into the generated AST.

The complexity really hits if you want to create the module body from my example (those unquotes are usually named unquote fragments) within the quote of a macro. This is where you need to use the bind_quoted option for quote to remove the ambiguity.

43
Post #4

Also Liked

NobbZ

NobbZ

Quote and unquote are the AST equivalent of the double quote that encloses a string and #{} which you use in a string to inject a variables value rather than just it’s name.

They are essential for code generation, meta programming and macros

entone

entone

Let’s assume we have a function that is going to generate a function for us, and we want to pass in some arguments that can get pattern matched on.

def create_handle_event_function(event, next) do
  quote do
    def handle_event(unquote(event) = runtime_event, state) do
      state = handle_our_event(runtime_event, state)
      {:ok, state, unquote(next)}
    end
  end
end

This allows us to pass in compile time arguments, that can get evaluated/pattern matched at runtime.

So unquote allows us to pass in compile-time args, and get the AST of the value for runtime.

Not sure if that helps at all.

augnustin

augnustin

This is amazing. 1 year later I come back here and now it feels like macros are something I could get comfortable with. :fireworks:

Thanks @LostKobrakai your example really helps.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
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

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
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 29603 241
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement