2

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

1 Answer 1

1

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}/
}/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.