Does any language have a dedicated syntax for this?
Bourne-shell type languages (sh, bash, zsh, etc.) have it:
while
foo
condition
do
bar
done
To be clear, I'm answering on having a syntax that's specifically dedicated to this type of loop construct.
Other languages like Rust, Lisp-based languages, Ruby, Haskell, or even the same Bourne-shell based languages, will support very similar constructs by way of consequence from having a syntax that generically turns lists of statements into expressions. That enables their use in the loop condition, which is generally limited in most languages to an expression. In bash, that can look like this:
while {
foo
condition
}; do
bar
done
Ruby:
while (foo; condition)
bar
end
Haskell:
whileM (do { foo; condition }) $ do
bar
Common Lisp:
(while (progn (foo) (condition))
(bar))
JavaScript (not sure lambdas are fair, though):
while ((function () { foo; return condition; })()) {
bar;
}
The while
syntax in Bourne-shell type languages however, instead of taking a single command/expression for the condition, will take a list. From the bash manpage:
while list-1; do list-2; done
The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero.
This is why it requires the do
keyword to signify the end of one list and the start of the other.
I am aware that this doesn't show a significant functional difference if any for the language user. However, it is the only language I could think of that has a syntax dedicated to this as was asked, and I do think it's interesting to note, at least for this site, because having non-generic syntax rules like this does complicate the language. The idea of the return status of the last command being the return status of a list is not just documented where "lists" is documented, but also here where while
is documented. And that has a sort of avalanche effect, because then set -e
also has to make a special note on the lists used for while
conditions, despite set -e
not being about loops.
-e
Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword