@@ -1242,8 +1242,11 @@ defmodule Kernel.SpecialForms do
1242
1242
end)
1243
1243
1244
1244
In the example above, we have generated the functions `foo/0` and
1245
- `bar/0` dynamically. Now, imagine that we want to convert this
1246
- functionality into a macro:
1245
+ `bar/0` dynamically. Note the parentheses in `unquote(k)()` are important,
1246
+ otherwise we would try to define a function as `def :foo` instead of
1247
+ `def foo()`.
1248
+
1249
+ Now, imagine that we want to convert this functionality into a macro:
1247
1250
1248
1251
defmacro defkv(kv) do
1249
1252
Enum.map(kv, fn {k, v} ->
@@ -1268,8 +1271,9 @@ defmodule Kernel.SpecialForms do
1268
1271
code fails.
1269
1272
1270
1273
This is actually a common pitfall when developing macros. We are
1271
- assuming a particular shape in the macro. We can work around it
1272
- by unquoting the variable inside the quoted expression:
1274
+ assuming a particular shape at compilation time, within the macro
1275
+ implementation. One may try to work around it by unquoting the
1276
+ variable inside the quoted expression:
1273
1277
1274
1278
defmacro defkv(kv) do
1275
1279
quote do
@@ -1281,9 +1285,10 @@ defmodule Kernel.SpecialForms do
1281
1285
1282
1286
If you try to run our new macro, you will notice it won't
1283
1287
even compile, complaining that the variables `k` and `v`
1284
- do not exist. This is because of the ambiguity: `unquote(k)`
1285
- can either be an unquote fragment, as previously, or a regular
1286
- unquote as in `unquote(kv)`.
1288
+ do not exist. This is because the two `unquote`s in the call
1289
+ above are meant to run at distinct moments: `unquote(kv)`
1290
+ applies to the immediate quote, `unquote(k)` is an unquote
1291
+ fragment.
1287
1292
1288
1293
One solution to this problem is to disable unquoting in the
1289
1294
macro, however, doing that would make it impossible to inject the
0 commit comments