Database The Prolog Way
Written by Mike James   
Friday, 18 February 2022
Article Index
Database The Prolog Way
Begin Prolog
Search
The Program

The complete program is:

adjacent(edgware_road,paddington,district,1).
adjacent(paddington,bayswater,district,1).
adjacent(bayswater,nottinghill_gate,district,1).
adjacent(paddington,warwick_avenue,bakerloo,1).
adjacent(warwick_avenue,maida_vale,bakerloo,1).

next(X,Y,L):-adjacent(X,Y,L,_).
next(X,Y,L):-adjacent(Y,X,L,_).
direct_connect(X,Y,L,S,F):-
                next(X,Z,L),
                not(member(Z,S)),
                direct_connect(Z,Y,L,[Z|S],F).
direct_connect(X,Y,L,S,[Y|S]):- next(X,Y,L).
one_change(X,Y,L,F):-
                direct_connect(X,Z,L,[X],F1),
                direct_connect(Z,Y,L2,[Z|F1],F),
                L\=L2.
exist(X):-next(X,_,_).
member(X,[X|_]).
member(X,[_|T]):-member(X,T).
route(X,Y,F):-exist(X),exist(Y),
              direct_connect(X,Y,_,[X],F),
              write('Direct Connection'),nl,
              revwrite(F).
route(X,Y,F):-exist(X),exist(Y),
              one_change(X,Y,_,F),
              write('One change required'),nl,  
              revwrite(F).
revwrite([X]):-write(X).
revwrite([H|T]):-revwrite(T), write('->'),write(H).

 

 

If you are using the downloaded version enter all of the clauses into the editor and compile the program.

 

edit

 

If you are using the online version enter all of the clauses into the lefthand panel.   

Switch to the command line and enter:

route(nottinghill_gate,maida_vale,F).

Which produces the output (make sure you have table results ticked in the online version):

One change required
nottinghill_gate->bayswater->paddington->
 paddington->warwick_avenue
->maida_vale

Note the double occurrence of paddington is due to this being the change of line. 

I  admit that there is a bug that can cause time wasting inefficient journeys but you can fix it in no time at all.

I hope you enjoy using this route finder but if you get lost then my advice is to ask a policeman...

You can see that Prolog, and logic programming in general,require a big change in the way that you think about problems but it is often more effective than the apparently more direct procedural approach - something that is rarely stated but is very true.

If you try to extend the tube program you will almost certainly have many a frustrating hour or two as your brain retrains itself to think in terms of logical assertions, but you will have a lot of fun on the way to a working program.

 

mapicon

 

More Information

SWI Prolog

Related Articles

The Triumph Of Deep Learning

Robot cars - provably uncrashable?

<ASIN:0201403757>

<ASIN:0262514451>

<ASIN:0136070477>

<ASIN:0136070477>

<ASIN:193435659X>



Last Updated ( Friday, 18 February 2022 )