Skip to content

Commit f5fc090

Browse files
authored
Small mention about disjunctive patterns (rescript-lang#70)
* Update pattern-matching-destructuring.mdx Disjunctive patterns are super valuable when you (rightly) don't want to use a wildcard, but have a lot of cases that match to the same thing. I think they should at least be mentioned in the docs even if they may not warrant a whole sub-section. * Added all required definitions * Remembering how to write valid rescript 😂 * Feedback adjustments * Moved to sub-section
1 parent ac206ad commit f5fc090

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

pages/docs/manual/latest/pattern-matching-destructuring.mdx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,42 @@ if (myNullableValue !== undefined) {
572572

573573
If you don't handle the `None` case, the compiler warns. No more `undefined` bugs in your code!
574574

575+
### Match multiple cases to one expression
576+
577+
Now, sometimes you may want to pattern-match on large but finite sets of possibilities where many possibilities map to the same expression. In these cases, wildcards can seem tempting because they reduce code duplication, but there's another option, often termed disjunctive patterns, that allow you to map multiple patterns to a single expression. That is, you can replace:
578+
579+
```res example
580+
type t = A | B | C | D | E
581+
let v = C
582+
switch v {
583+
| A => 1
584+
| _ => 2
585+
}
586+
```
587+
588+
with:
589+
590+
```res example
591+
type t = A | B | C | D | E
592+
let v = C
593+
switch v {
594+
| A => 1
595+
| B | C | D | E => 2
596+
}
597+
```
598+
599+
This still requires a bit more work than a wildcard, but it has the advantage of ensuring the compiler can enforce exhaustiveness, unlike a wildcard based solution. Additionally, unlike wildcards, you can easily refactor your code to have multiple pattern sets, like so:
600+
601+
```res example
602+
type t = A | B | C | D | E
603+
let v = C
604+
switch v {
605+
| A => 1
606+
| B | C => 2
607+
| D | E => 3
608+
}
609+
```
610+
575611
## Conclusion & Tips & Tricks
576612

577613
Hopefully you can see how pattern matching is a game changer for writing correct code, through the concise destructuring syntax, the proper conditions handling of `switch`, and the static exhaustiveness check.

0 commit comments

Comments
 (0)