@@ -23,6 +23,7 @@ iex> case {1, 2, 3} do
23
23
...> _ ->
24
24
...> "This clause would match any value"
25
25
...> end
26
+ "This clause will match and bind x to 2 in this clause"
26
27
```
27
28
28
29
If you want to pattern match against an existing variable, you need to use the ` ^ ` operator:
@@ -34,6 +35,7 @@ iex> case 10 do
34
35
...> ^x -> "Won't match"
35
36
...> _ -> "Will match"
36
37
...> end
38
+ "Will match"
37
39
```
38
40
39
41
Clauses also allow extra conditions to be specified via guards:
@@ -45,6 +47,7 @@ iex> case {1, 2, 3} do
45
47
...> _ ->
46
48
...> "Won't match"
47
49
...> end
50
+ "Will match"
48
51
```
49
52
50
53
The first clause above will only match when ` x ` is positive.
@@ -162,6 +165,7 @@ iex> cond do
162
165
...> true ->
163
166
...> "This is always true (equivalent to else)"
164
167
...> end
168
+ "This is always true (equivalent to else)"
165
169
```
166
170
167
171
Finally, note ` cond ` considers any value besides ` nil ` and ` false ` to be true:
@@ -241,6 +245,7 @@ One thing to keep in mind when using `do/end` blocks is they are always bound to
241
245
iex> is_number if true do
242
246
...> 1 + 2
243
247
...> end
248
+ ** (RuntimeError) undefined function: if/1
244
249
```
245
250
246
251
Would be parsed as:
@@ -249,6 +254,7 @@ Would be parsed as:
249
254
iex> is_number(if true) do
250
255
...> 1 + 2
251
256
...> end
257
+ ** (RuntimeError) undefined function: if/1
252
258
```
253
259
254
260
Which leads to an undefined function error as Elixir attempts to invoke ` is_number/2 ` . Adding explicit parentheses is enough to resolve the ambiguity:
0 commit comments