Prolog repeating symmetric relations

Consider this small program:

married(bill, hillary).
spouse(X, Y) :- married(X, Y); married(Y, X).
likes(X, Y) :- spouse(X, Y).

Now I want to evaluate the goal

?- likes(X, Y).
X = bill
Y = hillary ?;
X = hillary
Y = bill
yes 

Is there a way to prevent this symmetric relationship from repeating in the backward trace and keep symmetry for goals like ?- likes(hillary, X).?

+4
source share
2 answers

Here you can define spouse/2:

married(bill, hillary).
married(tom, mary).
married(sam, linda).

spouse(X, Y) :-
     \+ married(X, Y) -> married(Y, X) ; married(X, Y).

So, if there is no way to make married(X, Y)true, try married(Y, X). Otherwise married(X, Y).

| ?- spouse(X, Y).

X = bill
Y = hillary ? ;

X = tom
Y = mary ? ;

X = sam
Y = linda

(1 ms) yes
| ?- spouse(tom, Y).

X = tom
Y = mary

yes
| ?- spouse(X, tom).

X = mary
Y = tom

yes

The surface would show that the following, slightly simpler predicate may be equivalent, but it will not find all solutions:

spouse(X, Y) :-
     married(X, Y) -> true ; married(Y, X).

| ?- spouse(X, Y).

X = bill
Y = hillary ? ;

(1 ms) yes
| ?-

ADDITION

Based on the observation of Sergey:

| ?- Y = bill, spouse(X, Y).

X = hillary
Y = bill

yes

But:

| ?- spouse(X, Y), Y = bill.

no

, , spouse/2 , , , spouse(bill, hillary) spouse(hillary, bill) . bill, , hillary. , spouse(X, Y) X = bill Y = hillary, Y = bill .

, , @Sergey, , , .

+2

, , @SergeyDymchenko .

, . , ? :

?- spouse(X,Y), X @=< Y.
+2

Source: https://habr.com/ru/post/1538206/


All Articles