Home > Software engineering >  How to find a list in prolog?
How to find a list in prolog?

Time:11-17

Previously I wrote the predicate, reach(Departure, Arrivals) to find all points I can get into from the Departure point. How I can find a list of names of departure points from which I can get to a given point arrivals?

For example ?- list(krum, Departure).
Answer: Departure = [uzhorod].

This is my code:

    reachable(D, D, _).
reachable(Departure, Arrival, Visited) :-
    trip(_, Departure, Point, _),
    \  member(Point, Visited),
    reachable(Point, Arrival, [Point|Visited]).
reachable(Departure, Arrival) :-
    reachable(Departure, Arrival, [Departure]).

reach(Departure, Arrivals):-
    setof(
        Arrival,
        reachable(Departure, Arrival),
        Arrivals
    ),
    Arrivals \= [Departure].

This is my facts:

trip(01, kuiv, odessa, 1500).
trip(02, kuiv, lviv, 700).
trip(08, lviv, zaporizhya, 700).
trip(03, uzhorod, krum, 6000).
trip(04, vunohradiv, odessa, 2540).
trip(05, ternopil, kuiv, 3800).
trip(06, zaporizhya, donetsk, 900).
trip(07, lytsk, mariupol, 7500).

trip(Id, Departure, Arrivals, Price)
 

This is my output:

For example ?- reach(kuiv, Arrivals).
Answer: Arrivals = [donetsk, kuiv, lviv, odessa, zaporizhya]

CodePudding user response:

As @TA_intern points out we just need to flip arguments in the reach:

inverse_reach(Arrival, Departures) :-
    setof(
        Departure,
        reachable(Departure, Arrival),
        Departures
    ).
  • Related