简体   繁体   中英

How to find a list in prolog?

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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM