で予期しない結果を取得し、私はマクロモジュール次のマクロでbind_quoted
を理解していしようとしています:モジュールでbind_quoted声明
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.())
に従うよう
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
は、次にシェルで、私が遊んで最後の行の結果として、私は持っている
calling remote API...
=============
:ok
=============
:ok
しかし、私は期待して
=============
calling remote API...
:ok
=============
:ok
bind_quoted
は式を1回だけ実行することがわかります。
私の質問は、誰かが私が予期せぬ結果を得ている理由を説明してもらえますか?
いくつかのメディアをクロスポストしないでください。本当に必要な場合は、中央の場所を選択し、他のポストにリンクさせてください! – NobbZ
申し訳ありません、NobbZ。 –
@zero_coding Chris McCordの "Metaprogramming Elixir"への投資が賢明な動きであるマクロの使い方を習得しようとしているとお考えですか?あなたがこれらの種類の質問にあなた自身を助けるのを助けるかもしれないように思われます。もちろん、ちょっとした提案です。 –