This section deals with Rules, a general way to state when a predicate is true.
So far we haven't really been doing any programming, just defining objects and their properties. The first step to programming in prolog is the use of rules. With rules we state that a predicate is true, provided that other predicates are true. A rule looks like this:
a :- b, c, d.
This says that a is true, if b, c and d are true. If we have the following database
a :- b, c, d. b. c. d :- e. e.
and we were to ask prolog if a is true
prolog would take the query (or goal) a and from that generate the sub-goals b, c and d. It can see that b and c are true, directly, as they are stated as facts, but d is only true if e is true, which leads to another sub-goal, e. Since e is also a fact, prolog will answer yes.
Rules with Variables
We can use predicates with terms as well.
car(corvette) :- haswheels(corvette), haswindows(corvette).
states that a corvette is a car if it has wheels and windows. This isn't a very useful statement, as we could also simply state that a corvette is a car with
We can however use variables in rules. This way we can state, for instance that anything is a car provided that it has wheels and windows:
car(A) :- haswheels(A), haswindows(A). haswheels(corvette). haswindows(corvette).
The first line states that for car(A) to be true, haswheels(A) and haswindows(A) need to be true. If prolog is asked whether a corvette is a car with
it will bind A to corvette, and get the sub-goals haswheels(corvette) and haswindows(corvette). If it can prove both these goals (which it can), then car(corvette) must be true. When using variables in a program it's important to note that a variable doesn't mean anything beyond the sentence it's in. If two sentences use the variable A, it's not the same variable. For example:
bird(A) :- hasfeathers(A). dog(A) :- barks(A).
The A in the first line simply shows that the term of the predicate bird needs to be the same as the term of the predicate hasfeathers, it has nothing to do with the A in the second line.
Now we can return to our original program and add some rules.
human(david). human(john). human(suzie). human(eliza). man(david). man(john). woman(suzie). woman(eliza). parent(david, john). parent(john, eliza). parent(suzie, eliza). father(X,Y) :- parent(X,Y), man(X). mother(X,Y) :- parent(X,Y), woman(X).
We can ask prolog who is the father of eliza:
?- father(X, eliza). X = john ; No
Or to list all fathers in the database and their respective children:
?- father(Father, Child). Father = david Child = john ; Father = john Child = eliza ; No
?- mother(Mother,Child). Mother = suzie Child = eliza ; No
If you've used any other programming language, you may be familiar with recursion, which refers to a function calling itself. Prolog is particularly well suited for recursion, although in our case, it will be a predicate referring to itself, rather than a function. Go to the next section to see how and why this is done.