language icon indicating copy to clipboard operation
language copied to clipboard

"while-case" and "do-while-case"

Open munificent opened this issue 3 years ago • 5 comments

The patterns proposal adds a new "if-case" statement form for matching a single refutable pattern:

if (json case [int x, int y]) {
  print('Was coordinate array $x,$y');
} else {
  throw FormatException('Invalid JSON.');
}

Should we also support case inside while and do-while loops? I see no reason why not and it could sometimes be handy:

while (readNextLine() case [int x, int y]) {
  ...
}

do {
} while (readNextLine() case [int x, int y]);

munificent avatar Sep 29 '22 23:09 munificent

This is useful, but I'm going to move it to later because I don't want to keep throwing new stuff at the poor beleaguered implementers.

munificent avatar Nov 30 '22 02:11 munificent

With the do-while statement, though, it's quite surprising to have the declaration of x and y after the block where they are (presumably?) in scope. What's the value during the first iteration? ;-)

eernstg avatar Oct 25 '24 10:10 eernstg

OK, so maybe just while-case. :)

munificent avatar Nov 04 '24 22:11 munificent

Agree. Recently wished I had while-case.

But just allowing case as a general expression, with scope extending to the dominated true branch if used as a condition, would give us while for free. And allow it in do/while, but the variables can only be used in the test itself.

(That's why we need the full "fencepost" loop:

do { 
 ...
} while (e) {
 ...
} else {
  ...
} 

Where variables declared in the do part are also visible in the while and else parts (at least if there is no continue before their initialization), and pattern bound variables in the test condition are visible in the while part. A continue breaks the local block. Can I haz?)

lrhn avatar Nov 06 '24 06:11 lrhn

Just tried to use this again today and was sad when I remembered we didn't do it yet. :)

leafpetersen avatar Sep 04 '25 22:09 leafpetersen