dart-lang / dart-lang/language
Reusable Pattern Matching
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
## Problem
Dart currently offers powerful features with pattern matching like `if-case`, `switch expressions`, `destructuring`... which greatly enhance code readability and safety:
```dart
var json = {
'user': ['Lily', 13]
};
var { 'user': [name, age] } = json;
```
However, I believe these feature could empower even more developers by introducing a mechanism to define reusable patterns, much like we define functions or classes:
```dart
patterndef ValidUser(String name, int age) = { 'user': [name, age] };
```
This would be particularly useful in scenarios where the same pattern is used across multiple switch statements or within different parts of the application. Additionally, allowing the definition of pattern constants could help in enforcing consistency across the codebase and reducing redundancy.
## Proposal
By adding the `patterndef` keyword in Dart that allows developers to define patterns once and reuse them multiple times. Here's an example of what this could look like:
```dart
// patterndef have similar syntax of typedef
patterndef PrimaryColors() = Color.red || Color.green || Color.blue;
void validateColor() {
final color = Color.red;
// using switch expressions
final isPrimary = switch (color) {
PrimaryColors => true,
_ => false,
};
// using if-case
if (color case PrimaryColors) {
print('Is primary color: $isPrimary');
} else {
print('Is not primary color: $isPrimary');
}
// using destructuring
final PrimaryColors(colorIsPrimary) =color;
}
```
Contributor guide
Research direction
Start by reviewing Dart's existing pattern matching features, including if-case, switch expressions, and destructuring, then examine the proposed patterndef syntax and its examples. Done would require a settled language design for reusable patterns and pattern constants, including how they work across switch statements, if-case, and destructuring.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100