Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Paradigms
CSI2120
Jochen Lang
EECS, University of Ottawa
Canada
Logic Programming in Prolog
• Data structures
• Trees
– Representation
– Examples
– Binary search tree
• Graphs
– Representation
– Graph problems
b c
d e f g
2 3
treeA(X) :- X= 73
t(73,
t(31,
31 101
t(5,nil,nil),
nil),
t(101, 5 83
t(83,nil
t(97,nil,nil)),
nil)). 97
inorder(nil). 73
inorder(t(Root,Left,Right)) :-
inorder(Left),
write(Root), 31 101
write(' '),
inorder(Right).
5 83
?- treeB(X), inorder(X).
5 31 73 83 97 101
X = t(73, t(31, t(5, nil, nil), nil), 97
t(101, t(83, nil, t(97, nil, nil)),
nil)).
• Find all neighboring nodes and the connecting edge (use with edge/4
predicate).
neighbors(Graph,Node,Neighbors):-
setof((N,Edge),edge(Graph,Node,N,Edge),Neighbors).
– Define a graph
graphA(X) :- X=g([a,b,c,d,e,f],
[edge(a,b,3), edge(a,c,5), edge(a,d,7),
edge(e,f,1), edge(d,f,6)]).
– Example queries 5
?- graphA(X), neighbors(X,c,V). a c
3
V = [ (a, 5)].
e
b
?- graphA(X), neighbors(X,a,V). 7
1
V = [ (b, 3), (c, 5), (d, 7)].
6
d f
color(g(Ns,Edges),Colors,GC):-
generate(Ns,Colors,GC),
test(Edges,GC).
generate([],_,[]).
generate([N|Ns],Colors,[(N,C)|Q]):-
member(C,Colors),
generate(Ns,Colors,Q).
test([],_).
test([edge(N1,N2,_)|Ns],GC):-
member((N1,C1),GC),
member((N2,C2),GC),
C1\=C2,
test(Ns,GC).
?- graphA(X), color(X,[red,blue,white,green],V).
X = g([a, b, c, d, e, f], [edge(a, b, 3), edge(a,
c, 5), edge(a, d, 7), edge(e, f, 1), edge(d, f,
6)]),
V = [ (a, red), (b, blue), (c, blue), (d, blue),
(e, red), (f, white)] ;
X = …,
V = [ (a, red), (b, blue), (c, blue), (d, blue),
(e, red), (f, green)] ;
X = …,
V = [ (a, red), (b, blue), (c, blue), (d, blue),
(e, blue), (f, red)] ;
…
• Binary tree
– tree representation
– binary search tree
– insert an element
– delete an element
• Graphs
– graph representation
– graph search
– graph coloring
– labyrinth