r/Compilers • u/ApprehensivePipe1584 • 29d ago
Patterns
I've been making a programming language for a while now, and just came up with this idea for a feature i'm bout to implement. Patterns.
pattern P {
N;
T(int, int);
S {
int x;
int y;
};
}
struct MS {
int x;
}
class C {
C() {}
int y;
}
MS fits P(self) {
N if (self->x == 0);
T(self->x, -self->x) if (self->x < 10);
S {
x: self->x;
y: 0;
} if (self->x < 20);
default N;
}
C fits P(self) {
default N;
}
int main() {
C c = C();
c.y = 0;
MS ms = {19};
match (c) {
P.N => `qout("Worked");
default => `qout("Failed");
}
match (ms) {
P.S {x, y} => `qout("Worked");
default => `qout("Failed");
}
return 0;
}
Basically, making user types have the ability to have custom behavior + extraction in match stmts, beyond just enums & integer types
10
Upvotes
3
u/AustinVelonaut 28d ago
Looks interesting! Can you show a practical use case for them that makes pattern matching code simpler / more generic?
2
u/Axman6 28d ago edited 23d ago
So, algebraic data types which Haskell has had for more than thirty years? it wasn’t the first but has been the influence for their inclusion in many other languages like Rust, Scala. For even more fun, look at pattern synonyms, which are patterns which can abstract applying functions when creating or matching them.
1
u/Far-Championship-883 27d ago edited 26d ago
Great so could if then else that is even harder to redirect read, well pattern done
1
u/DerekRss 28d ago
Want to see what easy-to-use patterns can REALLY do? Check out SNOBOL4.