Consider this flow structure which I happen to use often:
if ( hasPosts() ) {
while ( hasPosts() ) {
displayNextPost();
}
} else {
displayNoPostsContent();
}
Are there any programming languages which have an optional else clause for while, which is to be run if the while loop is never entered? Thus, the code above would become:
while ( hasPosts() ) {
displayNextPost();
} else {
displayNoPostsContent();
}
I find it interesting that many languages have the do-while construct (run the while code once before checking the condition) yet I have never seen while-else addressed. There is precedent for running an N block of code based on what was run in N-1 block, such as the try-catch construct.
I wasn't sure whether to post here or on programmers.SE. If this question is more appropriate there, then please move it. Thanks.
This is really esoteric. Standard Common Lisp does not provide it. But we find it in a library called ITERATE.
Common Lisp has extremely fancy control structures. There is a library called ITERATE, which is similar to Common Lisp's LOOP macro, but with even more features and more parentheses.
Example:
(iterate (while (has-posts-p))
(display-next-post)
(else (display-no-posts-content)))
It does exactly what you want. The else clause is only run once when the while clause was never true.
Example:
(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))))
There are some posts:
EXTENDED-CL 41 > *posts*
(1 2 3 4)
EXTENDED-CL 42 > (test)
1
2
3
4
NIL
There are no posts:
EXTENDED-CL 43 > *posts*
NIL
EXTENDED-CL 44 > (test)
no-posts
NIL
Python has else clauses on while and for, but they only run if the loop is never broken out of with break, return, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With