We've progressed from testing the truth of simple facts, to asking which things satisfy a single property. The next step is asking which things satisfy multiple properties.
The following program is simply both of our previous ones combined, creating a database of facts about tasty fruit and red fruit.
% Example 03 - Querying Multiple Properties
% simple facts
tasty(apple).
tasty(banana).
tasty(cherry).
% red fruit
red(apple).
red(cherry).
red(grape).
Querying With Multiple Properties
Let's ask which fruit are both tasty and red.
?- tasty(X), red(X).
The comma means “and”, or conjunction to be fancy. Prolog is being asked to find which X
satisfy both tasty(X)
and red(X)
at the same time.
Prolog works through each part of the query, progressing from left to right. Here it starts with tasty(X)
.
Finding tasty(apple)
at the top of the database leaves prolog with X=apple
. Prolog then tests to see if the next part of the query red(X)
is true. Because X
was set to apple
by the first part of the query, this part becomes red(apple)
. Prolog finds this in the database, so X=apple
is a valid answer.
After finding the first solution X=apple
, prolog backtracks to the point where X
is unbound and tries to search for other solutions.
Prolog finds that tasty(X)
unifies with the fact tasty(banana)
, which leaves X=banana
. Prolog then has to test the second part of the query red(X)
, which is now red(banana)
. It can't prove red(banana)
is true because this doesn't exist in the database, so it discards X=banana
as a potential answer. To be clear, X=banana
works for the first part of the query tasty(X)
, but it doesn't for the second part red(X)
, and this is why it is rejected.
Prolog backtracks and tries again. Following the same method, it finds X=cherry
satisfies tasty(X)
and red(X)
.
After this point there are no more facts in the database about things with the property tasty
so the search ends.
In this way prolog finds all the fruit which are both tasty and red.
?- tasty(X), red(X).
X = apple
X = cherry
The diagram below shows visually prolog's search for solutions for tasty(X),red(X)
.
Key Points
- Queries with multiple properties separated by a comma are conjunctions. Prolog will try to see if all these properties can be true at the same time.
- Prolog tries to satisfy each part of conjunctive query, progressing from left to right. Any variables that are set in one part retain their value into subsequent parts.