-1

Let's say we have some facts and rules set like these :

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(singapore,auckland).
byPlane(losAngeles,auckland).

travel2(X,Y,car) :- byCar(X,Y).
travel2(X,Y,train) :- byTrain(X,Y).
travel2(X,Y,plane) :- byPlane(X,Y).

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

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

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

travel(X,Y, go(byCar(X,Z),G)) :-
  byCar(X,Z),
  travel(Z,Y,G).

travel(X,Y, go(byTrain(X,Z),G)) :-
  byTrain(X,Z),
  travel(Z,Y,G).

travel(X,Y, go(byPlane(X,Z),G)) :-
  byPlane(X,Z),
  travel(Z,Y,G).

So My Question is, how to make a rule named path/2. For Example

path(X,Y) :- %What to write here...

this rule will make an output of which other cities you have to go to get from one place to another , and also how (byCar ? byTrain? or byPlane?)

Basically the rule "travel/3" already have the same specific details, but how to make it onto a new rule named "path/2".

Thanks in advance :)

false
  • 10,264
  • 13
  • 101
  • 209
  • 1
    Let us see. How may questions on StackOverflow for Prolog have an answer with the word `path`? [676](https://stackoverflow.com/search?q=%5Bprolog%5D+path+is%3Aanswer). – Guy Coder Nov 11 '21 at 14:24

1 Answers1

0

Your code does not make it easy because the result of a long path is nested (A, (B, (C, (D, E)))).

Make something which can print the nested paths:

% prints a single connection e.g. go(byCar(valmont, metz))
printGo(go(A)) :-
    writeln(A).

% prints nested connections e.g. go(byCar(valmont, metz), go(byTrain(metz, paris)))
printGo(go(A, B)):-
    writeln(A),
    printGo(B).

Then path/2 calls travel/3 to find a path, and prints the path:

path(X, Y) :-
    travel(X, Y, Path),
    printGo(Path).

e.g.

?- path(valmont, auckland)

byCar(valmont, saarbruecken)
byTrain(saarbruecken, frankfurt)
byPlane(frankfurt, bangkok)
byPlane(bangkok, auckland)
true
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87