简体   繁体   中英

Prolog not unique elements in predicate call

In my Prolog script, I have defined:

mother(X,Y) :-
    parent_of(X,Y),
    female(X).

I then want to know if there are any mothers with more than two children, so I run:

mother(X,Y), mother(X,Z)

With the result:

X = pam,
Y = M, M = bob

Which has left me quite baffled.... I figured that if I add

not(Y = Z)

This will fix it, but am unsure as to why...

It looks like that you assumed that variables with different names can't have the same value. That's not true. You have to specify this explicitly (like in mathematics, for example, - variable X can have the same value as a different variable Y, unless you explicitly specify the opposite).

If you execute a query like

mother(X,Y).

The result would bring back mothers that have two children as well.

So if your database was something like

female(maria).
female(irini).
parent_of(maria,nick).
parent_of(maria,dario).
parent_of(irini,dewey).

and you executed the mother(X,Y). query, the result would bring back

1 ?- mother(X,Y).
X = maria,
Y = nick ;
X = maria,
Y = dario ;
X = irini,
Y = dewey.

So your result would have the mother (maria) that has two children.

If you only want a mother with two children, you should modify your mother query as:

mother(X,Y) :-
    parent_of(X,Y),
    parent_of(X,M),
    Y \= M,
    female(X).

The result of this query would be:

3 ?- mother(X,Y).
X = maria,
Y = nick ;
X = maria,
Y = dario ;
false.

( false means that Prolog did't find any more results).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM