Alternative to express "Commutativity" in Prolog?

as a newbie to Prolog, I found that the commutative expression in Prolog is not intuitive.

for example, if I want to express X and Y in one family, for example:

family(X,Y) :- married(X,Y); relative(X,Y); father_son(X,Y). 

I must also add the following to the definition: to make it β€œcommutative”:

  married(Y,X); relative(Y,X); father_son(Y,X). 

But we use Prolog because we want to write elegant code ... so I would hope to add only one line (instead of the three above) to the original:

  family(Y,X). 

Here is the DOT. this leads to termination! why is the prologue not so "logical"? and is there an alternative to this neat single-line expression that doesn't break?

Good weekend! Tue

+6
source share
2 answers

The problem with the family(X,Y) :- family(Y,X). lies in the fact that it unconditionally unites with itself at each level and continues recursively; there is no exit condition from this recursion.

You must swap the argument at a higher level:

 family(X,Y) :- is_family(X,Y); is_family(Y,X). is_family(X,Y) :- married(X,Y); relative(X,Y); father_son(X,Y). 

Alternatively, you can make the basic rules below symmetrical, where that makes sense:

 is_married(X,Y) :- married(X,Y); married(Y,X). is_relative(X,Y) :- relative(X,Y); relative(Y,X). 

Now you can rewrite the family rule as follows:

 family(X,Y) :- is_married(X,Y); is_relative(X,Y); father_son(X,Y); father_son(Y,X). 
+8
source

What about:

 relatives(X,Y) :- married(X,Y); relative(X,Y); father_son(X,Y). family(X,Y) :- relatives(X,Y); relatives(Y,X). 
+1
source

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


All Articles