# What is the most efficient way to define a Loop until function?

Mathematica has the While function which is very convenient when we need to process some code until the attainment of a certain state (identified with a condition). Personally, I also like very much the Loop-Until approach.

An advantage of the Loop body Until condition is that the body being performed first, it is not necessary to set initial values to the variables being tested in condition. In While, all the variables must be set so that the preliminary test can return a value.

I have this definition below but would like to know if there are more efficient ways to define a Loop.

Loop[body_, test_] := Block[{}, body; While[! test, body]]
SetAttributes[Loop, HoldAll]


Edit

With the nice comments of everyone, I updated the code so that a MaxIterations option can be given, and usage and error messages are provided:

Unprotect[Loop];
Loop::usage = "Loop[body, test] performs body then verify test until test returns True. Loop[body, test, MaxIterations-> i] sets a maximal number of iterations (default infinity).";
Loop::maxiter = "Maxiterations 1 reached. Aborting...";
Loop[body_, test_, opt___] := Block[
{res, currenti = 1, maxi = MaxIterations /. {opt} /. Options[Loop]},
body;
While[(!test) && (currenti<maxi),
res = body;
If[maxi == ++currenti, Message[Loop::maxiter, currenti]; Abort[]]
];
res
]
SetAttributes[Loop, HoldAll]
Options[Loop] = {MaxIterations -> Infinity};
Protect[Loop];


Here are two examples

n = 1;
Loop[Print[n]; ++n, n > 4]
n = 1;
Loop[Print[n]; ++n, n > 4, MaxIterations -> 2]

• I updated the answer. Jan 2, 2022 at 11:18
• I'll just add the obligatory reference: Alternatives to procedural loops and iterating over lists in Mathematica. Jan 2, 2022 at 15:02
• Another option is to set a boolean flag (OMG!) before you enter the loop, and then turn the flag off inside the loop when condition is met. As in keepRunning = True; While[keepRunning, ...... If[condition,keepRunning=False]]. Notice there is no no need to do Break[] now. This will run one time at least. This is how we used to program in the good old days :) Jan 2, 2022 at 17:40
• @Nasser: yes, indeed, the Loop structure was very popular with languages such as Pascal. I also find it more intuitive than the While. Your version is neat as well. What about performance in terms of computation times? Jan 2, 2022 at 19:10
• Jan 3, 2022 at 13:46

I tend to use

While[True,
body;
If[condition, Break[]]
]


but what you show is equally good. This is just an alternative.

Try to avoid procedural loops in Mathematica when you can.

This is of course not always possible, but we can define a functional equivalent of the concept. In IGraph/M, I have a utility function called IGTryUntil. IGTryUntil[cond][x] will keep evaluating x until cond[x] becomes True, then it returns x. One of the main use cases is rejection sampling: generate random objects until they satisfy a condition. For example, a random connected graph: IGTryUntil[ConnectedGraphQ][RandomGraph[{20,20}]].

If you are going to create a custom function for this, it does not matter that much if the implementation is not simple. It's the usage of the function that should be simple. You can see the implementation of IGTryUntil here:

https://github.com/szhorvat/IGraphM/blob/a65dceb5ab1135e77b496a05888aa94787d3be91/IGraphM/Utilities.m#L513

• "Try to avoid procedural loops..." Good point, we might use Loop[body_, test_] := Block[{res}, body; While[! test, res = body]; res] Jan 2, 2022 at 12:27
• Both answers were equally usefull. I had to make a choice... Jan 4, 2022 at 16:29

Here's a simpler version:

SetAttributes[Until,HoldAll]
Until[body_, test_] := While[body; !test]

• There should be a negation to test but yes, very elegant! Jan 2, 2022 at 18:06
• @DenisCousineau Thanks, I fixed the bug. However, did you want to use Until[body, test] or Until[test, body]? Jan 2, 2022 at 18:14