tomsky
tomsky

Reputation: 545

Prolog - sending a list as a parameter to be displayed

I'm trying to write a program to find a route between towns, add the path to the list and then, ad the end display it. I think adding to the list works, but I'm having the problem displaying the list, don't know how can I pass a list as a parameter to be used when it's done finding the path? Hope you guys can help. Here's the code:

connected(middlesbrough, stockton).
connected(middlesbrough, darlington).
connected(stockton, sunderland).
connected(darlington, thirsk).
connected(stockton, newcastle).
connected(newcastle, york).
connected(thirsk, york).
connected(york, leeds).
connected(leeds, huddersfield).
connected(leeds, dewsbury).
connected(huddersfield, manchester).
connected(dewsbury, manchester).


run(List):- 
  write('Enter Starting City :'), 
  read(Start), 
  write('Enter Finishing City :'), 
  read(End),  
  findroute(Start,End),
writeList([List]).

findroute(Start,End):-
connected(Start,End).
findroute(Start,End):-

add(Start, List, [Start | List]),

connected(Start,Link), findroute(Link,End).


add(A,B,[A|B]).

 writeList([]).      
writeList([Head | Tail]):-   
  write(Head),               
  nl,                             
  writeList(Tail).                 

Upvotes: 0

Views: 328

Answers (1)

twinterer
twinterer

Reputation: 2436

Your findroute/2 predicate does not return the list, so the output can't work.

The call should look something like this:findroute(Start,End,List)

Obviously, the findroute/2 predicate must be changed to findroute/3:

findroute(Start,End,[Start,End]):-
    connected(Start,End).
findroute(Start,End,List):-
    connected(Start,Link),
    add(Start,Rest,List),
    findroute(Link,End,Rest).

(hint: be sure you understand why the add/3 call works even though Rest is uninstantiated at that point. Otherwise your tutor won't believe that this code is your homework! ;-) )

You may want to add a cut at the end of the first clause if you only want to find the shortest route.

Finally, List is already a list, so don't put square brackets around it when calling writeList/1!

Upvotes: 2

Related Questions