Search code examples
prolog

find the list of all airports in a country in prolog


This is my flightdb.pl

#flight(citya ,cityb)
flight(dublin, london).
flight(cork, moscow).
flight(chicago, dublin).
flight(berlin, moscow).
flight(cork, newyork).
flight(paris, hongkong).

#country(city,country)
country(dublin,ireland).
country(cork,ireland).
country(london,uk).
country(rome,italy).
country(moscow,russia).
country(hongkong,china).
country(amsterdam,holland).
country(berlin,germany).
country(paris,france).
country(newyork,usa).
country(chicago,usa). 
country(sao_paulo,brazil).
country(rio,brazil).

I am trying to get all the airports in the particular country

this is the predicate that I wrote

list_airport(X,L) :-country(L,X).

I have just started with prolog ,is the logic correct?


Solution

  • You can query the database with:

    ?- country(X, ireland).
    X = dublin ;
    X = cork.
    

    You can generate a list of all the matches with findall/3 [swi-doc]:

    ?- findall(C, country(C, ireland), Cs).
    Cs = [dublin, cork].
    

    So if you want to obtain a list of cities for a given country, you can use:

    list_airport(C, L) :-
        findall(Ci, country(Ci, C), L).
    

    and query with:

    ?- list_airport(usa, L).
    L = [newyork, chicago].