3 ms·
There's nothing wrong with the cut, or with getting more control over the execution of your program, which is what the cut gives you. You only get in trouble w
by YeGoblynQueenne 2y ago
There's nothing wrong with the cut, or with getting more control over the execution of your program, which is what the cut gives you.
You only get in trouble with the cut when you're just starting out and don't know what you're doing, and write your code in a way that it keeps entering infinite recursion or backtracking until the cows come home. At that point, because you don't yet know how to control those behaviours, you start sowing your code with cuts all over the place, which maybe stops the backtracking and infinite recursion (but maybe not) but it makes it an incomprehensible mess that still doesn't do what you want it to do.
As you grow and learn, you figure out how to control backtracking and recursion by ordering your program clauses and your clause literals in a sensible manner. At that point the use of the cut becomes so regular and formulaic that it might as well be added in by a pre-procesor.
For instance, you want a program that walks over a list and modifies an element if a condition holds, otherwise it continues, until the list is empty. You write:
% Program "skeleton" not meant to be executed but to expose a pattern
modify_list([],Xs,Xs):-
! % We're done, stop trying
modify_list([X|Xs],[Y|Acc],Bind):-
modify_element(X,Y)
,! Don't re-process X!
,modify_list(Xs,Acc,Bind).
modify_list([_X|Xs],Acc,Bind):-
modify_list(Xs,Acc,Bind).
In the example above, the two cuts have a very clear reason to be where they are (they stop unnecessary backtracking) which is immediately obvious by eyballing the program with sufficient experience. The vast majority of the use of cuts in the code you write once you have a bit of experience and understanding of how Prolog works is like that.