除了直接使用 Code.eval_quoted
把表達試直接執行之外
寫巨集(macro)的時候,我們也會使用 Macro.to_string/1
來預先檢查目前寫的巨集
representation = quote do
rem(9, 3)
end
Macro.to_string(representation)
#=> "rem(9, 3)"
但如果我今天想要使用 quote 外面的變數的話...
n = 99
representation = quote do
rem(n, 3)
end
Macro.to_string(representation)
#=> "rem(n, 3)"
我們會發現,表達式保留的是 quote 裡面原本的樣子,
這樣子我們如果之後要使用這個表達式來寫巨集的時候,
每次都要準備好變數 n 相當不方便
unquote/1
這個時候我們可以使用 unquote/1
將 n
包起來
n = 99
representation = quote do
rem(unquote(n), 3)
end
Macro.to_string(representation)
#=> "rem(99, 3)"