10.2 If-then-else

Although our second try in using a cut in the max predicate to make it more efficient went wrong, the argument that we used when placing the cut in the first clause and then deleting the test X>Y from the second clause seems sensible: if we have already tested whether X is smaller or equal to Y and we have found out that it is not, we don't have to test whether X is greater than Y as well (we already know this).

There is a built-in predicate construction in Prolog which allows you to express exactly such conditions: the if-then-else construct. In Prolog, if A then B else C is written as ( A -> B ; C). To Prolog this means: try A. If you can prove it, go on to prove B and ignore C. If A fails, however, go on to prove C ignoring B. The max predicate using the if-then-else construct looks as follows:

max(X,Y,Z) :-
    (  X =< Y
    -> Z = Y
    ;  Z = X  

Patrick Blackburn, Johan Bos and Kristina Striegnitz
Version 1.2.5 (20030212)