2 ms·
Why is repeat/0 gross? It implements a failure-driven loop. If you want to force your code to backtrack over all choice points, that's what you need to do. You
by YeGoblynQueenne 4y ago
Why is repeat/0 gross? It implements a failure-driven loop. If you want to force
your code to backtrack over all choice points, that's what you need to do. You
can't get the same result with recursion. For instance if you have a
nondeterministic predicate (definition) and want to loop over all its results,
if you try to do that with recursion you'll just generate the same result at
every step of the recursion. Instead you want to iterate over all the choice
points.
To demonstrate its behaviour you can try that on the SWI-Prolog command line:
?- repeat, between(1,3,I).
I = 1 ;
I = 2 ;
I = 3 ;
I = 1 ;
I = 2 ;
I = 3 ;
I = 1 .
The ";" are where I ask for more results, the "." is where I said "stop". If you
tried to recurse around between(1,3,I), you'd get I bound to "1" every step
through the recursion- and still leave two choice points behind for every "1".
It's been a while since I used repeat/0, but in general it's used to write
generators. It usually makes more sense to use findall/3 and friends, which
simply iterate over choice points without adding new ones. For example:
?- findall(I, between(1,3,I), Is).
Is = [1, 2, 3].
People complain about dirty imperative constructs in Prolog like that all the
time, but they are very useful to a pragmatic programmer and everytime anyone
tries to "fix" Prolog by removing the impurities, they break it.