Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

[prolog] Building a list a return value 1

Status
Not open for further replies.

jnpnshr411

Programmer
May 1, 2010
4
US
Hello all,

this is my first time on these forums. I am not new to programming at all, but am very lost with prolog. I have been reading through "Learn Prolog Now!"

they as me to build a predicate that would let me know if i can travel from one place to another.

the assertions that I have are
Code:
byCar(auckland,hamilton). 
byCar(hamilton,raglan). 
byCar(valmont,saarbruecken). 
byCar(valmont,metz). 
byTrain(metz,frankfurt). 
byTrain(saarbruecken,frankfurt). 
byTrain(metz,paris). 
byTrain(saarbruecken,paris). 
byPlane(frankfurt,bangkok). 
byPlane(frankfurt,singapore). 
byPlane(paris,losAngeles). 
byPlane(bangkok,auckland). 
byPlane(losAngeles,auckland).

I wrote a functor that will answer yes if there is some way to get from point X to Y. However I want to make a predicate called travel/3 that will build a list of travel points needed to go from X to Y.

Code:
travel(X,Y) :- byCar(X,Y),byPlane(X,Y),byTrain(X,Y).

travel(X,Y) :- byCar(X,Z) ; byTrain(X,Z) ; byPlane(X,Z), travel(Z,Y).

Can someone lead my on the right path to build the list?

thank you for any help
 
At least, you must write
Code:
travel(X,Y) :- 
   (byCar(X,Z) ; byTrain(X,Z) ; byPlane(X,Z)), 
   travel(Z,Y).
 
okay. I didnt know I could include those parentheses, however that function works correctly. It return yes or no if a path exists between X and Y.

What I want to create is a function that would look like

trave(X,Y,L) :- ? ?

if i told it travel(metz,losAngele, L).

it should return L = [metz, paris, losAngeles].

I tried drawing a tree structure of how prolog would solve it but I dont know where to bind thing to make the list.
 
You should put in a list the towns you visit to prevent cycles.
You should create a special predicat to test if it is possible to go from X to Y by car/plane/train (fo example fromto/2)

Now, you travel From To passing By :
Code:
travel(From, To, By, Travel) :-
  % if fromto(From, To) exists
  fromto(From, To),
  % To hasn't been visited
  not member(To, By),
  % your travel is finished
  Travel = [To | By].
You have to write the other case and think of the way to launch the research.

Hope this help.
 
Thank you very much. It was very helpful. I also went back and googled a bit on list manipulation. Its amazing the kind of power prolog has, but its hard to get my head around. I managed to get it running smoothly. Thank you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top