Pregunta

I have a database full of facts such as:

overground( watfordjunction   , watfordhighstreet , 2 ). 
overground( watfordhighstreet , bushey            , 3 ). 
overground( bushey            , carpenderspark    , 3 ). 
overground( carpenderspark    , hatchend          , 2 ). 

example: watford junction to watfordhighstreet takes 2 minutes.

I then designed a rule so that I can test if a journey from any station to another can be done including any reverse journeys.

isjourney(Station1,Station2):-
   overground(Station1,_,_), overground(_,Station2,_),!; overground(Station2,_,_), overground(_,Station1,_),!.
isjourney(Station1,Station2):-
   overground(Station1,Station3,_), isjourney(Station3,Station2).
isjourney(Station1,Station2):-
   overground(Station3,Station2,_), isjourney(Station1,Station3).

I understand that the 1st line first checks if station1 and station2 exist in the facts. The cuts also end backtracking once the journey is found to be true in order to prevent a infinite loop.

The 2nd line then checks if a journey between station1 and station2 is possible through a intermediate station (station3). What I'm confused about is that 3rd line... It seems to me like its just doing the opposite, in other words checking for the same thing as line 2 but for a reverse journey. However what I find is that if I delete the 3rd line and test the code it still works, including if I test for a reverse journey. If the second line of the rule can check if a forward and reverse journey is possible, then what is the 3rd line doing?

¿Fue útil?

Solución

It seems to me like its just doing the opposite, in other words checking for the same thing as line 2 but for a reverse journey.

That's indeed what it seems to be doing. This code is very confusing; it could better have been written using an intermediate predicate such as

connected(A, B) :- overground(A, B, _).
connected(A, B) :- overground(B, A, _).

Otros consejos

This means the roads are 2-way, the source and destination of a route may be interchanged.

Your code doesn't even check if there's a route between two places: the first rule is enough to get true as output. If the first rule checks the existences of the places, give it a different name. Checking existence is not equivalent to having a route between them.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top