r/Compilers • • Oct 25 '26

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

8 Upvotes

33 comments sorted by

3

u/AustinVelonaut Oct 25 '26

Looks interesting! Can you show a practical use case for them that makes pattern matching code simpler / more generic?

3

u/ApprehensivePipe1584 Oct 25 '26

Basically, my `match` only matches on integers & enums, so this allows your own non-enum types to interop with `match`, such as a heap wrapper like this
```
pattern Valid {
Valid(void *);
Invalid;
}
class MyHeapWrapper {
private void *data;
bool isValid() {...}
...
}
MyHeapWrapper fits Valid(heap) {
Valid(heap->data) if (heap.isValid());
default Invalid;
}
```
then you could just
```
match (myheap) {
Valid.Valid(data) => ...handle
Valid.Invalid => ...error
}
```
or like, in a game you could have for example
```
pattern Active {
Active;
Idle;
Off;
}
class Player {
...
}
Player fits Active(p) {
Active if (!p.is_dead);
default Off;
}
```
Which not only avoids neding to for example track a PlayerState enum and manually set it, but also allows for easier encapsulation, etc. And also it allows you to make multiple types of the same pattern, like a physics render that has a global pattern for like physics states and can share matching. Also, it's compiel time only and takes up no data, compared to storing enums. Not sure if theres a difference between it and enums except it has more options for tags (sruct tags), it allows you to avoid storing just a random enum in your class (e.g. for cache line purposes), less public fields, and it providing a shared interface automatically instead of manually setting state and providing like a setEnumState method and nonsense.

2

u/Axman6 Oct 25 '26 edited Oct 30 '26

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. 

4

u/ApprehensivePipe1584 Oct 25 '26

Oh yeah, its very similar to pattern synonyms in Haskell. Didn't even think of that. I don't think it's the exact same purpose, but definitely similar.

2

u/AustinVelonaut Oct 25 '26

It's not just ADT or pattern synonyms, though. It looks to me more like a form of typeclasses (ad-hoc polymorphism) combined with patterns, where a pattern can have multiple independent concrete instances defined by user data structures.

3

u/Competitive_Ideal866 Oct 26 '26

Sounds like active patterns aka view patterns?

2

u/AustinVelonaut Oct 26 '26

Yeah, F# active patterns come closer to describing what the OP proposes, except additionally the constructors are grouped into a typeclass-like pattern which can have multiple ad-hoc fits instances.

1

u/Far-Championship-883 Oct 27 '26 edited Oct 28 '26

Great so could if then else that is even harder to redirect read, well pattern done 

1

u/ApprehensivePipe1584 Oct 28 '26

What? What do you even mean "so could that is even"? Are you being sarcastic?

1

u/ApprehensivePipe1584 Oct 28 '26

I could answer your question if you meant something else.

1

u/ApprehensivePipe1584 Oct 28 '26

Oh are you trying to say that if (cond) then else could do it better and thing if (cond); thing if (cond);.. is hard to read? well pattern done though what does that mean? this syntax i chose because it reads more line-by-line as just making it a function doesn't really fit this syntax so i didn't want
if(thing) {
return CASE
...
and that would mkae the syntax much harder. This doesn't do the same thing as if else, it handles patter nmatching tags struct cases and is automatic pattern matching, it couldn't.

0

u/Far-Championship-883 Oct 29 '26

I use this programming language and contribute to some of it.

https://github.com/AiLang-Author/Ailang-Self-Hosting-/blob/master/Demo%20Programs/programs/068_fork_branch_combinatorial.ailang

// Fork + Branch — combinatorial use (off-list companion demo)

//

// Companion to 061_branch_not_switch.ailang, 062_switch_case.ailang,

// and 067_fork_not_switch.ailang (now in the clean 001-132 sequence).

// Those showed the constructs in isolation; this one is the part

// where people go "oh, now I see it." A multi-axis decision tree

// where Fork and Branch alternate based on what question each level

// is actually asking.

//

// Scenario: combat-action resolver for a text adventure. A single

// player turn dispatches over six axes — six is the AiLang

// function-parameter limit, and it's plenty for a real decision tree:

//

// action : attack | defend | cast | item | flee (Branch 5)

// in_combat? : yes/no (Fork)

// target_alive? : yes/no (Fork)

// spell_school : 0=none | 1=offensive | 2=heal | 3=util (Branch)

// item_kind : 0=none | 1=weapon | 2=potion | 3=scroll(Branch)

// hp_low? : yes/no (Fork)

//

// Shared scenario state lives in a FixedPool so the Show subroutine

// can read it and the driver code can write it — the canonical

// AiLang pattern for "this data is visible across call sites."

// Plain top-level variables don't reliably cross the SubRoutine

// boundary for mutable state; FixedPool gives them a named home.

//

// In C you'd write the dispatcher as a switch-over-action containing

// if-else chains containing nested switches — three kinds of syntax

// for three kinds of dispatch, plus `break` ceremony everywhere. In

// AiLang each level uses the construct whose NAME matches the

// question being asked: Branch for "which value," Fork for "is this

// true." Reading top-to-bottom, the intent is visible without

// decoding.

Function.ResolveAction {

Input: action: Integer // 1=attack 2=defend 3=cast 4=item 5=flee

Input: in_combat: Integer // 0/1

Input: target_alive: Integer // 0/1

Input: spell_school: Integer // 1=offensive 2=heal 3=util (0 = n/a)

Input: item_kind: Integer // 1=weapon 2=potion 3=scroll (0 = n/a)

Input: hp_low: Integer // 0/1

Output: Integer

Body: {

outcome = 99

Branch action {

Case 1: { // ─── ATTACK ────────────────────

Fork in_combat TrueBlock: {

Fork target_alive TrueBlock: {

outcome = 10 // strike lands

} FalseBlock: {

outcome = 11 // target already dead

}

} FalseBlock: {

outcome = 12 // not in combat

}

}

Case 2: { // ─── DEFEND ────────────────────

Fork in_combat TrueBlock: {

outcome = 20 // shield up

} FalseBlock: {

outcome = 21 // defending nothing

}

}

Case 3: { // ─── CAST ──────────────────────

Branch spell_school {

Case 1: { // offensive

Fork in_combat TrueBlock: {

Fork target_alive TrueBlock: {

outcome = 30 // fireball lands

} FalseBlock: {

outcome = 31 // wasted on corpse

}

} FalseBlock: {

outcome = 32 // combat spell OOC

}

}

Case 2: { // healing

Fork hp_low TrueBlock: {

outcome = 33 // heal meaningful

} FalseBlock: {

outcome = 34 // heal wasted

}

}

Case 3: { // utility

outcome = 35 // light / detect

}

Default: { outcome = 36 } // unknown school

}

}

Case 4: { // ─── USE ITEM ─────────────────

Branch item_kind {

Case 1: { // weapon

Fork in_combat TrueBlock: {

outcome = 40 // draw mid-fight

} FalseBlock: {

outcome = 41 // calm equip

}

}

Case 2: { // potion

Fork hp_low TrueBlock: {

outcome = 42 // saves life

} FalseBlock: {

outcome = 43 // wasted

}

}

Case 3: { // scroll

Fork in_combat TrueBlock: {

outcome = 44 // scroll in fight

} FalseBlock: {

outcome = 45 // utility scroll

}

}

Default: { outcome = 46 } // no such item

}

}

Case 5: { // ─── FLEE ──────────────────────

Fork in_combat TrueBlock: {

outcome = 50 // flee attempt

} FalseBlock: {

outcome = 51 // nothing to flee

}

}

Default: { outcome = 99 } // unknown action

}

ReturnValue(outcome)

}

}

// Pretty-print the outcome code.

Function.OutcomeMessage {

Input: code: Integer

Output: Address

Body: {

Branch code {

Case 10: { ReturnValue("weapon strike connects") }

Case 11: { ReturnValue("target is already dead") }

Case 12: { ReturnValue("nothing to attack") }

Case 20: { ReturnValue("you raise your shield") }

Case 21: { ReturnValue("defending against nothing") }

Case 30: { ReturnValue("fireball engulfs the enemy") }

Case 31: { ReturnValue("offensive spell wasted on corpse") }

Case 32: { ReturnValue("offensive spell fizzles OOC") }

Case 33: { ReturnValue("healing light restores you") }

Case 34: { ReturnValue("healing wasted — full HP") }

Case 35: { ReturnValue("utility spell takes effect") }

Case 36: { ReturnValue("unknown spell school") }

Case 40: { ReturnValue("draw weapon mid-fight") }

Case 41: { ReturnValue("equip weapon calmly") }

Case 42: { ReturnValue("potion saves your life") }

Case 43: { ReturnValue("potion wasted at full HP") }

Case 44: { ReturnValue("scroll blasts the enemy") }

Case 45: { ReturnValue("utility scroll triggers") }

Case 46: { ReturnValue("you don't have that item") }

Case 50: { ReturnValue("you flee!") }

Case 51: { ReturnValue("nothing to flee from") }

Default: { ReturnValue("invalid outcome") }

}

ReturnValue("??")

}

}

// Shared scenario state — declared next to the SubRoutine that reads it.

// FixedPool fields are Pool.field; Main writes them, Show reads them.

FixedPool.Scenario {

"label": Initialize=""

"action": Initialize=0

"in_combat": Initialize=0

"target_alive": Initialize=0

"spell_school": Initialize=0

"item_kind": Initialize=0

"hp_low": Initialize=0

}

SubRoutine.Show {

PrintMessage(Scenario.label)

PrintMessage(" -> ")

code = ResolveAction(Scenario.action, Scenario.in_combat,

Scenario.target_alive, Scenario.spell_school,

Scenario.item_kind, Scenario.hp_low)

PrintNumber(code)

PrintMessage(" : ")

PrintMessage(OutcomeMessage(code))

PrintMessage("\n")

}

SubRoutine.Main {

PrintMessage("=== combat action resolver ===\n")

// Attack paths

Scenario.label = "swing sword at orc "

Scenario.action = 1

Scenario.in_combat = 1

Scenario.target_alive = 1

RunTask(Show)

Scenario.label = "attack dead rat "

Scenario.target_alive = 0

RunTask(Show)

Scenario.label = "attack while OOC "

Scenario.in_combat = 0

RunTask(Show)

// Defend paths

Scenario.label = "defend vs goblin "

Scenario.action = 2

Scenario.in_combat = 1

RunTask(Show)

Scenario.label = "defend in peaceful "

Scenario.in_combat = 0

RunTask(Show)

// Cast paths

Scenario.label = "fireball at orc "

Scenario.action = 3

Scenario.in_combat = 1

Scenario.target_alive = 1

Scenario.spell_school = 1

RunTask(Show)

Scenario.label = "fireball at corpse "

Scenario.target_alive = 0

RunTask(Show)

Scenario.label = "heal at low HP "

Scenario.in_combat = 0

Scenario.spell_school = 2

Scenario.hp_low = 1

RunTask(Show)

Scenario.label = "heal at full HP "

Scenario.hp_low = 0

RunTask(Show)

Scenario.label = "utility spell "

Scenario.spell_school = 3

RunTask(Show)

// Item paths

Scenario.label = "equip sword mid-fight "

Scenario.action = 4

Scenario.in_combat = 1

Scenario.spell_school = 0

Scenario.item_kind = 1

RunTask(Show)

Scenario.label = "potion at low HP "

Scenario.in_combat = 0

Scenario.item_kind = 2

Scenario.hp_low = 1

RunTask(Show)

Scenario.label = "potion at full HP "

Scenario.hp_low = 0

RunTask(Show)

Scenario.label = "scroll in combat "

Scenario.in_combat = 1

Scenario.item_kind = 3

RunTask(Show)

// Flee paths

Scenario.label = "flee from combat "

Scenario.action = 5

Scenario.item_kind = 0

RunTask(Show)

Scenario.label = "flee from nothing "

Scenario.in_combat = 0

RunTask(Show)

}

RunTask(Main)

1

u/ApprehensivePipe1584 Oct 29 '26

Well this is different from that i still don't understand what you mean. This is attaching custom behavior to pattern matching.

0

u/Far-Championship-883 Oct 29 '26

look at how hard your syntax is to READ

1

u/ApprehensivePipe1584 Oct 29 '26
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;
}

I don't find it too hard to read. everything in main is just normal C/C++ style syntax plus rust-style match, Patterns are just defining names like an enum + struct style tags, and fits statements are literally just
thing if (cond);
like math. you just put the name of the parameter that is being checked (self in these cases) which is a pointer to the type (MS*/C*) then you just do normal conditions. its like inline if statements. thing if cond, like cases blocks in math, which is a big left brace then value if thing,...
such as:
⎧ 1, if x > 0

f(x) = ⎨ 0, if x = 0

⎩ -1, if x < 0

1

u/Far-Championship-883 Oct 30 '26

Yeah, c and c++ suck to fucking read

1

u/ApprehensivePipe1584 28d ago

It's just C style syntax that's just a preference of c/c++ style vs a modern rusty style

1

u/Far-Championship-883 28d ago

rust is also shit

1

u/ApprehensivePipe1584 28d ago

correct. I'm biased as a fan of C++, and C, and Zig, and despise Rust. I like C-Style syntax and am assuming you prefer a modern or like Haskell-like style?

→ More replies

1

u/DerekRss Oct 25 '26

Want to see what easy-to-use patterns can REALLY do? Check out SNOBOL4.

1

u/Pie-Lang Oct 26 '26

This is basically adding a customization point to pattern matching. I like it!