C
C#16mo ago
__dil__

✅ Introduce variable in `while` condition

Is it possible to achieve something like this? (pseudo-C#)
while (Computation() val when val != otherVal)
// You can use `val` here...
while (Computation() val when val != otherVal)
// You can use `val` here...
The idea is that the loop should go until the result of some computation does not match some predicate, and to also keep the result of the computation around in the loop. If not, how would you achieve a similar pattern?
7 Replies
Thinker
Thinker16mo ago
while (Computation() is var val && val != otherVal)
while (Computation() is var val && val != otherVal)
bit of a strange syntax ik is var val is a pattern which just declares a variable returns true
__dil__
__dil__OP16mo ago
Oh that's great, thanks 😄
reflectronic
reflectronic16mo ago
there is also the classic
T val;
while ((val = Computation()) != otherVal)
T val;
while ((val = Computation()) != otherVal)
Thinker
Thinker16mo ago
yikes
reflectronic
reflectronic16mo ago
it, admittedly, is not a one-liner
__dil__
__dil__OP16mo ago
I really don't like variable declarations without initialization, but yeah that's a good pattern to know too
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?