do.while: Do While/Until Loops in R

do.whileR Documentation

Do While/Until Loops in R

Description

Allows for the do while/until loop syntax seen in other languages.

Usage

expr %while% cond
expr %until% cond

Arguments

expr

An expression in a formal sense. This is either a simple expression or a so-called compound expression, usually of the form { expr1 ; expr2 }. MUST be wrapped with do ( .. ).

cond

A length-one logical vector that is not NA. Other types are coerced to logical if possible, ignoring any class. MUST be wrapped with parenthesis.

Details

First, the code block expr is evaluated, and then the condition cond is evaluated. This repeats while/until the condition is TRUE. This contrasts from a while loop where the condition is evaluated before the code block.

break breaks out of a do while/until loop, next halts the processing of the current iteration and advances the looping index; exactly the same as a for, while, or repeat loop.

Value

NULL invisibly.

See Also

while

Do while loop

Examples

# Suppose you want a unique name for a temporary file (we'll ignore that
# `tempfile` exists for now). We can use a do while loop to create a new
# random name until a unique name is found.
do ({
    value <- sprintf("%x", sample(1000000000, 1))
    print(value)
}) %while% (file.exists(value))


## note that the following is equivalent:
# do ({
#     value <- sprintf("%x", sample(1000000000, 1))
#     print(value)
# }) %until% (!file.exists(value))


# Suppose you want a random number that is greater than one million (we'll ignore
# that `stats::runif` exists for now).
do ({
    value <- sample(1.01e+06, 1)
    print(value)
}) %until% (value > 1e+06)


## note that the following is equivalent:
# do ({
#     value <- sample(1.01e+06, 1)
#     print(value)
# }) %while% (value <= 1e+06)


# Finally suppose you wanted to ask the user for input, but wanted to make sure
# it was valid. Here, we'll say the input is valid if it is all numeric
# characters (ignore leading and trailing whitespace).
# Let's put a limit on it too, only ask a certain amount of times
count <- 0L
do ({
    value <- readline("Enter an integer: ")
    value <- gsub("^\\s+|\\s$", "", value)
    valid <- grepl("^[[:digit:]]+$", value)
    count <- count + 1L
}) %until% (count >= 5L || valid)
print(list(value = value, valid = valid, count = count))


## note that the following is equivalent:
# do ({
#     value <- readline("Enter an integer: ")
#     value <- gsub("^\\s+|\\s$", "", value)
#     valid <- grepl("^[[:digit:]]+$", value)
#     count <- count + 1L
# }) %while% (count < 5L && !valid)

ArcadeAntics/essentials documentation built on Nov. 7, 2024, 4:33 p.m.