Elixir 报价 vs 逃生
Elixir quote vs escape
在 Elixir 中,什么时候应该使用 Macro.escape/1
而不是 quote/1
?我查看了 beginner's guide,但没有帮助。
quote/2
returns the abstract syntax tree (AST) of the passed in code block.
Macro.escape/2
returns 传入的AST value.
这是一个例子:
iex(1)> a = %{"apple": 12, "banana": 90}
%{apple: 12, banana: 90}
iex(2)> b = quote do: a
{:a, [], Elixir}
iex(3)> c = Macro.escape(a)
{:%{}, [], [apple: 12, banana: 90]}
quote/2
将保留原始变量 a
,而 Macro.escape/2
会将 a
的值注入返回的变量AST.
iex(4)> Macro.to_string(b) |> Code.eval_string
warning: variable "a" does not exist and is being
expanded to "a()", please use parentheses to remove
the ambiguity or change the variable name
nofile:1
iex(5)> Macro.to_string(c) |> Code.eval_string
{%{apple: 12, banana: 90}, []}
iex(6)> Macro.to_string(b) |> Code.eval_string([a: "testvalue"])
{"testvalue", [a: "testvalue"]}
为了完整起见:
iex(1)> a = %{"apple": 12, "banana": 90}
%{apple: 12, banana: 90}
iex(3)> Macro.escape(a)
{:%{}, [], [apple: 12, banana: 90]}
iex(2)> quote do: %{"apple": 12, "banana": 90}
{:%{}, [], [apple: 12, banana: 90]}
在 Elixir 中,什么时候应该使用 Macro.escape/1
而不是 quote/1
?我查看了 beginner's guide,但没有帮助。
quote/2
returns the abstract syntax tree (AST) of the passed in code block.
Macro.escape/2
returns 传入的AST value.
这是一个例子:
iex(1)> a = %{"apple": 12, "banana": 90}
%{apple: 12, banana: 90}
iex(2)> b = quote do: a
{:a, [], Elixir}
iex(3)> c = Macro.escape(a)
{:%{}, [], [apple: 12, banana: 90]}
quote/2
将保留原始变量 a
,而 Macro.escape/2
会将 a
的值注入返回的变量AST.
iex(4)> Macro.to_string(b) |> Code.eval_string
warning: variable "a" does not exist and is being
expanded to "a()", please use parentheses to remove
the ambiguity or change the variable name
nofile:1
iex(5)> Macro.to_string(c) |> Code.eval_string
{%{apple: 12, banana: 90}, []}
iex(6)> Macro.to_string(b) |> Code.eval_string([a: "testvalue"])
{"testvalue", [a: "testvalue"]}
为了完整起见:
iex(1)> a = %{"apple": 12, "banana": 90}
%{apple: 12, banana: 90}
iex(3)> Macro.escape(a)
{:%{}, [], [apple: 12, banana: 90]}
iex(2)> quote do: %{"apple": 12, "banana": 90}
{:%{}, [], [apple: 12, banana: 90]}