Skip to content

Commit ae7e3d8

Browse files
committed
Introduce pattern matching support
1 parent e0d1666 commit ae7e3d8

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

course9/course_en.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,27 @@ fn init {
333333

334334
---
335335

336+
# Pattern Matching
337+
338+
- The type must implement the `op_get` method, where the key is a native type and the value is an `Option[T]`.
339+
- When matching, the key must be a literal.
340+
- In `{ "key": pat }`, the pattern pat type is `Option[T]`.
341+
- Unmatched keys will be ignored even if they exist.
342+
- The code generated is optimized, with each key being queried at most once.
343+
344+
```moonbit
345+
fn init {
346+
let empty: Map[Int, Int] = make()
347+
let one = { empty[1] = 1 }
348+
match one {
349+
{ 2 : Some(y) } => println(y)
350+
{ 2 : None, 1 : Some(k) } => println(k)
351+
}
352+
}
353+
```
354+
355+
---
356+
336357
# Summary
337358

338359
- In this chapter, we learned how to

course9/lecture_en.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,21 @@ fn init {
292292

293293
In the previous example, the assignment statement is essentially an expression, and the return value is determined by the `op_get` method. We can use this method to retrieve the updated value. For mutable data structures, we also have the option to modify them in place without returning any value.
294294

295+
With the implementation of `op_get`, we can introduce pattern matching support to `Map`. This feature is applicable when the key is a native type and the value is an `Option[T]`.
296+
297+
```moonbit
298+
fn init {
299+
let empty: Map[Int, Int] = make()
300+
let one = { empty[1] = 1 }
301+
match one {
302+
{ 2 : Some(y) } => println(y)
303+
{ 2 : None, 1 : Some(k) } => println(k)
304+
}
305+
}
306+
```
307+
308+
When matching, it is important to note that the key needs to be a literal value. In `{ "key": pat }`, the type of the pattern `pat` should be `Option[T]`. It is worth mentioning that the key-value pair pattern is open, meaning that any unmatched keys will be ignored even if they exist. Additionally, the code generated for key-value pair patterns is optimized, ensuring that each key is only queried at most once.
309+
295310
# Summary
296311

297312
In this chapter, we learned how to

0 commit comments

Comments
 (0)