Cut (logic programming)

{{short description|Feature in Prolog}}

{{multiple issues|

{{Tone|date=February 2009}}

{{Technical|date=August 2020}}

}}

The cut, in Prolog, is a goal, written as !, which always succeeds but cannot be backtracked. Cuts can prevent unwanted backtracking, which could add unwanted solutions and/or space/time overhead to a query.

The cut should be used sparingly. While cuts can be inserted into code containing errors, if a test is unnecessary because a cut has guaranteed that it is true, it is good practice to say so in a comment at the appropriate place.{{Cite book|last=Dyckhoff|first=Roy|url=https://books.google.com/books?id=ciQEHp39pAkC&q=Cut+(logic+programming)&pg=PA282|title=Extensions of Logic Programming: 4th International Workshop, ELP '93, St Andrews, U.K., March 29 - April 1, 1993. Proceedings|date=1994-05-20|publisher=Springer Science & Business Media|isbn=978-3-540-58025-6|language=en}}

Some programmers call the cut a controversial control facility[https://books.google.com/books?id=e-WpCAAAQBAJ&q=%22cut%22 Foundations of Logic Programming], Springer (2012). because it was added for efficiency reasons only and is not a logical formula.

Types

= Green cut =

The use of a cut that only improves efficiency is referred to as a green cut. Green cuts are used to make programs more efficient without changing program output. For example:

gamble(X) :- gotmoney(X),!.

gamble(X) :- gotcredit(X), \+ gotmoney(X).

This is called a {{color|green|green}} cut operator. The ! tells the interpreter to stop looking for alternatives; however, if {{code|gotmoney(X)}} fails it will check the second rule. Although checking for {{code|gotmoney(X)}} in the second rule may appear redundant since Prolog's appearance is dependent on {{code|gotmoney(X)}} failing before, otherwise the second rule would not be evaluated in the first place. Adding {{code|\+ gotmoney(X)}} guarantees that the second rule will always work, even if the first rule is removed by accident, changed, or moved after the second one.

= Red cut =

A cut that is not a green cut is referred to as a {{color|red|red}} cut, for example:

gamble(X) :- gotmoney(X),!.

gamble(X) :- gotcredit(X).

Proper placement of the cut operator and the order of the rules are required to determine their logical meaning. If for any reason the first rule is removed (e.g. by a cut-and-paste accident) or moved after the second one, the second rule will be broken, i.e., it will not guarantee the rule {{code|\+ gotmoney(X)}}.

= Harmful cut =

A cut which affects the correctness of the program is a harmful cut. For example:

min(X,Y,X) :- !, X =< Y. % the ! Is harmful because if Y

min(X,Y,Y) :- Y < X. % it will not let to continue to the second rule and will fail

References