Untitled
Untitled
Basics........................................................................................................................................................2
Solutions...............................................................................................................................................3
1.1 Family Relations.......................................................................................................................3
1.1.1 Facts.....................................................................................................................................3
1.1.2 Predicates............................................................................................................................3
1.1.3 More Family Relations......................................................................................................3
Solution 1.1......................................................................................................................................4
1.2 A Simple Thought (Basic Inference)....................................................................................5
Solution 1.2......................................................................................................................................6
1.3 A Small World (Knowledge Representation)......................................................................6
Solution 1.3......................................................................................................................................6
2 Backtracking.......................................................................................................................................8
Solutions................................................................................................................................................8
2.1 Banknote Change.......................................................................................................................8
Solution 2.1........................................................................................................................................8
2.2 The 4-Color Problem..................................................................................................................9
Solution 2.2......................................................................................................................................10
2.3 Europe........................................................................................................................................10
Solution 2.3......................................................................................................................................12
3.1 Family Relations........................................................................................................................12
Solution 3.1......................................................................................................................................13
3.2 Factorial and Fibonacci............................................................................................................13
Solution 3.2......................................................................................................................................14
3.3 List Manipulations.....................................................................................................................14
Solution 3.3......................................................................................................................................15
3.4 A Complex Bicycle....................................................................................................................18
Solution 3.4......................................................................................................................................19
4.1 Means of Transport...................................................................................................................21
Solution 4.1......................................................................................................................................22
4.2 Problems with Insulators..........................................................................................................23
Solution 4.2......................................................................................................................................24
4.3 Resistor Network (Representation by Terms).......................................................................25
Solution 4.3......................................................................................................................................25
4.4 Digital Circuits (Representation by Clauses).........................................................................25
Solution 4.4......................................................................................................................................26
5.1 A Tennis Tournament...............................................................................................................27
Solution 5.1......................................................................................................................................28
5.2 Three Friends............................................................................................................................29
Solution 5.2......................................................................................................................................29
5.3 The N Queens Problem...........................................................................................................29
5.3.1 Generate and Test................................................................................................................29
5.3.2 Stepwise Generate and Test...............................................................................................31
6.1 Higher-order Predicates...........................................................................................................32
Solution 6.1......................................................................................................................................32
6.2 Memoization..............................................................................................................................33
Solution 6.2......................................................................................................................................34
6.3 User Interaction.........................................................................................................................35
Solution 6.3......................................................................................................................................35
6.4 Counter.......................................................................................................................................37
Solution 6.4......................................................................................................................................38
6.5 Transformation of Facts into List Arguments.........................................................................38
Solution 6.5......................................................................................................................................39
7.1 Car Driving in Switzerland........................................................................................................40
Solution 7.1......................................................................................................................................41
7.2 Two Canisters............................................................................................................................42
Solution 7.2......................................................................................................................................42
7.3 River Crossing...........................................................................................................................43
Solution 7.3......................................................................................................................................44
7.4 A Robot.......................................................................................................................................44
Solution 7.4......................................................................................................................................45
Basics
Solutions
1.1.1 Facts
man( m) /* m is man */
woman( w) /* w is woman */
1.1.2 Predicates
child( C, P) /* C is child of P */
son( S, P) /* S is son of P */
daughter( D, P) /* D is daughter of P */
uncle( U, N) /* U is uncle of N */
aunt( A, N) /* A is aunt of N */
woman( w) /* w is woman */
Define further family relations (e.g. niece, cousin, spouse (!), ...) und test them.
Remark:
The goal X \= Y with the predefined operator \= succeeds, if and only if X and Y are not equal (more
precisely: if they do not unify).
Solution 1.1
woman(queen_elizabeth_II).
mother(queen_elizabeth_II, prince_charles).
mother(queen_elizabeth_II, princess_anne).
mother(queen_elizabeth_II, prince_andrew).
mother(queen_elizabeth_II, prince_edward).
man(duke_philip).
father(duke_philip, prince_charles).
father(duke_philip, princess_anne).
father(duke_philip, prince_andrew).
father(duke_philip, prince_edward).
man(prince_charles).
father(prince_charles, prince_william).
father(prince_charles, prince_henry).
woman( princess_anne).
man( prince_andrew).
man( prince_edward).
woman(princess_diana).
mother(princess_diana, prince_william).
mother(princess_diana, prince_henry).
man(prince_william).
man(prince_henry).
/* 1.2 */
grandchild( Grandchild, G) :-
Solution 1.2
man( 'I')
4. What is to the left (right) of the table, ... (with respect to the center of the room)?
Hint:
Start with the reprentation of the queries and adapt the reprentation of the room correspondigly. Aim at a
concise program with few facts and many rules.
Solution 1.3
2 Backtracking
Solutions
What are the possibilities to change the 100 Swiss Franc bank note into smaller notes 10 Fr., 20 Fr. and
50 Fr.
that finds all solutions by backtracking, such that 10*N10 + 20*N20 + 50*N50 = 100. Save the possible
values for N10, N20, N50 as facts, e.g. N10 can be one of 0, 1, 2, .., 10.
Solution 2.1
c5( 0).
c5( 1).
c5( 2).
c2( 4).
c2( 5).
c1( 6).
c1( 7).
c1( 8).
c1( 9).
c1( 10).
Find an "admissible" coloring of a map such that all adjacent countries have different colors. It had been
conjectured for a long time that such a coloring is possible with only 4 colors. This conjecture was
formulated precisely by F. Guthrie already in 1852, but proved by K. Appel und W. Haken only in 1976
using a computer program.
Write a Prolog program that finds all admissible colorings of a given map using the colors red, blue,
yellow and green.
map( A, B, C, D, E) :-
adjacent( A, B),
adjacent( A, D),
adjacent( A, E),
adjacent( B, C),
adjacent( B, D),
adjacent( B, E),
adjacent( C, D),
adjacent( C, E),
adjacent( D, E).
The query
?- map( A, B, C, D, E)
Solution 2.2
map( A, B, C, D, E) :-
adjacent( D, E).
color( red).
color( bue).
color( yellow).
color( green).
2.3 Europe
Write a database with European countries specifying the area, the population and the neighbors of the
individual countries:
. . .
. . .
. . .
Solution 2.3
neighbor_d( S) :- /* Query 3 */
neighbors( d, S),
neighbor_ch1( S) :- /* Query 4 */
Extend the family relations of the Example 1.1 by the following predicates:
ancestor( A, X)
/* A is an ancestor of X */
descendant(D, X)
/* D is a descendant of X */
related( X, Y)
Solution 3.1
ancestor( A, X) :-
parent( A, X).
ancestor( A, X) :-
parent( P, X),
ancestor( A, P).
descendant( D, X) :-
child( C, X).
descendant( D, X) :-
child( C, X),
descendant( D, C).
related( X, Y) :-
ancestor( X, Y).
related( X, Y) :-
descendant( X, Y).
related( X, Y) :-
factorial( N, F)
Solution 3.2
factorial( 0, 1).
factorial( X, Y) :-
X > 0, X1 is X - 1,
fibo( 0, 1).
fibo( 1, 1).
fibo( X ,Y) :-
member(X, Y)
append( X, Y, Z)
rev( X, Y)
sum( X, S)
positive( X, Y)
flatten( X, Y)
/* Y is the list of the atomic elements that occur in the list X or in the
sublists of X.
Example:
set( X, Y)
Example:
sort_list( X, Y)
step k: X1, X2, ... Xk are already sorted as Y1, Y2, ... Yk
step k+1: Xk+1 is inserted into Y1, Y2, ... Yk at the correct position. */
Solution 3.3
member( X, [ X| _]).
member( X, [ _| Y]) :- member( X, Y).
min( X, Y, X) :- X =< Y.
min( X, Y, Y) :- X > Y.
list_length( [ _| Xs], L) :-
not_member( _, []).
not_member( X, [ Y| Ys]) :-
X \= Y, not_member( X, Ys).
X =< Y1.
element( c)
parts( C, E)
part( C, SubC)
element( saddle_area).
element( down_tube).
element( seat_tube).
element( seat_stay).
element( chain_stay).
element( saddle).
element( seat_post).
element( handlebar_grip).
element( head_tube).
element( schock_absorber).
element( fork).
element( spokes).
element( hub).
element( rim).
element( tire).
element( valve).
element( pedal).
element( crank_arm).
element( front_derailleur).
element( rear_derailleur).
element( chain).
element( front_brakes).
element( rear_brakes).
Solution 3.4
element( saddle_area).
element( down_tube).
element( seat_tube).
element( seat_stay).
element( chain_stay).
element( saddle).
element( seat_post).
element( handlebar_grip).
element( head_tube).
element( schock_absorber).
element( fork).
element( spokes).
element( hub).
element( rim).
element( tire).
element( valve).
element( pedal).
element( crank_arm).
element( front_derailleur).
element( rear_derailleur).
element( chain).
element( front_brakes).
element( rear_brakes).
parts( S, Parts) :-
structure( S, Cs),
part( S, C) :-
structure( S, Cs),
member( C, Cs).
part( S, K) :-
structure( S, Cs),
Replenish the "knowledge base" such that the following questions can be answered "correctly" and
"completely":
Which transport means are fast, which are eco-friendly, which are safe?
Solution 4.1
public( bus).
public( train).
public( airplane).
public( ship).
private( bicycle).
private( motorcycle).
private( car).
vehicle( bicycle).
vehicle( motorcycle).
vehicle( car).
vehicle( bus).
slow( bicycle).
eco-friendly( bicycle).
fast( car, mittel).
dangerous( car).
has_petrolengine( car).
has_petrolengine( bus).
has_electricmotor( train).
has_petrolengine( airplane).
slow( ship).
has_dieselmotor( ship).
Power transmission lines are attached to poles using insulators. Breakdowns of insulators can arise in
one of three ways:
1. A flashover arc is a breakdown and conduction of the air around the insulator, causing an arc
along the outside of the insulator. The flashover arc happens when the voltage is too high, e.g.
because of a lightning strike.
2. A puncture arc is a breakdown and conduction of the material of the insulator, causing an electric
arc through the interior of the insulator. The puncture arc happens when the insulator material is
faulty or has cracks. The insulator is damaged and must be replaced.
3. A surface leakage is an undesirable flow of current over the surface of the insulator. It happens
when the surface is dirty and wet. Composite polymer materials are prone to the surface leakage.
When creepage pathes are built the insulators must be replaced.
Solution 4.2
breakdown( flashover_arc).
breakdown( puncture_arc).
breakdown( surface_leakage).
A resistor network, in which the resistors are connected in series or in parallel, can be described by a
compound term. For example:
A resistor can be specified by the fact resistor( R, V), where V is the resistance of the resistor R
measured in Ohm, e.g. resistor( r1, 5). Define the predicate
res( N, R)
Solution 4.3
res( NW, R) :-
Hint:
... .
Simulate the circuit and check that this is a 1-bit full-adder, i.e.
adder_overflow( X, Y, Z, OF).
X, Y, Z are lists with N bits starting with the "most significant bit", Z is the sum of X und Y, and OF is the
overflow.
adder( X, Y, Sum).
where Sum is the sum of X und Y. It is a list with N+1 bits starting with the "most significant bit".
Solution 4.4
xor( I1, I2, X), and( I1, I2, A1), and( X, C_in, A2),
adder_overflow( X, Y, Z, OF).
or( 0, 0, 0).
or( 0, 1, 1).
or( 1, 0, 1).
or( 1, 1, 1).
xor( 0, 0, 0).
xor( 0, 1, 1).
xor( 1, 0, 1).
xor( 1, 1, 0).
and( 0, 0, 0).
and( 0, 1, 0).
and( 1, 0, 0).
and( 1, 1, 1).
On a sunny afternoon Adam, Bob, Carlo and Daniel play some tennis matches. The results are recorded
as Prolog facts:
category( S, 2)
category( S, 3)
Implement the predicate category( Player, Category) in two ways: once using only cut, and once using
only not. Test your implementations using the queries:
3. Does Adam belong to the category 1? Does he belong to the category 2? Does he belong to the
(nonexisting) category 4?
Solution 5.1
The three friends Bill, Daniel und Michael live in different cities and have different jobs. Each year they
meet in Zurich, where one of them lives, and take part in the Silvester run. This time Michael was faster
than his friend from Bern and Daniel was faster than the officer. The fastest was the sport teacher as
always. Daniel lives in Basel, and Michael is a doctor.
Who is who ?
Solution 5.2
friends( S) :-
N queens should be positioned on a NxN chessboard so that none of them can hit any other in one move.
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally.
The most straigtforward (but inefficient) solution is the "Generate and Test" method, that can be
implemented in Prolog in general as follows:
test( Solution).
solve( N, Position) :-
generate( N, Position),
test( Position).
The predicate generate generates by backtracking all possible positions of the queens and the
predicate test tests whether these positions are admissible.
A position can be represented e.g. as [p(1,D1), p(2,D2), ..., p(N,DN)]. The structure p(1,D1) means that a
queen is in the column 1 and in the row D1, etc. The possible values for D1, D2, ..., DN correspond to the
permutations of the numbers 1, 2, ...N.
queens( N, Pos) :-
list( 1, N, Columns),
test( Pos).
test( []).
test1( _, []).
list( N, N, [ N]).
The problem can be solved more efficiently by placing the queens in the columns step by step and
immediately testing whether the placement is admissible. If the placement is not admissible, the
backtracking in the columns is performed to get an admissible placement and only afterwards a new
column is tried. Try to implement this method.
A partial solution with admissible queens in the columns 1, 2, …, k is represented by two lists: a list B with
occupied rows and a list F with free rows.
queens( N, Pos) :-
queens_seq( N, RevPos),
reverse_list(RevPos, Pos).
queens_seq( N, Pos) :-
list( 1, N, Rows),
test_seq( D, Ds) :-
abolish( F, A)
/* erases all predicates with the main functor F and the arity A */
filter( P, X, Y)
Examples:
pos( X) :- X > 0.
neg( X) :- X < 0.
Solution 6.1
retract_all( _).
/* Testing */
assert_test :-
assert(test(1)),
assert(test(2)),
assert(test(a, b)).
pos( X) :- X > 0.
neg( X) :- X < 0.
6.2 Memoization
fibo( 0, 0).
fibo( 1, 1).
fibo( N, F) :-
N > 1,
N1 is N-1,
N2 is N-2,
F is F1 + F2.
This method is extremely inefficient because intermediate results are recomputed many times. Avoid this
deficiency by storing the intermediate results using assert.
Note: Another efficient method is the iterative computation (implemented by recursion). To this purpose
two additional arguments for F(N-1) and F(N-2) are introduced, F1 = F(N-1) and F2 = F(N-2). Consider
the iterative implementation in a procedural language:
F2 = 0
F1 = 1
for k = 2 to N do:
Sum = F2 + F1
F2 = F1
F1 = Sum
return F1
Solution 6.2
fibo( 0, 0).
fibo( 1, 1).
fibo( N, F) :-
N > 1, N1 is N - 1, N2 is N - 2,
/* Iterative solution */
Counter > 0,
Sum is F2 + F1,
F2_new = F1,
F1_new = Sum,
Counter1 is Counter - 1,
Result = F1.
fibo_iter(0, 0).
fibo_iter(1, 1).
fibo_iter(N, F) :-
N > 1,
Counter is N - 1,
fibo_iter(Counter, 0, 1, F).
Write a program for interactive querying the distance between two cities:
?- d( City1, City2).
...
Take the symmetry of the distance relation into account. If a distance is not known, the system should not
answer NO but it should request the distance from the user and store it for later usage.
?- d( zuerich, baden).
?- d( zuerich, bern).
Thank you. I confirm: The distance between zuerich and bern is 110 km.
?- d( zuerich, bern).
Solution 6.3
/* End Database */
distances :-
repeat,
read( Input),
process_input( Input), !.
d( X, Y, D) :- dist( X, Y, D).
d( X, Y, D) :- dist( Y, X, D).
process_input( exit) :- !.
nl, write( 'The distance between '), write( S1), write( ' and '),
write( S2),
distance( S1, S2, D) :- d( S1, S2, D), output( S1, S2, D), !.
process_answer( _, _, _, no).
process_answer( _, _, _, eof).
nl, write( '*** Invalid Input ***'), ask_user( S1, S2, D).
6.4 Counter
Implement a counter. A counter has a name and a value, and is manipulated using the following
operations:
init( C, V)
get( C, V)
inc( C)
dec( C)
del( C)
Example.:
⇒ V = 2
Solution 6.4
a(4).
a(1).
a(5).
a(3).
a(4).
a(1).
?- bag_of( b(c,X), a(X), B). ⇒ B = [[b(c, 4), b(c, 1), b(c, 5), b(c, 3),
b(c, 4), b(c, 1)]
The list B can contain duplicate elements. The order of the elements is irrelevant.
The predicate setof(X, P, S) is similar to bagof, but the list S is a proper mathematical set without
duplicate elements. Moreover, the list S is sorted according to the relation '<'. Example:
?- set_of( X, a(X), S). ⇒ S = [1, 3, 4, 5]
Solution 6.5
bag_of( X, P, _) :-
call( P),
asserta( found(X)),
fail.
bag_of( _, _, B) :-
collect( B, BB) :-
( X == mark -> BB = B
), !.
set_of( X, P, S) :-
bag_of( X, P, L),
sort1( L, S).
insert1( X, [ Y1| Ys], [ Y1| Zs]) :- X > Y1, insert1( X, Ys, Zs).
/* Test data */
a(4).
a(1).
a(5).
a(3).
a(4).
a(1).
which means that there is a route W from X to Y having the length L. W is the ordered list of the cities in
between starting with X.
Solution 7.1
L1 is L0 + DXY,
There are two canisters. The big one holds 7 liters, the small one 5 liters. How can we achieve 4 liters of
water in the big canister? Only the following actions are possible:
2. Empty a canister.
3. Pour the content of a canister into the other one until the former is empty or the later is full.
Write first a general method for problem solving and apply it afterwards to the specific problem of the two
canisters.
Solution 7.2
write_list( []).
/* Two Canisters */
goal( k( 4, _)).
Y1 is Y + X, Y1 =< 5.
X1 is X + Y - 5, X1 >= 0.
X1 is X + Y, X1 =< 7.
Y1 is X + Y - 7, Y1 >= 0.
A farmer with a sheep, a goat and a bag of hay wants to cross a river. He has a boat that provides place
only for him and one other object. He should not leave the sheep and the goat unsupervised with the hay.
How can he manage the crossing?
start_fl( f( farmer( L), sheep( L), goat( L), hay( L))) :- L = bank1.
goal( f( farmer( R), sheep( R), goat( R), hay( R))) :- R = bank2.
opposite( B, B1),
( P = sheep, S = B, S1 = B1, Z1 = Z, H1 = H ;
P = goat, Z = B, S1 = S, Z1 = B1, H1 = H ;
P = hay , H = B, S1 = S, Z1 = Z, H1 = B1 ;
P = none, S1 = S, Z1 = Z, H1 = H ),
safe( farmer( _), sheep( B), goat( B), hay( H)) :- opposite( B, H).
7.4 A Robot
A robot should shut a stopcock in a contaminated room. The robot stands at the door, while the stopcock
is in the opposite corner at the ceiling. He (it) can reach it only if he steps on a movable ramp that is at the
window. The robot can perform the following actions:
1. Walk around
Which actions should the robot perform in order to shut the stopcock?
state(
ramp( at_window),
stopcock( open)).
state(
ramp( in_corner),
stopcock( closed)).
Solution 7.4
position( Y), X \= Y.
position( Y), X \= Y.
position( at_door).
position( at_window).
position( in_corner).