[ Control | Reference Manual | Alphabetic Index ]

+Condition -> +Then ; +Else

Conditional construct - succeeds if Then succeeds for the first solution of Condition, or if Condition fails and Else succeeds.
Condition
Atom or compound term.
Then
Atom or compound term.
Else
Atom or compound term.

Description

The conditional (if-then-else) construct. First Condition is called and if this succeeds any further solutions of Condition are cut and Then is called. Else is never executed in this case regardless of the outcome of Then.

If Condition fails, Else is called. In this case, Then is never executed.

It is allowed, but not recommended to use ->/2 without ;/2 as

   ( Condition -> Then )
   
because this is equivalent to
   ( Condition -> Then ; fail )
   
which is sometimes considered unintuitive. If this behaviour is really wanted, it can be expressed more clearly by
   once Condition , Then
   

The more common idiom, where nothing is to be done in the else-case, must be written like this, using true/0:

   ( Condition -> Then ; true )
   

Also note that a !/0 inside Condition only has a local effect in Condition. If a !/0 appears in Then or Else, it cuts through the whole construct.

Since ->/2 and ;/2 have a lower precedence than ,/2, the whole construct should always be enclosed in parentheses:

    ( Condition ->
        Then
    ;
        Else
    )
    

Modules

This predicate is sensitive to its module context (tool predicate, see @/2).

Fail Conditions

Fails if Condition succeeds and Then fails, or if Condition and Else fail

Resatisfiable

Resatisfiable if Condition succeeds and Then is resatisfiable, or Condition fails and Else is resatisfiable

Exceptions

(4) instantiation fault
One of the arguments is not instantiated.
(5) type error
One of the arguments is neither an atom nor a compound term.

Examples

Success:
      % Then-branch executed
      ?- X = 1, ( X == 1 -> write(a) ; write(b) ).
      a
      X = 1
      Yes (0.00s cpu)

      % Else-branch executed
      ?- X = 2, ( X == 1 -> write(a) ; write(b) ).
      b
      No (0.00s cpu)

      % the Condition is cut, the Then-branch isn't
      ?- ( member(X,[1,2]) -> member(Y,[a,b]) ; member(Y,[c,d]) ).
      X = 1
      Y = a
      Yes (0.00s cpu, solution 1, maybe more)
      X = 1
      Y = b
      Yes (0.03s cpu, solution 2)

See Also

; / 2, ! / 0, *-> / 2