adolfosrs
adolfosrs

Reputation: 9389

Prolog building lists from predicates list

I have the following predicates in Prolog:

rules('Archer','NX-01').
rules('Kirk','NCC-1701').
rules('Picard','NCC-1701-D').
rules('Janeway','Voyager').
rules('Almak','IRWTMet').

Where 'Archer', 'Kirk', 'Picard', 'Janeway' and 'Almak' are Ship Commanders and 'NX-01', 'NCC-1701', 'NCC-1701-D', 'Voyager' and 'IRWTMet' are Ships.

So I want to, given a list of Ships return a list of Ship Commanders.

I'm trying this:

list_ship_commanders([],_).
list_ship_commanders([Ship|T],R):-
   findall(Commander,rules(Commander,Ship),R),
   list_ship_commanders(T,R).

The above code only works when the Ship list has only one element. I'm using "findall" but i'm not sure this is the right way.

Upvotes: 1

Views: 129

Answers (1)

CapelliC
CapelliC

Reputation: 60014

From your data (and your code) it's not clear if you allow multiple Ships per Commander (or multiple Commanders per Ship :).

If you are not interested in such detail, you can try:

list_ship_commanders(Ships, Commanders) :-
    findall(Commander, (member(S, Ships), rules(Commander, S)), Commanders).

You will get a list with Commanders possibly repeated, and no link to pertinent rules/2.

Upvotes: 1

Related Questions