Prolog/Introduction/Answers

From Wikibooks, open books for an open world
< Prolog‎ | Introduction
Jump to: navigation, search

x[edit]

We'll use the following database, to represent a section of this family tree.

 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).

1. List the women in the database

 ?- woman(Woman).
 Woman = bellatrix_black ;
 Woman = andromeda_black ;
 Woman = narcissa_black ;
 Woman = walburga_black ;
 Woman = druella_roisier ;
 Woman = irma_crabbe.

2. List the children in the database

 ?- parent(_, Child).
 Child = sirius_black ;
 Child = sirius_black ;
 Child = regulus_black ;
...

3. List all combinations of a father and his son.

 ?- 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.

4. which women have both a father and a son in the database?

 ?- 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.


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:

hasFather(Somebody):-  parent(Father,Somebody), man(Father).
womenWithNoFather(Woman) :- woman(Woman), \+ hasFather(Woman).

Query:

?- womenWithNoFather(Woman).

 Woman = druella_roisier ;
 Woman = irma_crabbe ;

fail.