【发布时间】:2016-04-12 16:42:00
【问题描述】:
我正在尝试在宏中理解bind_quoted 并具有以下宏模块:
defmodule Debugger do
defmacro log(expression) do
if Application.get_env(:debugger, :log_level) == :debug do
quote bind_quoted: [expression: expression] do
IO.puts "============="
IO.inspect expression
IO.puts "============="
expression
end
else
expression
end
end
end
然后在 shell 中,我按照下面的模块玩弄
iex(1)> import_file "debugger_fixed.exs"
{:module, Debugger,
<<70, 79, 82, 49, 0, 0, 6, 224, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 158, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
{:log, 1}}
iex(2)> require Debugger
nil
iex(3)> Application.put_env(:debugger, :log_level, :debug)
:ok
iex(4)> remote_api_call = fn -> IO.puts("calling remote API...") end
iex(7)> Debugger.log(remote_api_call.())
作为最后一行的结果,我得到了
calling remote API...
=============
:ok
=============
:ok
但我期待
=============
calling remote API...
:ok
=============
:ok
我知道bind_quoted 只执行一次表达式。
我的问题是,有人可以解释为什么我得到了意想不到的结果吗?
【问题讨论】:
-
请不要跨多个媒体发帖,如果确实需要,请选择一个中心位置,让其他帖子链接到它!
-
@zero_coding 我是否可以建议,如果您正在尝试学习如何使用宏,那么投资 Chris McCord 的“Metaprogramming Elixir”会是明智之举吗?似乎这可能会帮助您解决这些问题。当然,这只是一个建议。
标签: elixir