views:

27

answers:

1

Are nested while loops broken in golfscript or do I not know how to use them?

I want to iterate Q from 5 to 0, and for each iteration, iterate Z from 10 to 0. The single loops work well separately, and they seem self-contained (not relying on the stack between operations):

5:Q;
{"Q:"Q+ p Q}
{
  Q 1- :Q;
}while

10:Z;{"Z:"Z+ p Z}{Z 1- :Z;}while

Output:

"Q:5"
"Q:4"
"Q:3"
"Q:2"
"Q:1"
"Q:0"
"Z:10"
"Z:9"
"Z:8"
"Z:7"
"Z:6"
"Z:5"
"Z:4"
"Z:3"
"Z:2"
"Z:1"
"Z:0"

But if I put the Z loop inside the Q loop, I get strange results:

5:Q;
{"Q:"Q+ p Q}
{
  10:Z;{"Z:"Z+ p Z}{Z 1- :Z;}while

  Q 1- :Q;
}while

Output:

"Q:5"
"Z:10"
"Z:9"
"Z:8"
"Z:7"
"Z:6"
"Z:5"
"Z:4"
"Z:3"
"Z:2"
"Z:1"
"Z:0"
"Z:0"

Based on Z printing out twice, it seems like there is only one current conditional block, and any execution of "while" overwrites it.

In any case, how would I accomplish this feat in golfscript?

+1  A: 

It looks like the (only) interpreter unfortunately doesn't handle nested do/while/until loops correctly. The problem seems to only arise when you have two of these loops of the same time nested, and not when the loops are different types.

For example:

{0do 1}do       #not an infinite loop, but it should be
{0{}while 1}do  #is an infinite loop as expected
{0{"i"p}while 1}{"o"p}while
     #not an infinite loop, outputs "i" instead of continuously outputting "o"

Strangely I haven't noticed this error before. Generally, using the constructs { }% and { }/ will be better than using do/while/until loops if they are applicable. For your example, it would be better to use:

6,-1%{:Q"Q: "\+p
 11,-1%{:Z"Z: "\+p}/
}/
Nabb