0

I'm new to prolog so the concept of unifying is still new, so bear with me.

I want something like:

pair(X,Y)

That works like this:

?- pair(4,Y).

Y = 4,

?- pair(3,Y).

Y = 0,

But I don't really know how to do this. I know you can use something like X mod 2 =:= 0 which is true or false, but I don't know how to make "if this than that" code in prolog's way.

false
  • 10,264
  • 13
  • 101
  • 209
  • 1
    Prolog predicates are about making logical statements. So you want `pair(X, 0)` to be true if.... something. And you want `pair(X, X)` to be true if.... something. – lurker Apr 27 '17 at 01:19
  • `Y #= (X+1) mod 2 * X.` using [tag:clpfd], or `Y is (X+1) mod 2 * X.` For an answer in general, see [this](http://stackoverflow.com/a/37057721/772868). – false Apr 27 '17 at 05:54

1 Answers1

0

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.

s0nata
  • 194
  • 1
  • 7