PLOGHELP CONDITIONAL Chris Mellish
Revised by Kathryn Seifert October 1986
Operator which attempts goals conditionally
?- X -> Y; Z.
Keywords: or, conditional, conditional statement, arrow, operator,
symbol
POPLOG Prolog allows for a simple form of "conditional statement" in
Prolog programs. The goal:
?- X -> Y; Z.
means if X can be satisfied (only consider its first solution), attempt
Y, otherwise attempt Z.
Backtracking can generate alternative solutions for Y or Z (whichever is
chosen), but cannot generate alternatives to X. Here is a simple use of
the conditional to define the factorial of a number:
factorial(N1,FAC) :-
(N1=0 -> FAC=1; N2 is N1 - 1, factorial(N2,FAC2), FAC is FAC2*N1).
Note that this could also have been defined by:
factorial(0,1) :- !.
factorial(N,FAC) :-
N2 is N - 1, factorial(N2,FAC2), FAC is FAC2*N.
Indeed, it is often clearer to have several short clauses than a single,
deeply embedded clause. Note that if Y and Z are complex goals involving
disjunctions or more conditionals, it may be necessary to enclose them
in brackets.
The conditional is actually defined as a special case of the ';'
operator (see PLOGHELP * SEMICOLON). That is, (X -> Y; Z) is equivalent
to ;(->(X,Y),Z) and ';' is actually defined as if by:
(X -> Y); Z :- X, !, Y.
(X -> Y); Z :- !, Z.
X ; Y :- X.
X ; Y :- Y.
Note: The conditional cannot appear in a top-level goal.
-- RELATED DOCUMENTATION ----------------------------------------------
PLOGHELP * SEMICOLON
Operator to "or" two goals
PLOGHELP * SYMBOLS
Summary and index of HELP files for symbols used in Prolog
PLOGHELP * OPERATORS
Operator declarations made when the Prolog system is loaded