Download Introduction to Prolog Programming
Transcript
48 Chapter 5. Backtracking, Cuts and Negation A cut is written as !. It is a predefined Prolog predicate and can be placed anywhere inside a rule’s body (or similarly, be part of a sequence of subgoals in a query). Executing the subgoal ! will always succeed, but afterwards backtracking into subgoals placed before the cut inside the same rule body is not possible anymore. We will define this more precisely a bit later. Let’s first look at our example about removing duplicate elements from a list again. We change the previously proposed program by inserting a cut after the first subgoal inside the body of the first rule; the rest remains exactly the same as before. remove_duplicates([], []). remove_duplicates([Head | Tail], Result) :member(Head, Tail), !, remove_duplicates(Tail, Result). remove_duplicates([Head | Tail], [Head | Result]) :remove_duplicates(Tail, Result). Now, whenever the head of a list is a member of its tail, the first subgoal of the first rule, i.e., member(Head, Tail), will succeed. Then the next subgoal, !, will also succeed. Without that cut it would be possible to backtrack, that is, to match the original goal with the head of the second rule to search for alternative solutions. But once Prolog went past the cut, this isn’t possible anymore: alternative matchings for the parent goal1 will not be tried. Using this new version of the predicate remove_duplicates/2, we get the desired behaviour. When asking for alternative solutions by pressing ; we immediately get the right answer, namely No. ?- remove_duplicates([a, b, b, c, a], List). List = [b, c, a] ; No Now we are ready for a more precise definition of cuts in Prolog: Whenever a cut is encountered in a rule’s body, all choices made between the time that rule’s head has been matched with the parent goal and the time the cut is passed are final, i.e., any choicepoints are being discarded. Let’s exemplify this with a little story. Suppose a young prince wants to get married. In the old days he’d simply have saddled his best horse to ride down to the valleys of, say, Essex2 and find himself the sort of young, beautiful, and intelligent girl he’s after. But, obviously, times have changed, life in general is becoming much more complex these days, and most importantly, our prince is rather busy defending monarchy against 1 2 With “parent goal” we mean the goal that caused the matching of the rule’s head. This story has been written with a British audience in mind. Please adapt to your local circumstances.