Idea: Qualified jumps

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 14 18:09:29 UTC 2022


On Mon, Mar 14, 2022 at 05:33:29PM +0000, Quirin Schroll via Digitalmars-d wrote:
> #### Idea
> Imagine you have a loop that does multiple things slightly
> differently. You think about refactoring those similar parts into a
> single function that takes a few parameters and could even have a
> nice, descriplive name. And you can’t — because there's a pesky
> `return` or `break` statement that just wouldn't work when put into
> another function. How would it even work anyways? Well, how would it?
> It couldn’t ever work in a global-scope function, that’s for sure, but
> it could — in principle — work in a nested function or a lambda under
> some reasonable conditions.
[...]

This is a similar problem to the one already solved by opApply: have the
function return a value that indicates whether the containing loop
should continue executing or not. For example, when iterating over an
aggregate containing .opApply, the loop body is transformed such that
`continue;` becomes `return 0;` and `break;` becomes `return 1;`. The
loop implementation stops the loop if the delegate returns non-zero.

In a similar vein your refactored code could just replace a hoisted code
block with:

	if (refactoredCode(...)) break;

Depending on the circumstances you may need to further differentiate
between normal return and short-circuit `continue`, so you use a scheme
where 0 = normal return, 1 = break, -1 = continue. So you'd do:

	L1: foreach (...) {
		...
		switch (auto ret = refactoredCode(...)) {
			case 1: break L1;
			case -1: continue;
		}
		...
	}

Kinda verbose, I'll grant you that, but I'm sure you can think of ways
of making it more concise.


T

-- 
I think Debian's doing something wrong, `apt-get install pesticide', doesn't seem to remove the bugs on my system! -- Mike Dresser


More information about the Digitalmars-d mailing list