Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - How can I compare the results that came from two or more different predicates?

Tags:

prolog

For example,

The first one is something like:

sum(X,Y,Result):- Result is X + Y.

The second one is:

times(X,Y,R):- R is X * Y.

Can I even define them like this? Also what should I do if I want to write a thing that compare the value of two results? When I try to do something like sum(X,Y,R1) > times(X,Y,R2), it doesn't allow me. I want to write a program that's true if R1 > R2. In this case, I want to get the sum of X and Y and the multiplication of X and Y, and find out which value is larger. How could I do that?

like image 909
xsx Avatar asked Mar 07 '23 18:03

xsx


1 Answers

You seem to be under the impression that a predicate returns something. A predicate however can only be true (the condition is satisfied, or variable can be unfied such that the predicate us satisfied), or false (the predicate is not satisfied, and unification can not satisfy it). A predicate can also error in case you call it the wrong way. But that is basically it: true, false (and error).

So it does not make sense to write something as sum(X,Y,R1) > times(X,Y,R2), since nor sum/3 nor times/3 return something.

The idea of Prolog is to unify variables. If you write sum(1,4,X) then after the predicate call, X will be unified with 5. So what you can do is write:

sum(X,Y,R1), times(X,Y,R2), R1 > R2.

This will however only work if X and Y are instantiated in the first place, since is/2 requires the expression on the right side to be (fully) grounded.

like image 70
Willem Van Onsem Avatar answered Apr 06 '23 05:04

Willem Van Onsem