130 likes | 1.02k Views
Cool Programs in Prolog. CS 581 02/28/05 Flora Tan. A Graph Example. A connected graph. Vertices 1, 2, 3, 4, 5. Edges are the connecting lines. Find all paths between any two vertices. Easy to implement in Prolog. Prolog. List the edges as facts. edge(1,2). edge(1,3).
E N D
Cool Programs in Prolog CS 581 02/28/05 Flora Tan
A Graph Example • A connected graph. • Vertices 1, 2, 3, 4, 5. • Edges are the connecting lines. • Find all paths between any two vertices. • Easy to implement in Prolog.
Prolog • List the edges as facts. edge(1,2). edge(1,3). edge(1,4). edge(2,3). edge(2,5). edge(3,4). edge(3,5). edge(4,5).
Prolog • Add the rules. Options: • The edges are bi-directional. We could list out another eight edges as facts. Ex: edge(2,1), edge(3,1), edge(3,2), edge(4,1), edge(4,3), edge(5,2), edge(5,3), edge(5,4) • Use disjunction. connected(X,Y) :- edge(X,Y) ; edge(Y,X).
Prolog • Add the rules. Options (continue): • Alternatively, we could write this as two rules. connected(X,Y) :- edge(X,Y). connected(X,Y) :- edge(Y,X). • But we don’t want to do this. An infinite loop. edge(X,Y) :- edge(Y,X).
The rest of the code. path(A,B,Path) :- travel(A,B,[A],Q), reverse(Q,Path). travel(A,B,P,[B|P]) :- connected(A,B). travel(A,B,Visited,Path) :- connected(A,C), C \== B, not(member(C,Visited)), travel(C,B,[C|Visited],Path). Note the following: Conjunction Goal matching Recursive search List processing – reverse, member Accumulator Prolog
Base case travel(A,B,P,[B|P]) :- connected(A,B). Inductive case travel(A,B,Visited,Path) :- connected(A,C), C \== B, not(member(C,Visited)), travel(C,B,[C|Visited],Path). A path from A to B is obtained if A and B are connected. A path from A to B is obtained provided that A is connected to a vertex C different from B that is not on the previously visited part of the path, and one continues finding a path from C to B. Prolog
Running the program • Load the program into SWI-Prolog ?- [swi('demo/test')]. • Run the program. ?- path(1,5,P). P = [1, 2, 5] ; P = [1, 2, 3, 5] ; P = [1, 2, 3, 4, 5] ; P = [1, 4, 5] ; P = [1, 4, 3, 5] ;
Continue • The paths. P = [1, 4, 3, 2, 5] ; P = [1, 3, 5] ; P = [1, 3, 4, 5] ; P = [1, 3, 2, 5] ;
Why is this cool? • Graph search algorithms uses DFS/BFS and Adjacency List/Adjacency Matrix. • Prolog uses Depth First Search. • Other graphs examples: searching a maze, Dijkstra’s algorithm, graph coloring. • Coding in C is about 300 lines because we have to implement our own DFS and Adjacency List/Matrix.
Adjacency List – an array of pointers to linked lists 1 -> 2 -> 3 -> 4 2 -> 1 -> 3 -> 5 3 -> 1 -> 4 -> 5 4 -> 1 -> 3 -> 5 5 -> 2 -> 3 -> 4 Adjacency Matrix – a 2D array of integers 1 2 3 4 5 1 0 1 1 1 0 2 1 0 1 0 1 3 1 0 0 1 1 4 1 0 1 0 1 5 0 1 1 1 0 Adjacency List / Matrix
References • Programming in Prolog by W. F. Clocksin and C. S. Mellish. • Prolog tutorial • http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_15.html