Nov 5, 2003 ------------- - More examples with Prolog - outputting text - write - writeln - nl (newline) - problems solved today - more tinkering with cuts - Tower of Hanoi - finding paths in graphs - Files for today: /* more practice with cuts : determine what each of back1, back2, and back3 will print */ back1 :- example(X), d(Y), write(X), write(Y), nl, fail. back2 :- example(X), !, d(Y), write(X), write(Y), nl, fail. back3 :- example(X), e(Y), write(X), write(Y), nl, fail. example(1). example(2). d(1). d(2). d(3). e(1) :- !. e(2). ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y). ancestor(X,X). parent(amy,bob). /* query is ancestor(X,bob) */ /* Try these various combos: ancestor(X,Y) :- parent(X,Z), !, ancestor(Z,Y). ancestor(X,X). parent(amy,bob). ancestor(X,Y) :- !, parent(X,Z), ancestor(Z,Y). ancestor(X,X). parent(amy,bob). ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y). ancestor(X,X) :- !. parent(amy,bob). */ /* move n disks from peg a to peg b using peg c as intermediary move(N,A,B,C) */ move(0,_,_,_) :- !. move(N,A,B,C) :- M is N-1, move(M,A,C,B), step(A,B), move(M,C,B,A). step(A,B) :- write('move a disk from peg '), write(A), write(' to peg '), write(B), nl. /* edge(X,Y) means there is a directed edge from X to Y */ edge(a,b). edge(b,c). edge(c,a). /* path(X,Y) is true when there is a directed path from X to Y */ /* have a third argument that keeps a running tally of nodes visited so far */ path(X,X,T). path(X,Y,T) :- edge(X,Z), notamember(Z,T), append([Z],T,T2), path(Z,Y,T2). /* I can go from X to Y through Z only if Z was not already visited in T */ notamember(X,[]). notamember(X,[Y|Z]) :- X\= Y, notamember(X,Z).