Search code examples
listprolog

How to clear the previous query result on a list (in Prolog)


I have this code:

connected(a,b).
connected(b,a).
connected(b,j).
connected(j,b).
connected(j,i).
connected(i,j).
connected(i,h).
connected(h,i).
connected(h,g).
connected(g,h).
connected(g,f).
connected(f,g).
connected(g,k).
connected(k,g).
connected(f,k).
connected(k,f).
connected(k,e).
connected(e,k).
connected(k,d).
connected(d,k).
connected(e,d).
connected(d,e).
connected(d,c).
connected(c,d).

route(X,Y,R):-route(X,Y,[X],P),reverse(R,P).

route(X,Y,Vs,[Y|Vs]):-connected(X,Y),not_yet_visited(Y,Vs).

route(X,Y,Vs,Rs):-connected(X,Z),not_yet_visited(Z,Vs),route(Z,Y,[Z|Vs],Rs).

not_yet_visited(A,As):- \+memberchk(A,As).

is_the_same(B,C):- B=C,write('The starting room is the same with the ending room').

go(X,Y):-is_the_same(X,Y).
go(X,Y):-route(X,Y,R),writelist(R).

writelist([L]):-write(L),write('-->'),write('I am in room '),write(L).
writelist([L|Lt]):-write(L),write('-->'),writelist(Lt).

The execution predicate is the go/2 where I give a starting room X and an ending room Y.Route predicate calculates the path from X to Y and then it stores it to the R list.Then it prints it via the writelist predicate and the result is being showed like this:

go(a,d).
a-->b-->j-->i-->h-->g-->f-->k-->d-->I am in room d

The problem is that when I ask for an alternative solution path,it keeps the previous latest value of the list and it prints it at the beggining of the next query just like this:

go(a,d).
a-->b-->j-->i-->h-->g-->f-->k-->d-->I am in room d
true ;
d-->a-->b-->j-->i-->h-->g-->f-->k-->e-->d-->I am in room d
true ;
d-->a-->b-->j-->i-->h-->g-->k-->d-->I am in room d
true ;
d-->a-->b-->j-->i-->h-->g-->k-->e-->d-->I am in room d
true ;
d-->
false.

The starting room should be "a" for this certain example and not "d". How can I get rid of the previous "d" value??


Solution

  • I found the problem and I solved it.

    writelist([L]):-write(L),write('-->'),write('I am in room '),write(L),!.
    writelist([L|Lt]):-write(L),write('-->'),writelist(Lt).
    

    It needed a CUT at the end of the first writelist clause.