简体   繁体   中英

How do I return unique results from a knowledge base in Prolog?

Complete prolog beginner here.

Let's say I have a prolog knowledge base which contains food and it's price, for example:

food(banana,99).

etc.

I'm trying to write a predicate that will return true if there are two or more items in the knowledge base that have the same price. The problem I'm encountering is that the query I've written:

multiple(X) :- food( _ ,X), food( _ ,X).

will return true if there is only one item in the database with price X. I understand what the problem is (that it's finding the same item twice and returning true), but I don't understand how to write a query that will find two or more unique items from food.

I've tried writing a 'unique' rule, as follows:

multiple(X) :- food(Y,X), food(Z,X), unique(Y,Z).
unique(Y,Z) :- Y /= Z

But that doesn't seem to work.

Thanks.

"Not-equal" is written \\= , not /= , in standard Prolog. Your solution should work:

?- [user].
|: food(milk, 10).
|: food(banana, 99).
|: food(strawberry, 40).
|: food(bread, 40).
|: % user://2 compiled 0.00 sec, 664 bytes
true.

?- food(X, Price), food(Y, Price), X \= Y.
X = strawberry,
Price = 40,
Y = bread ;
X = bread,
Price = 40,
Y = strawberry ;
false.

except that it may return duplicates. To get rid of those, use a query such as

food(X, Price), food(Y, Price), X @< Y.

which uses the term-ordering @< to make sure that the first term is "less than" the second (which implies they are not equal).

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