learn-prolog-now-exercises icon indicating copy to clipboard operation
learn-prolog-now-exercises copied to clipboard

Chapter 3 exercise Exercise 3.3

Open kagankorkmaz opened this issue 5 years ago • 1 comments

Are you sure about the solution? It looks like OUT OF LOCAL STACK will be occur.

kagankorkmaz avatar May 29 '20 19:05 kagankorkmaz

This one works. The ! is a cut, meaning once a solution is found, Prolog does not have to backtrack (and thus does not have to find any alternative routes). The trick was to use another functor for the other direction, called travelBetweenReverseDirection, so that Prolog cannot go back to the initial direction using travelBetween.

directTrain(forbach,saarbruecken).
directTrain(freyming,forbach).
directTrain(fahlquemont,stAvold).
directTrain(stAvold,forbach).
directTrain(saarbruecken,dudweiler).
directTrain(metz,fahlquemont).
directTrain(nancy,metz).

travelBetween(X,Y) :- directTrain(X,Y),!.
travelBetween(X,Y) :-
	directTrain(X,Z),
	travelBetween(Z,Y),
	!.
travelBetween(X,Y) :- travelBetweenReverseDirection(Y,X),!.
travelBetweenReverseDirection(X,Y) :- directTrain(X,Y).
travelBetweenReverseDirection(X,Y) :-
	directTrain(X,Z),
	travelBetweenReverseDirection(Z,Y).

Victordmz avatar Mar 08 '21 17:03 Victordmz