Prolog River Crossing - prolog

So I was given an assignment to try to solve this problem in Prolog, though the teacher has only covered the basics and this is essentially the only project in Prolog. I feel like I'm over thinking it and that he's just expecting too much as a first time Prolog program.
The problem is listed below, how should I go about solving this?
Write a Prolog program that solves the word problem below. As part of the solution, it should print all the crossings, with the paddler listed first.
Tom, Jack, Bill, and Jim had to cross a river using a canoe that held only two people.
In each of the three crossings from the left to the right bank of the river, the canoe had two persons, and in each of the two crossings from the right to the left bank, the canoe had one person. Tom was unable to paddle when someone else was in the canoe with him.
Jack was unable to paddle when anyone else but Bill was in the canoe with him. Each person paddled for at least one crossing.
This is what I have so far, though it "works", it doesn't make sure that everyone paddles at least once.
state(tom(Side),jim(Side),jack(Side),bill(Side),c(Side)).
initial(state(tom(l),jim(l),jack(l),bill(l),c(l))).
final(state(tom(r),jim(r),jack(r),bill(r),c(r))).
canoe(P):-P=p.
canoe(P,C):-P=p,C=c.
bad(state(tom(W),jim(X),jack(Y),bill(Z),c(C))):-
C=l,(W=c;X=c;Y=c;Z=c).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W1),jim(X),jack(Y),bill(Z),c(C1))):-
((canoe(W1),W=r,W=C,C1=m);(canoe(W),W1=l,W1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X1),jack(Y),bill(Z),c(C1))):-
((canoe(X1),X=r,X=C,C1=m);(canoe(X),X1=l,X1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X),jack(Y1),bill(Z),c(C1))):-
((canoe(Y1),Y=r,Y=C,C1=m);(canoe(Y),Y1=l,Y1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X),jack(Y),bill(Z1),c(C1))):-
((canoe(Z1),Z=r,Z=C,C1=m);(canoe(Z),Z1=l,Z1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W1),jim(X1),jack(Y),bill(Z),c(C1))):-
((canoe(X1,W1),W=l,W=X,W=C,C1=m);
(canoe(X,W),W1=r,W1=X1,W1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W1),jim(X),jack(Y),bill(Z1),c(C1))):-
((canoe(Z1,W1),W=l,W=Z,W=C,C1=m);
(canoe(Z,W),W1=r,W1=Z1,W1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X1),jack(Y1),bill(Z),c(C1))):-
((canoe(X1,Y1),Y=l,Y=X,Y=C,C1=m);
(canoe(X,Y),Y1=r,Y1=X1,Y1=C1)).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X1),jack(Y),bill(Z1),c(C1))):-
((canoe(Z1,X1);canoe(X1,Z1)),
Z=l,Z=X,Z=C,C1=m);
((canoe(Z,X);canoe(X,Z)),Z1=r,Z1=X1,Z1=C1).
move(state(tom(W),jim(X),jack(Y),bill(Z),c(C)),
state(tom(W),jim(X),jack(Y1),bill(Z1),c(C1))):-
((canoe(Y1,Z1);canoe(Z1,Y1)),
Y=l,Y=Z,Y=C,C1=m);
((canoe(Y,Z);canoe(Z,Y)),Y1=r,Y1=Z1,Y1=C1).
find(Path):-initial(S),rez(S,Path).
bkt(State,Path,[Path|State]):-final(State).
bkt(State,Path,Sol):-move(State,Next),not(bad(Next)),
not(member(Next,Path)),bkt(Next,[Path|Next],Sol).
rez(State,Sol):-bkt(State,[State],Sol).
start:-find(D),writef('%w\n',D).

(This answer may be too late, but since this is quite a classic problem/puzzle which has many many variants, I think it might still be useful to try and break the problem down a little bit.)
As yet stated in answers above, I think it might be a good idea to do some refactoring and try to write a simpler, more manageable model for this problem. What I mean with this is if someone asked you for example to 'quickly modify' your code to integrate let's say a fifth person to the puzzle, it wouldn't be much fun to refactor the code above.
You could start -this is just one approach to give you an idea- by encoding the configuration of the 4 men in a list, where we use an 'l' or 'r' to specify whether someone is located on the left or right side of the river bank. This would give us an initial state like so:
% Tom, Jack, Bill, and Jim are all on the left side
[l,l,l,l]
And we want to reach the goal state:
% Tom, Jack, Bill, and Jim are all on the right side
[r,r,r,r]
This gives us a model that is a lot easier to read/understand (imo).
We could then think some more about how we are going to encode actual transports between the river banks. We wrote our list configuration to specify which person is located where, so now we need a Prolog predicate that can transform one configuration into another. Let's say:
transport(StartState,[Persons],EndState)
Now, for the implementation, instead of explicitly matching on all possible moves (like you do in your current code), it's always a good idea to try and generalise what exactly is happening (the fun part in Prolog :) ).
Without writing too complicated code at once, we break the problem down into small pieces:
% Facts defining a crossing of the river
cross(l,r).
cross(r,l).
% Transport example for Tom
transport([X,Jack,Bill,Jim],[tom],[Y,Jack,Bill,Jim]) :- cross(X,Y).
As you can see, we now defined 'transport' in a very simple way: it is known that Tom will only cross the river on his own, so we use the cross fact to change his location. (Note that Jack, Bill and Jim are just variables stating either an 'l' or 'r' as indication on which river bank those people are located. Since Tom only crosses on his own, these variables will not change!). We could write this even more abstract and don't match specifically on 'tom', but I'm trying to keep it simple in this example.
Of course, we still need to express which crossings are valid and which aren't. From your question: "In each of the three crossings from the left to the right bank of the river, the canoe had two persons, and in each of the two crossings from the right to the left bank, the canoe had one person."
These conditions can very easily be coded using our 'transport' predicate since the initial state (first arg) tells us whether we are crossing from left to right, or vice versa and our 2nd argument specifies a list of which persons are crossing. In other words, the direction of the crossing and the amount of passengers are already known and it seems a bit trivial to write down these conditions here.
Next up: "Jack was unable to paddle when anyone else but Bill was in the canoe with him." Again, this is already very easily written together in our 'transport' (note that I've used wildcards to leave out information we don't care about for this particular condition, but of course, this will probably be different in the resulting end code. It is merely to give an example.):
% Transport example for Jack (Persons length = min 1 - max 2)
transport([_,_,_,_],Persons,[_,_,_,_]) :-
length(Persons,2),
( member(jack,Persons) ->
member(bill,Persons)
;
* other condition(s) *
).
% Alternative with pattern matching on Persons
transport([_,_,_,_],[A,B],[_,_,_,_]) :-
* if jack is A or B, then bill is the other one *
Another quick example: "Tom was unable to paddle when someone else was in the canoe with him."
% Tom cannot peddle in a team of 2
transport([_,_,_,_],Persons,[_,_,_,_]) :-
length(Persons,2),
\+ member(tom,Persons).
As you may have noticed, we have now almost completely broken down the problem in bits and pieces that can be very easily expressed in our model and we are not far from writing the actual solver. There are however enough code examples to be found online and I don't think it's necessary to work out any more of the code right here.
More inspiration can be found by searching for the classic Fox-Goose-Beans/Cabbage puzzle.
Good luck to everyone!

Related

Prolog rules for small environment

I have several Prolog facts indicating that something or someone is either a person, location or object. I have a clause go(person,location) that indicated that a person moves from where they are to the location given in the clause. However, when I ask the relevant query to find out if someone is at a certain location, Prolog responds with every person that was ever there according to the clauses. How do I go about writing a rule that says that if you are in one location you are by definition not in any of the others?
It appears that you left one important aspect out when modeling the situation as Prolog facts: When did the person go to the location?
Assume you had instead facts of the form:
person_went_to_at(Person, Location, Time).
then it would be pretty easy to determine, for any point in time, where everyone was, and where they moved to last (and, therefore, are now).
You probably need to add timing information to your facts. Imagine the following situtation:
go(dad, kitchen, bathroom).
go(dad, bathroom, garage).
go(dad, garage, kitchen).
Since Prolog is (more or less) declarative, in this case, the actual order of the facts in the file does not matter. So, you cannot conclude that dad is in the kitchen, he might have started from and returned to the garage. Even if you add some kind of starting predicate, say startLoc(dad, kitchen), this does not help with loops (e.g. when you add go(dad, kitchen, outside) to the above rules).
If you add timing information (and leave out the previous room, as this is clear from the timing information), this becomes:
go(dad, bathroom,1).
go(dad, garage,2).
go(dad, kitchen,3).
The actual numbers are not relevant, just their order. You can now get the latest location by ensuring that there is no later "go" command with dad:
location(X, Y) :- go(X, Y, T), \+ ( go(X, _, T2), T2 > T ).

Recursive reference in prolog

I meet some problem when I try to implement
friends(mia, ellen).
friends(mia, lucy).
friends(X,Y) :-
friends(X,Z),
friends(Y,Z).
and when i ask ?- friends(mia, X)., it run out of local stack.
Then I add
friends(ellen, mia) friends(lucy, mia)
I ask ?- friends(mia, X). ,it keeps replying X = mia.
I can't understand, why it is recursive?
First, two assumptions:
the actual code you wanted to write is the following one, with appropriate dots:
friends(mia,ellen).
friends(mia,lucy).
friends(X,Y) :-
friends(X,Z),
friends(Z,Y).
transivity holds: friends of friends are my friends too (I would rather model friendship as a distance: "A is near B" and "B is near C" does not necessarly imply "A is near C"). repeat's answer is right about figuring out first what you want to model.
Now, let's see why we go into infinite recursion.
Step-by-step
So, what happens when we ask: friends(mia,X) ?
First clause gives Y=ellen (you ask for more solutions)
Second clause gives Y=lucy (you ask again for more solutions)
Stack overflow !
Let's detail the third clause:
I want to know if friends(mia,Y) holds for some variable Y.
Is there a variable Z such that friends(mia,Z) holds ?
Notice that apart from a renaming from Y to Z, we are asking the same question as step 1 above? This smells like infinite recursion, but let's see...
We try the first two clauses of friends, but then we fail because there is no friends(ellen,Y) nor friends(lucy,Y), so...
We call the third clause in order to find if there is a transitive friendship, and we are back to step 1 without having progressed any further => infinite recursion.
This problem is analogous to infinite Left recursion in context-free grammars.
A fix
Have two predicates:
known_friends/2, which gives direct relationships.
friends/2, which also encodes transitivity
known_friends(mia,ellen).
known_friends(mia,lucy).
friends(X,Y) :- known_friends(X,Y).
friends(X,Y) :- known_friends(X,Z), friends(Z,Y).
Now, when we ask friends(mia,X), friends/2 gives the same answer as the two clauses of known_friends/2, but does not find any answer for the transitive clause: the difference here is that known_friends will make a little progress, namely find a known friend of mia (without recursion), and try to find (recursively) if that friend is a friend of some other people.
Friends' friends
If we add known_friends(ellen, bishop) :-) then friends will also find Y=bishop, because:
known_friends(mia,ellen) holds, and
friends(ellen,bishop) is found recursively.
Circularity
If you add cyclic dependencies in the friendship graph (in known_friends), then you will have an infinite traversal of this graph with friends. Before you can fix that, you have to consider the following questions:
Does friends(X,Y) <=> friends(Y,X) hold for all (X,Y) ?
What about friends(X,X), for all X ?
Then, you should keep a set of all seen people when evaluating friends in order to detect when you are looping through known_friends, while taking into account the above properties. This should not be too difficult too implement, if you want to try.
This clause of friends/2 is flawed:
friends(X,Y) :- friends(X,Z),friends(Y,Z).
Translate that into English: "If X and Y have a mutual friend Z, then X and Y are friends."
Or, let's specialize, let X be "me", let Y be my neighbour "FooBert", and let Z be "you": So if I am your friend and FooBert is your friend... does that make me and FooBert friends? I don't think so, I hate that guy---he always slams the door when he gets home. :)
I suggest you consider the algebraic properties that the relation friends/2 should have, the ones it may have, and ones it should not have. What about reflexivity, symmetry, anti-symmetry, transitivity?

Negated possibilities in Prolog

This is a somewhat silly example but I'm trying to keep the concept pretty basic for better understanding. Say I have the following unary relations:
person(steve).
person(joe).
fruit(apples).
fruit(pears).
fruit(mangos).
And the following binary relations:
eats(steve, apples).
eats(steve, pears).
eats(joe, mangos).
I know that querying eats(steve, F). will return all the fruit that steve eats (apples and pears). My problem is that I want to get all of the fruits that Steve doesn't eat. I know that this: \+eats(steve,F) will just return "no" because F can't be bound to an infinite number of possibilities, however I would like it to return mangos, as that's the only existing fruit possibility that steve doesn't eat. Is there a way to write this that would produce the desired result?
I tried this but no luck here either: \+eats(steve,F), fruit(F).
If a better title is appropriate for this question I would appreciate any input.
Prolog provides only a very crude form of negation, in fact, (\+)/1 means simply "not provable at this point in time of the execution". So you have to take into account the exact moment when (\+)/1 is executed. In your particular case, there is an easy way out:
fruit(F), \+eats(steve,F).
In the general case, however, this is far from being fixed easily. Think of \+ X = Y, see this answer.
Another issue is that negation, even if used properly, will introduce non-monotonic properties into your program: By adding further facts for eats/2 less might be deduced. So unless you really want this (as in this example where it does make sense), avoid the construct.

Findall with lists for Pacman netlogo game

I'm a beginner at prolog and I'm trying to make pacman move by itself using netlogo and prolog. So this is part of my code:
walkfront(_,_,_,_,_,_,Pacman,DirP,Lab,Ghost,_,Pellet,_,_,Decision) :-
findall(Dir,
( member(Dir,[0,90,180,270]),
\+ ( member((G,false),Ghost), dangerous(Pacman,G,2,Dir,_) ) ),
L),
findall(Dir,(member(Dir,[0,90,180,270]),(member(P,Pellet))),T),
chooseNotDangerous(L,Pacman,DirP,Lab,Dir,T)
walkfront(_,_,_,_,_,_,Pacman,DirP,Lab,Ghost,_,Pellet,_,_,Decision) this line has all the lists of information I'm getting from netlogo, Pacman has the position of pacman (x,y), DirP is the direction pacman is facing, Lab is the free spaces in the maze, Ghost is the position of the ghosts (x,y,eaten?), Pellet is a list of all the positions of the pellets (x,y), Decision is the output choosen by pacman.
The first findall is supposed to give me all the directions (Dir) that don't have ghosts and that aren't dangerous and save them in a list called L.
The second findall, I wanted it to give me all the directions that have pellets and save them in a list called T.
My question is if this findall's are correct because my code isn't working for some reason and I think it might be beacause of the second findall.
Thank you for helping me :).
Technically, findall/3 never fails, as it will complete with an empty result list if none of the calls succeed (well, exceptions apart, if your Prolog implements them).
Of course, it's impossible to answer your question, without all the code. And probably, even with all the code available, you will get little - if any - help, because the structure of your program seems more complex than what could be advisable.
Prolog is a language with a relational data model, and such data model is better employed when it's possible to keep the relations clean, best if normalized. Now you have a predicate with 16 arguments. How are you going to ensure all of them play correctly together ?
I would say - not change now the structure of your program, if you succeed debugging it ok. But the next program - if any - use another style, and the facilities that your Prolog offers to implement data hiding.
Plain old Prolog 'only' had compound terms: you code should likely be
packman(CurrPackManState, CurrGhostsState, NextPackManState, NextGhostsState) :-
...
where CurrGhostsState should be a list of CurrGhostState, and each element of this list should unify with an appropriate structure, hiding information about position, color, shape, etc...
SWI-Prolog now has dicts, and any Prolog will let you use DCGs to reduce the complexity of the code. See this page from Markus Triska, look for 'Implicitly passing states around'.
Also, you can always choice to put some less frequently updated info - like for instance the maze structure - in global database, with assert/retract.

Learn prolog exercise 2.3

Im going thru the learn prolog website to try to learn some prolog and are trying to under stand exercise 2.3. I guess every call to word() goes one down into some sort of stack or so and that would explain why it seems to change the words from the end back to the beginning. But how come that it goes back down again if it changes one of the words a bit up?
Like:
a criminal eats a criminal
a criminal eats a big kahuna burger
a criminal eats every criminal
a criminal eats every big kahuna burger
word(article,a).
word(article,every).
word(noun,criminal).
word(noun,'big kahuna burger').
word(verb,eats).
word(verb,likes).
sentence(Word1,Word2,Word3,Word4,Word5) :-
word(article,Word1),
word(noun,Word2),
word(verb,Word3),
word(article,Word4),
word(noun,Word5).
Then an swi-prolog question is it possible to get it to say yes/no instead of true/false?
Best Regards Anders Olme
Let me expand a bit on what starblue said.
Logically, this program says that any set of five things is a sentence if the first thing is an article, the second thing is a noun, the third thing is a verb, the fourth thing is another article and the fifth thing is another noun. The magic of Prolog is that you don't have to tell it how to get the answer, such as "try every article for the first word, then loop trying every noun for the second word, and so forth"; instead you just state your problem declaratively (the first word is an article, etc.) and Prolog will figure it out. So as long as your question is stated logically, you should (eventually) get every possible valid answer.
Because Prolog runs on an actual computer though, it must have an actual strategy for finding the answers, and that strategy is depth first search: it binds each variable in turn, trying every possibility until it can unify that variable, then it moves on to the next variable. When you ask for the next solution, it backs up to the last unification that had other possibilities and tries to find another one that satisfies the predicate. This is why the generated sentences come out in the order they did: word 5 unified last, so when Prolog backs up, it retries word 5. When it exhausts all the possible unifications for word 5, it backs up to word 4 and then moves forward again to word 5. So it will eventually try every possibility for all five words. If you don't like the order in which it's trying, you can change the order in which you bind the variables. For example, if you want it to retry the first word, then the second, you could rewrite the program to this:
sentence(Word1,Word2,Word3,Word4,Word5) :-
word(noun,Word5),
word(article,Word4),
word(verb,Word3),
word(noun,Word2),
word(article,Word1).
?- sentence(X,Y,Z,Q,A), write([X,Y,Z,Q,A]).
[a,criminal,eats,a,criminal] ;
[every,criminal,eats,a,criminal] ;
[a,big kahuna burger,eats,a,criminal]
True to your expectation, this is being managed internally by a stack. Most modern Prologs are implemented with a technique called the WAM, the Warren Abstract Machine. The WAM is like most other programming language virtual machines in that there is a call stack, but there's also a second stack called the trail which it pushes variables onto at each binding. Backtracking then works by popping the last variable off the trail and trying to unify it and resume from there. If there is no other unification for this variable, it pops another variable off the stack and backs up further. When Prolog runs out of trail, it simply returns false, because no binding was possible.

Resources