Ahashan Alam Sojib
Ahashan Alam Sojib

Reputation: 346

prolog : using elements of a list in a fact

I want to make a Prolog console application that shows venue name and rent for any event for a given(user input) location. So far I have been able to create a list of venues of a given(user input) location.

My code is given below.

listing(venue_location).
listing(venue_seating).
listing(venue_overhead).

venue_location(washington_party_hall1, washington).
venue_location(washington_party_hall2, washington).
venue_location(newyork_party_hall1, newyork).
venue_location(newyork_party_hall2, newyork).

venue_capacity(washington_party_hall1,300).
venue_capacity(washington_party_hall2,450).
venue_capacity(newyork_party_hall1, 340).
venue_capacity(newyork_party_hall2,500).

venue_rent(washington_party_hall1,1350).
venue_rent(washington_party_hall2,1200).
venue_rent(newyork_party_hall1,1500).
venue_rent(newyork_party_hall2,1000).

main:-
   write("Enter a location"),nl,write("->"),
   read(Loc),
   findall(X,venue_location(X,Loc),Venues),
   write(Venues).

This gives the following output:

Enter a location
->washington.
[washington_party_hall1,washington_party_hall2]
true.

Is there a way to use the venues list in venue_rent fact to get every list element's rent? I want to display the name of these venues with their rents in this way:

washington_party_hall1   1350
washington_party_hall2   1200

Upvotes: 1

Views: 1008

Answers (1)

lurker
lurker

Reputation: 58324

You know that if you have a given venue, say Venue, you can get the rent from your facts:

?- Venue = washington_party_hall1, venue_rent(Venue, Rent).
Rent = 1350

If you want to get the rent for all of the venues in a list Venues, you can use member/2:

?- Venues = [washington_party_hall1,washington_party_hall2], member(Venue, Venues), venue_rent(Venue, Rent).

That's the basic query structure of what you want. Now if you want to write things to the terminal in a nice format, you can use a failure driven loop, which is a common way to display a list of items in a formatted fashion:

write_venue_rents(Venues) :-
    member(Venue, Venues),
    venue_rent(Venue, Rent),
    write(Venue), write(' '), write(Rent), nl,
    fail.

This doesn't give you aligned columns, but you get the idea. You can look up the formatting options and predicates for Prolog to format the output to your taste.

Another way is to use maplist/2:

% Write out the rent for a given venue
write_venue_rent(Venue) :-
    venue_rent(Venue, Rent),
    write(Venue), write(' '), write(Rent), nl.

% Write out the rent for a list of venues
write_venue_rents(Venues) :-
    maplist(write_venue_rent, Venues).

I think the maplist/2 version is more elegant.

Upvotes: 2

Related Questions