Search code examples
prologprolog-cut

Prolog: "if then else", using cut


This is an easy question: I've seen this example in a Prolog text book. It is implementing if-then-else using a cut.

if_then_else(P, Q, R) :- P, !, Q.
if_then_else(P, Q, R) :- R.

Can anyone explain what this program is doing, and why it is useful?


Solution

  • The most important thing to note about this program that it is definitely not a nice relation.

    For example, from a pure logic program, we expect to be able to derive whether the condition had held if we pass it the outcome. This is of course in contrast to procedural programming, where you first check a condition and everything else depends on the condition.

    Also other properties are violated. For example, what happens if the condition actually backtracks? Suppose I want to see conclusions for each solution of the condition, not just the first one. Your code cuts away these additional solutions.

    I would also like to use the relation in other cases, for example, suppose I want to detect superfluous if-then-else constructs in my code. These are solutions to queries similar to:

    ?- if_then_else(NoMatter, Same, Same).
    

    If if_then_else/3 were a pure relation, we could use it to answer such queries. As it is currently implemented, it yields incorrect results for such queries.

    See and if_/3 for more information.