dotancohen
dotancohen

Reputation: 31481

Does any language have a while-else flow structure?

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.

Upvotes: 7

Views: 236

Answers (4)

Rainer Joswig
Rainer Joswig

Reputation: 139261

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

Upvotes: 6

Faré
Faré

Reputation: 960

I am no particular fan of Common Lisp's LOOP macro, but it can do it with

(loop while (has-posts-p) do (display-next-post) finally (return (display-no-posts-content)))

No return necessary if you don't care about the value.

Upvotes: 0

Some languages have macro features to enable you to define such things. in C, C++, Common Lisp you could define such macros.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Python has else clauses on while and for, but they only run if the loop is never broken out of with break, return, etc.

Upvotes: 4

Related Questions