mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Exhaustive Pattern Matching Of List Variants as a reason til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_612 TILs and counting..._
|
||||
_613 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -440,6 +440,7 @@ _612 TILs and counting..._
|
||||
|
||||
### ReasonML
|
||||
|
||||
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md)
|
||||
- [Pattern Match On Exceptions](reason/pattern-match-on-exceptions.md)
|
||||
- [String Interpolation With Integers And Sprintf](reason/string-interpolation-with-integers-and-sprintf.md)
|
||||
|
||||
|
||||
32
reason/exhaustive-pattern-matching-of-list-variants.md
Normal file
32
reason/exhaustive-pattern-matching-of-list-variants.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Exhaustive Pattern Matching Of List Variants
|
||||
|
||||
ReasonML's `switch` expression allows for powerful pattern matching. When
|
||||
using `switch` to pattern match against a list, the compiler will be sure to
|
||||
warn you if you haven't accounted for all variants of a list.
|
||||
|
||||
```reason
|
||||
let getFirst = (numList: list(int)): int => {
|
||||
switch(numList) {
|
||||
| [first, ...rest] => first
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
> this pattern-matching is not exhaustive. Here is an example of a value
|
||||
> that is not matched: []
|
||||
|
||||
The compiler knows that a list can either be 1) empty (`[]`) or 2) contain
|
||||
at least one value and another list (`[a, ...rest]`). To ensure all variants
|
||||
are accounted for, we can include the `[]` case in our switch.
|
||||
|
||||
```reason
|
||||
let getFirst = (numList: list(int)): int => {
|
||||
switch(numList) {
|
||||
| [] => -1
|
||||
| [first, ...rest] => first
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
[source
|
||||
code](https://reasonml.github.io/en/try.html?reason=DYUwLgBAdgrgtgIxAJwM4C4LAJarACmyjAEoIBeCAbQDYAaABjvvoEYBdAbgChvRIA5uABi2NJEr5YcADK4wmHHkLESJTEQkA+CAG9uECKgDu2MAGMAFlPhy8ZfYYA+1AGZi8dCADpfyEHjsFDru4gYQAL48UbwAUqjewAD2AvhCYKLiNogoqGqcQA)
|
||||
Reference in New Issue
Block a user