4.2.3.3 If-Then-Else

As an alternative to the use of cuts, and as an extension to the disjunction syntax, Prolog provides the construct:

     (If -> Then ; Else)

This is the same as the if-then-else construct in other programming languages. Procedurally, it calls the If goal, committing to it if it succeeds, then calling the Then goal, otherwise calling the Else goal. Then and Else, but not If, can produce more solutions on backtracking.

Cuts inside of If do not make much sense and are not recommended. If you do use them, their scope is limited to If itself.

The if-then-else construct is often used in a multiple-branch version:

     (   If_1 -> Then_1
     ;   If_2 -> Then_2
         ...
     ;   /* otherwise -> */
         WhenAllElseFails
     )

In contexts other than as the first argument of ;/2, the following two goals are equivalent:

     (If -> Then)
     
     (If -> Then ; fail)

That is, the ‘->’ operator has nothing to do with, and should not be confused with, logical implication.

once/1 is a control construct that provides a “local cut”. That is, the following three goals are equivalent:

     once(If)
     
     (If -> true)
     
     (If -> true ; fail)

Finally, there is another version of if-then-else of the form:

     if(If,Then,Else)

which differs from (If -> Then ; Else) in that if/3 explores all solutions to If. This feature is also known as a “soft cut”. There is a small time penalty for this—if If is known to have only one solution of interest, the form (If -> Then ; Else) should be preferred.


Send feedback on this subject.