Wolfram Computation Meets Knowledge

RepeatUntil

Contributed by: Taliesin Beynon

Evaluate repeatedly an expression until a test is satisfied.

ResourceFunction["RepeatUntil"][body,test]

will evaluate body once, and then continue to evaluate it as long as test returns true.

Details and Options

RepeatUntil has the attribute HoldAll.

Examples

Basic Examples

Basic usage:

In[1]:=
i = 1; ResourceFunction["RepeatUntil"][i++, Print[i]; i < 5]; i
Out[1]=

Applications

Number of iterations to get an approximation:

In[2]:=
x = 1.0; n = 1; r = 1.0;
ResourceFunction["RepeatUntil"][r = (1 + x/n)^n; n++, If[Exp[x] - r > 10^-6, True, Break[]]]; {r, n}
Out[3]=

Searching sequences of primes:

In[4]:=
k = -1;
ResourceFunction["RepeatUntil"][
 k++, (Print[#]; PrimeQ[#]) &[4180566390 k + 8297644387]]

Properties and Relations

Equivalent structure using While:

In[5]:=
i = 1; While[i++; Print[i]; i < 5]; i
Out[5]=

Resource History