Here’s a tedious loop pattern I find myself typing all the time:
control-code
while (condition)
body
control-code
endWhile
Two examples:
cur = cur.next
while (cur?)
fn(cur)
cur = cur.next
endWhile
Int32 num = input_Int32( "Enter a positive number: " )
while (num <= 0)
println( "Error, number must be positive!" )
num = input_Int32( "Enter a positive number: " )
endWhile
In fact, this is what I always attempt to use a repeat-until to solve before realizing it won’t work, like a jigsaw puzzle piece that never quite fits.
Perhaps as a result of my falling-out with repeat-until last night, I was extra sensitive to this issue this morning and resolved to do something about it. Ladies and gentlemen, I present… the reimagined do-while!
do
control-code #scope includes remainder of loop
while (condition)
body
endDoWhile
do
cur = cur.next
while (cur?)
fn(cur)
endDoWhile
do
Int32 num = input_Int32( "Enter a positive number: " )
while (num <= 0)
println( "Error, number must be positive!" )
endDoWhile
(Edit:)
After realizing that the “while” was ambiguous, I’ve reformulated this structure as a loop-while:
loop
cur = cur.next
continueIf (cur?)
fn(cur)
endLoop
It suddenly strikes me that this structure uses a mid-loop termination test, which is kinda neat.
November 28, 2008 at 10:22 am
There’s ambiguity with the “while”, ugh.
November 28, 2008 at 3:58 pm
Addendum: having said all that, I’m now gonna scrap it all again in favor of a manual escape:
loop
cur = cur.next
if (not cur?) escapeLoop
fn(cur)
endLoop
December 2, 2008 at 9:16 pm
You’re probably going to hate this.. In Ginger, the following is valid:
while
set num (input_Int32 “Enter a positive number:)
<= num 0
..
println “Error, number must be positive!”
The part before the ellipses is a code block that represents the condition and like most functional languages the last line gives the evaluated value of the entire block. The second block is the code body. The same thing can be written in Scheme though it looks uglier. Does this address the pattern?
I say you will hate it because I had one student look at some code I had written like this and I believe their response was – “what the hell is that?” I think I’ve stared at it enough that it actually looks elegant.
December 2, 2008 at 9:19 pm
And of course pre tags didn’t work so I lost the formatting.. Lets try this..
while
___set num (input_Int32 “Enter a positive number:)
___<= num 0
..
___println “Error, number must be positive!”
Now pretend the underscores are spaces..
December 2, 2008 at 9:51 pm
I like!