Skip to content

Commit ba7c0fa

Browse files
committed
chore: add pattern matching
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
1 parent f85489c commit ba7c0fa

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

content/week01/intro.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,42 @@ longer have to look at the whole program, but just smaller, digestible parts.
124124
Everyone learning a language will know what these common constructs are. No one
125125
will know what your special constructs are.
126126

127+
128+
#### Example: match
129+
130+
Let's quickly apply this to a much newer example. Take the following code that
131+
provides different printouts for different structures:
132+
133+
```python
134+
if isinstance(x, list):
135+
print(*x)
136+
elif isinstance(x, dict):
137+
print(*(f"{k}={v}" for k, v in x.items()))
138+
else:
139+
print(x)
140+
```
141+
142+
versus using pattern matching:
143+
144+
```python
145+
match x:
146+
case [*_]:
147+
print(*x)
148+
case {}:
149+
print(*(f"{k}={v}" for k, v in x.items()))
150+
case _:
151+
print(x)
152+
```
153+
154+
The pattern matching case is more focused, so it takes less reading. You know
155+
from the first line `match x` that this is based on the variable `x`; in the if
156+
chain, you could have switched to some other variable partway down the chain,
157+
so the reader has to look at each branch to verify you are just processing one
158+
variable. The language has built-in support for various situations, while the
159+
manual form would require you write everything out. There's a learning curve to
160+
the more specific structure, but anyone learning the language learns it once,
161+
rather than rereading it or rewriting it every time in every codebase.
162+
127163
## Course structure
128164

129165
The challenges of this course:

slides/week-01-1.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,29 @@ for i in range(10):
100100
compute(i)
101101
```
102102

103+
## Example: match
104+
105+
```python
106+
if isinstance(x, list):
107+
print(*x)
108+
elif isinstance(x, dict):
109+
print(*(f"{k}={v}" for k, v in x.items()))
110+
else:
111+
print(x)
112+
```
113+
114+
vs.
115+
116+
```python
117+
match x:
118+
case [*_]:
119+
print(*x)
120+
case {}:
121+
print(*(f"{k}={v}" for k, v in x.items()))
122+
case _:
123+
print(x)
124+
```
125+
103126
---
104127

105128
## Course structure

0 commit comments

Comments
 (0)