简体   繁体   中英

How to define a rule to require all in Prolog?

Having the knowledge base:

must_have(user, car, blue).
must_have(user, car, yellow).
must_have(user, bike, green).

How to define:

is_a_collector(X):-must_have(X, car, blue),
                   must_have(X,car,yellow),
                   must_have(X,bike,green).

without expliciting all the conditions?

I say this because the knowledge domain is large and I want to define a rule that catches many conditions.

I'm using Swi-Prolog.

For SWI-Prolog, you can use foreach/2 from library(aggregate) . Read the documentation on what exactly it does, but in effect, it creates the conjunction that you need.

?- foreach(must_have(X, _, _), X = user).
true.

?- foreach(must_have(X, _, _), X = foo).
false.

Or if you want to define a predicate,

is_a_collector(X) :- foreach(must_have(Y, _, _), Y = X).

However, @lurker is right that your question is a bit unclear. The proposed solution, too, feels somehow weird. At the very least, your database should contain other tables if you want to be able to state any queries that don't return truisms. At the moment, the first query above asks:

"Does every must_have/3 fact have user as its first argument?"

For that purpose, you could have used forall/2 directly, because you don't need a conjunction.

And what are you going to do with the answer to this?

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