An idea; Coroutines

victoroak victoroak at victoroak.com
Tue Jan 16 19:05:56 UTC 2024


On Tuesday, 16 January 2024 at 14:20:41 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
> 
> [...]
>

I was playing around with the concept of generators in D. They 
could be used as a base for coroutines. For me it would generete 
code like this:

```
// string fizzBuzz(size_t n) {
// 	for(size_t i; i < n; i++) {
// 		if (i % 3 == 0 && i % 5 == 0)
// 			yield "fizz";
// 		else if(i % 3 == 0)
// 			yield "buzz";
// 		else if (i % 5 == 0)
// 			yield "fizzbuzz";
// 		else
// 			yield i.to!string;
// 	}
// }

struct Generator {
	// params
	size_t n;
	
	// state of the generator
	size_t state = 0;

	// locals
	size_t i = void;

	this(size_t n) {
		this.n = n;
	}

	bool next(ref string output) {
		switch(state) {
			case 0:
				goto LABEL0;
			case 1:
				goto LABEL1;
			default:
				assert(0);
		}

		
		LABEL0:
		for (i = 0; i < n; i++) {
			if (i % 3 == 0 && i % 5 == 0) {
				output = "fizz";
				state = 1;
				return false;
			} else if(i % 3 == 0) {
				output = "buzz";
				state = 1;
				return false;
			} else if (i % 5 == 0) {
				output = "fizzbuzz";
				state = 1;
				return false;
			} else {
				output = i.to!string;
				state = 1;
				return false;
			}
			LABEL1:	
		}
		state = 2;
		return true;
	}
}
```

I was thinking about this. The generated struct would probably 
need to allocate in the GC if any parameter to the generator 
function escaped. We could use something like scope but I don't 
know how reliable it would be to make it safe. I would really 
like to see some kind of stackless resumable function in D.


More information about the Digitalmars-d mailing list