GolfScript 嵌套 while 循环

发布于 2024-09-26 23:45:30 字数 716 浏览 7 评论 0原文

Golfscript 中的嵌套 while 循环是否损坏,或者我不知道如何使用它们?

我想从 5 到 0 迭代 Q,并且对于每次迭代,从 10 到 0 迭代 Z。单个循环单独工作得很好,并且它们看起来是独立的(不依赖于操作之间的堆栈):

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

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

输出:

"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"

但是如果我将 Z 循环放入 Q 循环中,我得到奇怪的结果:

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

  Q 1- :Q;
}while

输出:

"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"

基于 Z 打印两次,似乎只有一个当前条件块,并且任何“while”的执行都会覆盖它。

无论如何,我如何在 Golfscript 中完成这一壮举?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初与友歌 2024-10-03 23:45:30

不幸的是,(唯一的)解释器似乎无法正确处理嵌套的 do/while/until 循环。该问题似乎仅在同时嵌套两个循环时出现,而不是在循环类型不同时出现。

例如:

{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"

奇怪的是我以前没有注意到这个错误。一般来说,如果适用的话,使用结构 { }%{ }/ 会比使用 do/while/until 循环更好。对于您的示例,最好使用:

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

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}/
}/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文