Just life
Just life

Reputation: 635

A simple prolog program

I want to implement the following function f(x,y) in Prolog

f(x,y) = a*x+b*y
where a = 1 if x > 0; a = -1 if x < 0; a = 0 if x = 0
and b = -1 if y > 0; b = 1 if y < 0; b = 0 if y = 0

For example,

f(2,-1) = 1*2 + 1*(-1) = 1
f(-2,-1) = (-1)*(-2) + (-1)*1 = 1
f(0,0) = 0*0 + 0*0 = 0

Any one can help?

Upvotes: 2

Views: 401

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74197

Shouldn't be much more complicated than this one-liner:

f(X,Y,Z) :- Z is sign(X)*X + -sign(Y)*Y

Upvotes: 0

repeat
repeat

Reputation: 18726

How about using the following formulation?

f(X,Y,Result) :-
   Result is abs(X) - abs(Y).

Let's run some queries:

?- f(0,0,0).
true.

?- f(-2,-1,1).
true.

?- f(2,-1,1).
true.

Upvotes: 1

user27815
user27815

Reputation: 4797

(Assuming you have a typo when defining y, y>0 not y>=0.) You need to define a relation between the input vars and the result of the function. Prolog can then answer yes/true with substitutions or no/false.

f(X,Y,Answer):-
    a_is(X,A),
    b_is(Y,B),
    Answer is A*X+B*Y.

a_is(X,1):-
    X>0.
a_is(X,-1):-
    X<0.
a_is(0,0).

b_is(Y,1):-
    Y<0.
b_is(Y,-1):-
    Y>0.
b_is(0,0).

Example:

?-f(2,-1,Answer).
Answer =1;
false.

Upvotes: 0

Related Questions