Language Reference/Terms/If-then-else

From wiki.visual-prolog.com

if-then-else can be used both as a statement and as an expression.

if-then-else (statement)

The if-then-eslse statement conditionally executes a group of statements.

IfThenElseTerm:
    if Condition then Term Elseif-list-opt Else-opt end if
 
Elseif:
    elseif Condition then Term
 
Else:
    else Term

The following two terms are equivalents.

if Cond1 then T1 elseif Cond2 then T2 else T3 end if
if Cond1 then T1 else
  if Cond2 then T2 else T3 end if
end if

Consider the schematic if then else term:

if Cond then T1 else T2 end if

First Cond is evaluated, if it succeeds then T1 is evaluated otherwise T2 is evaluated.

Cond is followed by an implicit cut, which turns:

  • a nondeterm condition into a determ condition and
  • a multi condition into a procedure.

Cond is a cut-scope (see Cut Scopes).

Example
clauses
    w(X) :-
        if X div 2 = 0 and X > 3 then 
            write("X is good")
        else
            write("X is bad"),
            nl
        end if,
        nl.

There are several things to notice about this example:

  • You can use "and" and "or" logical operators and other "complex" terms in all three sub-terms.
  • There is no comma before the keywords "then", "elseif", "else", and "end if".

For readability sake, we always recommend using "or" instead of ";". Likewise we also recommend using "and" (instead of ",") when it (as in the condition above) represents a logical "condition" rather than a "sequentation".

Leaving out the else-part is just shorthand for writing that else succeed, i.e.

if Cond then Term end if

is short-hand for

if Cond then Term else succeed end if

if-then-else (expression)

The if-then-else expression conditionaly evaluates excressions.

Syntactically it is same as the if-then-else statement, but and the terms in the branches must be expressions and the entire if-then-else expression will itself evaluate to a value.

The shorhand writings that leave out the else-part does not make sense for the expression.

Example
clauses
    w(X, Y) :-
        Min = if X < Y then X else Y end if,
        writef("The minimum is : %\n", Min).
The if-then-else expression above evaluates to X if X is less than Y else it evaluates to Y. Min is bound to the resulting value.