www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.announce - TrapFlow - Pattern Matching Library

reply Zenw <zero.error.no.warning gmail.com> writes:
Hello!

I've created a pattern matching library for D. Still 
experimental, but might be an interesting approach.

https://github.com/Zero-error-no-warning/TrapFlow


```D
import trapflow;

// Basic usage
auto x = 10.flow!string
     .trap[5]("5")
     .trap[$ <= 4](" <= 4")
     .trap[10,12]("10 12")
     .trap[15 .. 20]("15 16 17 18 19")
     .trap[$]("other")
     .result;
// Result: "10 12"

struct Inner { int a; string b; }
struct Outer { Inner s; int t; }

auto x = Outer(Inner(3,"three"), 33).flow("default")
     .trap[$[$[1,"one"], $]]("case 1")
     .trap[$[$ , 22]]("case 2")
     .trap[$[$[$,"three"], 33]]("case 3")
     .result;
// Result: "case 3"

// FizzBuzz
foreach(idx; 1..10) {
     auto fizzbuzz = tuple(idx % 3, idx % 5).flow!string
         .trap[$[0,0]]("FizzBuzz")
         .trap[$[0,$]]("Fizz")
         .trap[$[$,0]]("Buzz")
         .trap[$](idx.to!string)
         .result;
}
```


Looking forward to feedback :)
Nov 09
parent reply monkyyy <crazymonkyyy gmail.com> writes:
On Sunday, 9 November 2025 at 10:40:36 UTC, Zenw wrote:
 Hello!

 I've created a pattern matching library for D. Still 
 experimental, but might be an interesting approach.

 https://github.com/Zero-error-no-warning/TrapFlow
shouldnt you be using the lazy keyword in at least some of these headers?
Nov 09
parent reply Zenw <zero.error.no.warning gmail.com> writes:
On Sunday, 9 November 2025 at 17:36:27 UTC, monkyyy wrote:
 On Sunday, 9 November 2025 at 10:40:36 UTC, Zenw wrote:
 Hello!

 I've created a pattern matching library for D. Still 
 experimental, but might be an interesting approach.

 https://github.com/Zero-error-no-warning/TrapFlow
shouldnt you be using the lazy keyword in at least some of these headers?
You're absolutely right, I completely forgot about using `lazy` in `opCall`. Thanks a lot! It would be even better if the `$` symbol could be used inside a function literal in `opIndex`...
Nov 10
parent monkyyy <crazymonkyyy gmail.com> writes:
On Monday, 10 November 2025 at 10:35:42 UTC, Zenw wrote:
 On Sunday, 9 November 2025 at 17:36:27 UTC, monkyyy wrote:
 On Sunday, 9 November 2025 at 10:40:36 UTC, Zenw wrote:
 Hello!

 I've created a pattern matching library for D. Still 
 experimental, but might be an interesting approach.

 https://github.com/Zero-error-no-warning/TrapFlow
shouldnt you be using the lazy keyword in at least some of these headers?
You're absolutely right, I completely forgot about using `lazy` in `opCall`. Thanks a lot! It would be even better if the `$` symbol could be used inside a function literal in `opIndex`...
opDollar can be thinly lowered to a type ```d import std; struct foo{ struct dollar{} auto opDollar()=>dollar(); int opSlice(int,dollar)=>1; int opSlice(dollar,int)=>2; } unittest{ foo bar; bar[1..$].writeln; bar[$..1].writeln; } ```
Nov 10