0

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?

repeat
  • 18,496
  • 4
  • 54
  • 166
John
  • 303
  • 2
  • 12
  • Before you start, if you don't know what the cut (`!`) operator does, I suggest you look it up and study some of those examples. Then you should do a `trace` at the Prolog prompt and run the predicate with some examples. Very simple examples would be to do queries like, `if_then_else(true, X = 3, X = 4).` and `if_then_else(false, X = 3, X = 4)` and see what the order of execution is. At a high level, it would do what you would expect any if-then-else construct to do in any language, and it's useful for the same reasons. – lurker May 26 '16 at 15:37

1 Answers1

3

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.

Community
  • 1
  • 1
mat
  • 40,498
  • 3
  • 51
  • 78