9. Negation and cut
This chapter is about saying "not", and about telling Prolog to stop looking for other answers.
Negation as failure
\+ Goal is true when Goal can't be proved.
Prolog doesn't know that my_app doesn't depend on lodash. It only fails to prove that it does. Prolog treats "not provable" as "false". This idea is called negation as failure, and it works well when the database has all the facts.
With negation, you can find the packages that nothing depends on, the roots of the tree.
root/1 gives my_app twice, because package/1 finds it twice. Chapter 10 shows how to collect the answers without duplicates.
Watch out for unknown values
\+ never gives values to variables. If the goal succeeds, \+ fails, and if the goal fails, there are no values to give. So \+ works as expected only when its variables already have values.
The second query is false., because some package depends on something, so depends(P, _) succeeds, and \+ fails at once. The rule is to generate first and use \+ after.
Not equal
X \= Y means \+ X = Y. It is true when the two terms can't be unified. It has the same trap as \+.
Here A and B already have values when \= runs, so it works. This fixes the exercise of chapter 3.
Cut
The cut, written !, removes choice points. When Prolog passes a cut, it forgets the other clauses of the same predicate, and the other answers of the goals before the cut in the same clause.
first_color/1 gives only red. After the cut, Prolog doesn't go back to color/1 for green and blue.
Cut to choose a clause
Cuts are often used to say "if this clause applies, don't try the others".
Without the cuts, classify(-5, C) would also give C = positive as a second answer, because the third clause matches anything.
The danger of cut
A cut changes the meaning of a predicate, not only its speed. Here is a common mistake.
The first query is right. But the second one says that the max of 5 and 3 is 3. The query doesn't match the head of the first clause, because X can't be both 5 and 3. So the cut is never reached, and the second clause says that the query is true.
Code with cuts often works only in one direction, with some arguments known. All the relations in chapters 2 to 6 worked in every direction. A cut can take that away. Use it only when you need it, and write a safe version when you can.
Now the head of the first clause accepts any Z, and the unification Z = X happens after the cut.
If then else
( Condition -> Then ; Else ) runs Then if Condition is true, or Else if it is not. It uses a cut inside, but it is easier to read.
once(Goal) gives only the first answer of Goal. first_color(C) above could be written as once(color(C)).
Try it
- Write
leaf(P), which is true for a package that depends on nothing. Make sure?- leaf(P).findsreactandrollupin the box below. - Write
max/3with->instead of a cut. - Write
abs_value(X, A)with->, without theabsfunction.