411 REFERENCE · Wikibooks
Prolog/Introduction/Answers
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
x
We'll use the following database, to represent a section of this family tree.
<nowiki>
man(sirius_black).
man(regulus_black).
man(orion_black).
man(cygnus_black).
man(pollux_black).
woman(bellatrix_black).
woman(andromeda_black).
woman(narcissa_black).
woman(walburga_black).
woman(druella_roisier).
woman(irma_crabbe).
parent(orion_black, sirius_black).
parent(walburga_black, sirius_black).
parent(orion_black, regulus_black).
parent(walburga_black, regulus_black).
parent(cygnus_black, bellatrix_black).
parent(druella_roisier, bellatrix_black).
parent(cygnus_black, andromeda_black).
parent(druella_roisier, andromeda_black).
parent(cygnus_black, narcissa_black).
parent(druella_roisier, narcissa_black).
parent(pollux_black, walburga_black).
parent(irma_crabbe, walburga_black).
parent(pollux_black, cygnus_black).
parent(irma_crabbe, cygnus_black).
</nowiki>
1. List the women in the database
<nowiki>
?- woman(Woman).
Woman = bellatrix_black ;
Woman = andromeda_black ;
Woman = narcissa_black ;
Woman = walburga_black ;
Woman = druella_rosier ;
Woman = irma_crabbe.
</nowiki>
2. List the children in the database
<nowiki>
?- parent(_, Child).
Child = sirius_black ;
Child = sirius_black ;
Child = regulus_black ;
...
</nowiki>
3. List all combinations of a father and his son.
<nowiki>
?- parent(Father, Son), man(Father), man(Son).
Father = orion_black,
Son = sirius_black ;
Father = orion_black,
Son = regulus_black ;
Father = pollux_black,
Son = cygnus_black ;
fail.
</nowiki>
4. which women have both a father and a son in the database?
<nowiki>
?- woman(Woman), parent(Father, Woman), parent(Woman, Son), man(Father), man(Son).
Woman = walburga_black,
Father = pollux_black,
Son = sirius_black;
Woman = walburga_black,
Father = pollux_black,
Son = regulus_black ;
fail.
</nowiki>
5. (Extra question) Can you think of a way to display those women that do not have a father listed in the database? Can you describe what you would need to write such a query??
You need to use negation.
Rules to put inside db:
<nowiki>
hasFather(Somebody):- parent(Father,Somebody), man(Father).
womenWithNoFather(Woman) :- woman(Woman), \+ hasFather(Woman).
</nowiki>
Query:
<nowiki>
?- womenWithNoFather(Woman).
Woman = druella_roisier ;
Woman = irma_crabbe ;
fail.
</nowiki>