dragonwasrobot / learn-prolog-now-exercises

My solutions to the exercises and practical sessions of the book 'Learn Prolog Now!' by Patrick Blackburn, Johan Bos, and Kristina Striegnitz.
288 stars 81 forks source link

Chapter 3 exercise Exercise 3.3 #51

Open kagankorkmaz opened 4 years ago

kagankorkmaz commented 4 years ago

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

Victordmz commented 3 years ago

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).