Cut (logic programming)


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 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. Green cuts are used to make programs more efficient without changing program output. For example:

gamble :- gotmoney,!.
gamble :- gotcredit, \+ gotmoney.

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

Red cut

A cut that is not a green cut is referred to as a cut, for example:

gamble :- gotmoney,!.
gamble :- gotcredit.

Proper placement of the cut operator and the order of the rules is required to determine their logical meaning. If for any reason the first rule is removed or moved after the second one, the second rule will be broken, i.e., it will not guarantee the rule.