MiRAY
MiRAY

Reputation: 195

Define predicate from following the rules Prolog

I'm new to Prolog and I would like to convert given rules to Prolog language.

I have to define a predicate p(X1, Y1, X2, Y2) ,where X1, Y1 are integers, and X2 and Y2 are obtained from X1, Y1 following these rules:

  1. if Y1 ≤ 0 and |X1|≤−Y1 then X2 is X1 + 1 and Y2 is Y1
  2. else if X1 > 0 and |Y1| < X1 then X2 is X1, and Y2 is Y1+1
  3. else if Y1 > 0 and −Y1 < X1 ≤ Y1 then X2 is X1−1, and Y2 is Y1
  4. else X2 is X1 and Y2 is Y1−1

Upvotes: 1

Views: 67

Answers (1)

brebs
brebs

Reputation: 4456

I'll provide a steer, here is rule 1:

p(X1, Y1, X2, Y2) :-
    Y1 =< 0,
    abs(X1) =< -Y1,
    % Cut, to prevent processing alternatives
    !,
    X2 is X1 + 1,
    Y2 is Y1.

Sample output in swi-prolog:

?- p(-3, -5, X2, Y2).
X2 = -2,
Y2 = -5.

Upvotes: 1

Related Questions