11.3.191 repeat/0   ISO



Succeeds immediately when called and whenever reentered by backtracking.


Generally used to simulate the looping constructs found in traditional procedural languages.

Generates an infinite sequence of backtracking choices. In sensible code, repeat/0 is hardly ever used except in repeat loops. A repeat loop has the structure

Head :-

The purpose is to repeatedly perform some action on elements that are somehow generated, e.g. by reading them from a stream, until some test becomes true. Usually, generate, action, and test are all determinate. Repeat loops cannot contribute to the logic of the program. They are only meaningful if the action involves side-effects.

The easiest way to understand the effect of repeat/0 is to think of failures as “bouncing” back off them causing re-execution of the later goals.

Repeat loops are not often needed; usually recursive procedure calls will lead to code that is easier to understand as well as more efficient. There are certain circumstances, however, in which repeat/0 will lead to greater efficiency. An important property of SICStus Prolog is that all runtime data is stored in stacks so that any storage that has been allocated during a proof of a goal is recovered immediately on backtracking through that goal. Thus, in the above example, any space allocated by any of the actions is very efficiently reclaimed. When an iterative construct is implemented using recursion, storage reclamation will only be done by the garbage collector.


In the most common use of repeat loops, each of the calls succeeds determinately. It can be confusing if calls sometimes fail, so that backtracking starts before the test is reached, or if calls are nondeterminate, so that backtracking does not always go right back to repeat/0.

Note that the repeat loop can only be useful if one or more of the actions involves a side-effect — either a change to the data base (such as an assertion) or an I/O operation. Otherwise you would do the same thing each time around the loop (which would never terminate).


Succeeds repeatedly until backtracking is terminated by a cut or an exception.



See Also


Send feedback on this subject.