Oct 31, 2003 ------------- - More on PROLOG - Using append in interesting ways - member - nextto - sublist - triple - reverse - bubblesort (fix this, it is giving spurious answers after finding the right one) - ancestor - order of clauses matter - left-recursion is bad, since Prolog uses DFS! - a halloween party with predicates - mutual recursion is bad, doesn't cause stack overflow, but infinite loop nevertheless Files used in this session /* function to append lists */ /* first two are the inputs, last is the appended list */ append([],X,X). append(X,[],X). append([X|Y],Z,[X|M]) :- append(Y,Z,M). /* function to find the last element of a list */ last(X,List) :- append(_,[X],List). /* function to check if X is a member of list List */ member(X,List) :- append(_,[X|_],List). /* function to check if X and Y are next to each other in a list L */ nextto(X,Y,L) :- append(_,[X,Y|_],L). /* function to check if X is a sublist of Y */ sublist(X,Y) :- append(_,X,W), append(W,_,Y). /* function to triple a list */ /* given [3] produce [3,3,3] as answer */ /* X when tripled gives list Y */ triple(X,XXX) :- append(X,X,XX), append(XX,X,XXX). /* function to reverse a list */ /* give X as input, Y is the reversed X */ reverse([],[]). reverse([A|B],Y) :- reverse(B,Z), append(Z,[A],Y). /* function to do bubblesort */ /* X when bubblesorted gives Y */ bubblesort(X,Y) :- append(M,[A,B|N],X), A > B, append(M,[B,A|N],S), bubblesort(S,Y). bubblesort(L,L). /* fix this above code yourself, so as to not give more answers after the correct one */ /* in ancestor(X,Y), Y is meant to be the ancestor of X */ /* order of predicate definitions matter */ /* beware of left recursion, as written below */ /* because Prolog uses depth-first search */ ancestor(X,X). ancestor(X,Y) :- ancestor(Z,Y), parent(X,Z). parent(amy,mark). trick(eggs). trick(toiletpaper). trick(mailboxbaseball). trick(pumpkinsmashing). treat(kitkat). treat(hersheys). treat(snickers). practice(oct31, eggs). practice(oct31, toiletpaper). meal(oct31, hersheys). niceday(X) :- classletsoffearly(X). classletsoffearly(X) :- niceday(X).