You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: getting-started/meta/macros.markdown
+9-9
Original file line number
Diff line number
Diff line change
@@ -23,11 +23,11 @@ In order to better understand how macros work, let's create a new module where w
23
23
24
24
```elixir
25
25
defmoduleUnlessdo
26
-
deffun_unless(clause, expression) do
26
+
deffun_unless(clause, do:expression) do
27
27
if(!clause, do: expression)
28
28
end
29
29
30
-
defmacromacro_unless(clause, expression) do
30
+
defmacromacro_unless(clause, do:expression) do
31
31
quotedo
32
32
if(!unquote(clause), do:unquote(expression))
33
33
end
@@ -47,9 +47,9 @@ And play with those definitions:
47
47
48
48
```iex
49
49
iex> require Unless
50
-
iex> Unless.macro_unless true, IO.puts "this should never be printed"
50
+
iex> Unless.macro_unless true, do: IO.puts "this should never be printed"
51
51
nil
52
-
iex> Unless.fun_unless true, IO.puts "this should never be printed"
52
+
iex> Unless.fun_unless true, do: IO.puts "this should never be printed"
53
53
"this should never be printed"
54
54
nil
55
55
```
@@ -59,14 +59,14 @@ Note that in our macro implementation, the sentence was not printed, although it
59
59
In other words, when invoked as:
60
60
61
61
```elixir
62
-
Unless.macro_unlesstrue, IO.puts"this should never be printed"
62
+
Unless.macro_unlesstrue, do:IO.puts"this should never be printed"
63
63
```
64
64
65
65
Our `macro_unless` macro received the following:
66
66
67
67
{% raw %}
68
68
```elixir
69
-
macro_unless(true, {{:., [], [{:aliases, [], [:IO]}, :puts]}, [], ["this should never be printed"]})
69
+
macro_unless(true, [do:{{:., [], [{:__aliases__, [alias:false], [:IO]}, :puts]}, [], ["this should never be printed"]}])
70
70
```
71
71
{% endraw %}
72
72
@@ -86,7 +86,7 @@ And it then returned a quoted expression as follows:
86
86
We can actually verify that this is the case by using `Macro.expand_once/2`:
87
87
88
88
```iex
89
-
iex> expr = quote do: Unless.macro_unless(true, IO.puts "this should never be printed")
89
+
iex> expr = quote do: Unless.macro_unless(true, do: IO.puts "this should never be printed")
90
90
iex> res = Macro.expand_once(expr, __ENV__)
91
91
iex> IO.puts Macro.to_string(res)
92
92
if(!true) do
@@ -100,9 +100,9 @@ end
100
100
That's what macros are all about. They are about receiving quoted expressions and transforming them into something else. In fact, `unless/2` in Elixir is implemented as a macro:
0 commit comments