任何语言都有while-else流程结构吗?

dot*_*hen 7 coding-style

考虑一下我经常使用的这种流程结构:

if ( hasPosts() ) {
    while ( hasPosts() ) {
        displayNextPost();
    }
} else {
    displayNoPostsContent();
}
Run Code Online (Sandbox Code Playgroud)

是否有任何具有可选else子句的编程语言,while如果从未输入while循环,则运行该语言?因此,上面的代码将成为:

while ( hasPosts() ) {
    displayNextPost();
} else {
    displayNoPostsContent();
}
Run Code Online (Sandbox Code Playgroud)

我发现有趣的是,许多语言都有do-while构造(在检查条件之前运行while代码一次)但我从未见过while-else解决过.根据在N-1块中运行的内容(例如try-catch构造)运行N代码块是先例.

我不确定是在这里发布还是在程序员上发帖.SE.如果这个问题更合适,那么请移动它.谢谢.

Rai*_*wig 6

这真是太深奥了.标准Common Lisp不提供它.但我们在名为ITERATE的库中找到它.

Common Lisp具有非常奇特的控制结构.有一个名为ITERATE的库,它类似于Common Lisp的LOOP宏,但具有更多的功能和更多的括号.

例:

(iterate (while (has-posts-p))
  (display-next-post)
  (else (display-no-posts-content)))
Run Code Online (Sandbox Code Playgroud)

它完全符合你的要求.在其他时候子句只运行一次,而条款是不正确的.

例:

(defparameter *posts* '(1 2 3 4))

(defun has-posts-p ()
  *posts*)

(defun display-next-post ()
  (print (pop *posts*)))

(defun display-no-posts-content ()
  (write-line "no-posts"))

(defun test ()
  (iterate (while (has-posts-p))
    (display-next-post)
    (else (display-no-posts-content))))
Run Code Online (Sandbox Code Playgroud)

有一些帖子:

EXTENDED-CL 41 > *posts*
(1 2 3 4)

EXTENDED-CL 42 > (test)

1 
2 
3 
4 
NIL
Run Code Online (Sandbox Code Playgroud)

没有帖子:

EXTENDED-CL 43 > *posts*
NIL

EXTENDED-CL 44 > (test)
no-posts
NIL
Run Code Online (Sandbox Code Playgroud)


Bas*_*tch 1

有些语言具有宏功能,使您能够定义此类内容。在CC++Common Lisp中你可以定义这样的宏。