% farmer, wolf, cabbage, and goat problem % simplified from text by using a list instead of a stack. % a state is represented by state(Farmer, Wolf, Goat, Cabbage) % and w and e mean the west and east river banks move(state(X,X,G,C), state(Y,Y,G,C)):- opp(X,Y), not(unsafe(state(Y,Y,G,C))), writelist(['try farmer takes wolf ', Y, Y, G, C]), nl. move(state(X,W,X,C), state(Y,W,Y,C)):- opp(X,Y), not(unsafe(state(Y,W,Y,C))), writelist(['try farmer takes goat ', Y, W, Y, C]), nl. move(state(X,W,G,X), state(Y,W,G,Y)):- opp(X,Y), not(unsafe(state(Y,W,G,Y))), writelist(['try farmer takes cabbage ', Y, W, G, Y]), nl. move(state(X,W,G,C), state(Y,W,G,C)):- opp(X,Y), not(unsafe(state(Y,W,G,C))), writelist(['try farmer takes himself ', Y, W, G, C]), nl. move(state(F,W,G,C), state(F,W,G,C)):- writelist(['backtrack from ', F, W, G, C]), nl. unsafe(state(X,Y,Y,C)) :- opp(X,Y). unsafe(state(X,W,Y,Y)) :- opp(X,Y). opp(e,w). opp(w,e). path(X, X, L):- nl, write('The solution path is: '), nl, writelist(L). path(X, Y, L):- move(X, Z), not(member(Z, L)), path(Z, Y, [Z|L]). writelist([]). writelist([H|T]) :- write(H), write(' '), writelist(T). member(X,[X|_]). member(X,[_|T]:- member(X,T). go(Start, Goal):- path(Start, Goal, [Start]). test:- write('starting at state(e,e,e,e) '), nl, go(state(e,e,e,e), state(w,w,w,w)).