… -> … ; …functions as an if … then … else … facility. Example:
min(A, B, Min) :- A < B -> Min = A ; Min = B.
This version of
min (which, like the one
below, assumes that
B are numbers) says
A < B then unify
A otherwise unify
B". Possibly it is easier to understand a
two-rule version of
min(A, B, A) :- A <= B. min(A, B, B) :- B < A.
That is, the minimum of
A <= B; the minimum
B < A.
-> definition of
min does illustrate
the operation of
The code illustration has a rather procedural-programming
feel to it that may comfort beginning users of Prolog. Possibly
it should be avoided by them just for this reason! At least,
they should avoid using it when the only reason for using it is the
procedural feel. If use of
-> massively reduced the
length of the code, thereby simplifying it, that might be an
argument for using it.
The detailed semantics of
… -> … ; … is relatively
complex. The following description is quoted from the SWI Prolog
help text on
->/2construct commits to the choices made at its left-hand side, destroying choice-points created inside the clause (by
;/2), or by goals called by this clause. Unlike
!/0, the choice-point of the predicate as a whole (due to multiple clauses) is not destroyed. The combination
->/2acts as if defined by:If -> Then ; _Else :- If, !, Then. If -> _Then ; Else :- !, Else. If -> Then :- If, !, Then.Please note that
(If -> Then)acts as
(If -> Then ; fail), making the construct fail if the condition fails. This unusual semantics is part of the ISO and all de-facto Prolog standards.
Because of the cuts in this definition, the effect of
… -> … ; … can be unanticipated.
Beginning Prolog programmers should use it with as much care as a cut.
Programmers who already know a programming language with an if-then-else
construct (like C, C++, Java, ...) are likely to react to discovering
… -> … ; … with little cries of joy
and relief, and use it at every opportunity. A safer reaction is "if
you don't fully understand the semantics, don't use it."
COMP9414 and COMP9814 students at UNSW are forbidden to use it in any situation in which cuts are forbidden, primarily because we want you to learn how to manage without it (and cuts) where possible.