-
Notifications
You must be signed in to change notification settings - Fork 0
Learning Prolog
#Prolog Syntax Resources Used This source was useful because it describes unification and goes step by step how prolog tries to satisfy a goal. Probably the source I've used the most so far.
This brief introduction and this upenn page were helpful for just syntax, as of course was the SWI-prolog documentation.
#Some practice problems To get a bit more comfortable with syntax before tackling the river problem, I made:
- a genealogy searcher
- a customer/item/inventory database both of the previous two are from amzi. I also worked on the 4-color map problem but didn't finish it.
#River crossing assignment Problem: Your worldly possessions consist of a goat, a wolf, and a cabbage. You are travelling and have reached a river you must cross, but fortunately there is have a boat you can use. However it is a very small, unreliable boat, and although it can safely transport you and the wolf, the additional weight of the cabbage would be too much. Same with the goat, since it's a giant goat that weighs just as much as the wolf. You cannot leave the wolf and the goat alone together on one side of the river, nor can you leave the goat and the cabbage, for fear they would eat each other. How do you get all three of your possessions to the other side?
Prolog Code: mynot(l,r). mynot(r,l). upToOne((X,Y,),(X,Y,)). upToOne((,Y,Z),(,Y,Z)). upToOne((X,,Z),(X,,Z)).
step((P,C,G,W),(P1,C1,G1,W1)) :- safe(P1,C1,G1,W1), upToOne((C,G,W),(C1,G1,W1)), mynot(P,P1). %the person must change sides at least.
safe(P,C,G,W) :- mynot(W,G), mynot(G,C). %cases where the things in danger of eating eachother are on separate sides. safe(P,C,P,W). %any other safe case means the person and the goat must be on the same side, in which case the whereabouts of wolf and cabbage don't matter.
solve((r,r,r,r),[],_). solve(Y, [Z|X], Length1) :- step(Y,Z), Length1 > -1, Length2 is Length1 -1, solve(Z,X, Length2).
main :- solve((l,l,l,l),X,7), print([(l,l,l,l)|X]).
(I suspect there's a better way to display code than copying it directly onto the page...) (further explanation coming soon)