Understand Macro.escape

Hi all
I am trying to understand how Macro.escape works, read a several time the documentation and do not understand how it works or for what is good for?
Could please someone explain me, what Macro.escape is and how to use it or when to use it? Please with an example.

Thanks so much


As in the documentation (Macro.escape/2), it does return the AST of the passed in value in contrast do quote which does return the AST of the passed in code.

As contrived example from an iex session should make the difference more clear:

iex(1)> defmodule Foo, do: def(bar, do: [1,2,3])
{:module, Foo, <<...>>, {:bar, 0}}
iex(2)> Foo.bar
[1, 2, 3]
iex(3)> quote do: Foo.bar 
{{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}
iex(4)> Macro.escape(Foo.bar)
[1, 2, 3]
iex(5)> quote do: [1,2,3] 
[1, 2, 3]

So as you can see, the return value of quote, does give you an AST for some code that can generate the value [1,2,3], while for Macro.escape/1 the argument is evaluated to get its value and then this value is returned as AST. (for lists, atoms, and integers the AST is actually identically to the value).


Always good answer from you.
Thanks so much.