There are several ways to express a conditional statement in Prolog, besides using CLPFD (Constraint Logic Programming over Finite Domains):
1) make several statements, one for each case you are considering, and let Prolog execution mechanism find the one that is appropriate:
pair(X,Y) :- even(X), !, Y = X. % 'if X is even then Y = X'
pair(_,0). % 'else Y = 0'
In the second case here the unification is implicit, but in the first case it is explicit.
The _
symbol is a syntactic sugar for an 'anonymous variable', that is a variable for whose bindings we do not care and that we do not use.
The cut operator !
is used in the first clause to tell Prolog that it should not try to find other solutions for the Y
if the first clause succeeds (like, backtracking and trying the second clause):
% without cut | % with cut
?- pair(4,Y). | ?- pair3(4,Y).
|
Y = 4 ? ; | Y = 4 ? ;
|
Y = 0 ? ; % <- wrong behaviour! | no.
|
no |
2) use the (Condition -> ThenStatement ; ElseStatement)
if-then-else construct:
pair(X,Y) :- (even(X) -> Y = X ; Y = 0).
No cuts are allowed in the Condition
argument. The first solution of the Condition
is used.
3) some systems have the if/3
predicate, that is evaluated as if(Condition,ThenStatement,ElseStatement)
:
pair(X,Y) :- if( even(X), Y = X, Y = 0).
No cuts are allowed in the Condition
argument.