Cut (logic programming)
![]() | This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages)
|
The cut, in Prolog, is a goal, written as !, which always succeeds, but cannot be backtracked. It is best used to prevent unwanted backtracking, including the finding of extra solutions by Prolog and to avoid unnecessary computations.
The cut should be used sparingly. While cuts can be inserted into codes 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.
Some programmers call the cut a controversial control facility [1] because it was added for efficiency reasons only and is not a Horn clause.
Types
Green cut
A use of a cut which only improves efficiency is referred to as a green cut. For example:
gamble(X) :- gotmoney(X),!. gamble(X) :- gotcredit(X), \+ gotmoney(X).
This is called a green cut operator. The ! simply tells the interpreter to stop looking for alternatives. But you'll notice that if gotmoney(X) fails it will check the second rule. Checking for gotmoney(X) in the second rule seems useless since you already know that if Prolog is there then gotmoney(X) failed before, otherwise the second rule wouldn't be evaluated in the first place. However, by explicitly writing \+ gotmoney(X), you guarantee that the second rule will always work, even if the first one is removed by accident or changed.
Purpose(s):
- make program more efficient.
- do not change the output of the program.
Red cut
A cut that isn't a green cut is referred as a red cut, for example:
gamble(X) :- gotmoney(X),!. gamble(X) :- gotcredit(X).
You depend on the proper placement of the cut operator and the order of the rules to determine their logical meaning. If for any reason the first rule is removed (e.g. by a cut-and-paste accident), the second rule will be broken, i.e., it will not guarantee the rule \+ gotmoney(X).
References
- ^ Foundations of Logic Programming, Springer (1984).