I have the following prolog knowledge base containing train connections in Europe:
connection(paris, barcelona).
connection(barcelona, madrid).
connection(madrid, lisbon).
connection(paris, brussels).
connection(brussels, amsterdam).
connection(amsterdam, hamburg).
connection(hamburg, berlin).
I want to create a predicate ride/3 that can draw a route without creating a list. The three arguments should be 1. the starting point 2. the end point 3. the route, which should be a predicate fromTo/2.
An example:
?- ride(paris,lisbon,X).
X = fromTo(paris,barcelona, fromTo(barcelona,madrid,
fromTo(madrid,lisbon)))
I thought the base clause should be something along the lines of this, but that gives me an error.
ride(X,Y,go(X,Y):- connection(X,Y)
CodePudding user response:
You are getting an error because your base case is missing a parenthesis. Also looking from your expected output the third argument should be fromTo(X,Y)
.
Your recursive clause should be one that starts from X
, goes to Z
and then recursively calls itself but now going from Z
to Y
:
ride(X, Y, fromTo(X, Y)):-
connection(X, Y).
ride(X, Y, fromTo(X, Z, Chain)):-
connection(X, Z),
ride(Z, Y, Chain).
Sample run:
?- ride(paris,lisbon,X).
X = fromTo(paris, barcelona, fromTo(barcelona, madrid, fromTo(madrid, lisbon))) ;
false.