Question

I have written this little program:

married(guy1, fem1).
married(guy2, fem2).

married_to(X,Y):-!, married(X,Y); married(Y,X).

Prints:

X = guy1,
Y = fem1 ;
X = guy2,
Y = fem2.

My purpose was to print the married couples but one time each. The above rule works for me, but I can't understand why! How does this work?

What's the difference with that: married_to(X,Y):- married(X,Y); married(Y,X).

This prints:

X = guy1,
Y = fem1 ;
X = guy2,
Y = fem2 ;
X = fem1,
Y = guy1 ;
X = fem2,
Y = guy2.
Was it helpful?

Solution 2

imagine you have the equivalent definition married_to(X,Y):- true, !, married(X,Y) ; married(Y,X).. If true were to fail, then we'd jump to the alternative, but since it's not going to, we're firmly on the consequent branch (of the disjunction).

IOW your code is

married_to(X,Y):- ( !, married(X,Y) ) ; ( married(Y,X) ).

and not

married_to(X,Y):- !, (  married(X,Y)  ;   married(Y,X) ).

It is actually equivalent to

married_to(X,Y):- !, married(X,Y). 
married_to(X,Y):-    married(Y,X).

Perhaps with this it is easier to get a "feeling" for what is going on here. Obviously, the second clause of the predicate is cut off. :) We're committed to the first clause, the second doesn't get a chance to work at all.

OTHER TIPS

The cut commits execution to the first branch on the disjunction. Thus your rule:

married_to(X,Y):-!, married(X,Y); married(Y,X).

is operationally the same as:

married_to(X,Y):-!, married(X,Y).

And, given that there are no other clauses for the married_to /2 predicate, equivalent to:

married_to(X,Y):- married(X,Y).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top