Skip to content

Commit 8f09df6

Browse files
committed
Update and extend pattern-matching koans
1 parent a6f4182 commit 8f09df6

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

lib/koans/12_pattern_matching.ex

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,15 +83,15 @@ defmodule PatternMatching do
8383
end
8484

8585
koan "Errors are shaped differently than successful results" do
86-
dog = %{type: "dog"}
86+
dog = %{type: "barking"}
8787

88-
result =
88+
type =
8989
case Map.fetch(dog, :type) do
9090
{:ok, value} -> value
9191
:error -> "not present"
9292
end
9393

94-
assert result == ___
94+
assert type == ___
9595
end
9696

9797
defmodule Animal do
@@ -166,4 +166,42 @@ defmodule PatternMatching do
166166
^a = ___
167167
end
168168
end
169+
170+
koan "Pattern matching works with nested data structures" do
171+
user = %{
172+
profile: %{
173+
personal: %{name: "Alice", age: 30},
174+
settings: %{theme: "dark", notifications: true}
175+
}
176+
}
177+
178+
%{profile: %{personal: %{age: age}, settings: %{theme: theme}}} = user
179+
assert age == ___
180+
assert theme == ___
181+
end
182+
183+
koan "Lists can be pattern matched with head and tail" do
184+
numbers = [1, 2, 3, 4, 5]
185+
186+
[first, second | rest] = numbers
187+
assert first == ___
188+
assert second == ___
189+
assert rest == ___
190+
191+
[head | _tail] = numbers
192+
assert head == ___
193+
end
194+
195+
koan "Pattern matching can extract values from function return tuples" do
196+
divide = fn
197+
_, 0 -> {:error, :division_by_zero}
198+
x, y -> {:ok, x / y}
199+
end
200+
201+
{:ok, result} = divide.(10, 2)
202+
assert result == ___
203+
204+
{:error, reason} = divide.(10, 0)
205+
assert reason == ___
206+
end
169207
end

test/koans/patterns_koans_test.exs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,18 @@ defmodule PatternsTests do
1515
[1, 2, 3],
1616
{:multiple, ["Meow", "Woof", "Eh?"]},
1717
{:multiple, ["Mickey", "Donald", "I need a name!"]},
18-
"dog",
18+
"barking",
1919
"Max",
2020
{:multiple, [true, false]},
2121
"Max",
2222
1,
2323
2,
2424
{:multiple, ["The number One", "The number Two", "The number 3"]},
2525
"same",
26-
2
26+
2,
27+
{:multiple, [30, "dark"]},
28+
{:multiple, [1, 2, [3, 4, 5], 1]},
29+
{:multiple, [5, :division_by_zero]}
2730
]
2831

2932
test_all(PatternMatching, answers)

0 commit comments

Comments
 (0)