Skip to content

Commit 7da25d0

Browse files
committed
Add more details to unquoting in meta/chapter-1
I added an additional code sample showing what happens when you don't `unquote` a value but you want to inject that value in a quoted expression.
1 parent 419d5a3 commit 7da25d0

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

getting_started/meta/1.markdown

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ An Elixir program can be represented by its own data structures. In this chapter
1212

1313
## 1.1 Quoting
1414

15-
The building block of an Elixir program is a tuple with three elements. For example, the function call `sum(1,2,3)` is represented internally as:
15+
The building block of an Elixir program is a tuple with three elements. For example, the function call `sum(1, 2, 3)` is represented internally as:
1616

1717
```elixir
1818
{:sum, [], [1, 2, 3]}
@@ -45,7 +45,7 @@ Variables are also represented using such triplets, except the last element is a
4545

4646
```iex
4747
iex> quote do: x
48-
{ :x, [], Elixir }
48+
{:x, [], Elixir}
4949
```
5050

5151
When quoting more complex expressions, we can see that the code is represented in such tuples, which are often nested inside each other in a structure resembling a tree. Many languages would call such representations an Abstract Syntax Tree (AST). Elixir calls them quoted expressions:
@@ -65,7 +65,7 @@ iex> Macro.to_string(quote do: sum(1, 2 + 3, 4))
6565
In general, the tuples above are structured according to the following format:
6666

6767
```elixir
68-
{ tuple | atom, list, list | atom }
68+
{tuple | atom, list, list | atom}
6969
```
7070

7171
* The first element is an atom or another tuple in the same representation;
@@ -88,7 +88,15 @@ Most Elixir code has a straight-forward translation to its underlying quoted exp
8888

8989
Quote is about retrieving the inner representation of some particular chunk of code. However, sometimes it may be necessary to inject some other particular chunk of code inside the representation we want to retrieve.
9090

91-
For example, imagine you have a variable `number` which contains the number you want to inject inside a quoted expression. The number can be injected into the quoted representation by using `unquote`:
91+
For example, imagine you have a variable `number` which contains the number you want to inject inside a quoted expression.
92+
93+
```iex
94+
iex> number = 13
95+
iex> Macro.to_string(quote do: 11 + number)
96+
"11 + number"
97+
```
98+
99+
That's not what we wanted, since the value of the `number` variable has not been injected and `number` has been quoted in the expression. In order to inject the *value* of the `number` variable, `unquote` has to be used inside the quoted representation:
92100

93101
```iex
94102
iex> number = 13

0 commit comments

Comments
 (0)