Anthony Brice
Anthony Brice

Reputation: 57

Making a list of lists in Prolog

I'm writing a functor find/3 in Prolog that should return a list of paths from one destination to another as given by a database of facts. A fact in this database takes the form

flight(Carrier,ID,Start,Destination,Hours,Cost).

These are meant to simulate a database of flights. Each flight/6 has a unique ID. I'm only working with 3 facts for now:

flight('FL', 1, 'TYO', 'PAR', 2, 1800).
flight('WN', 4, 'PAR', 'OSA', 16, 100).
flight('FL', 2, 'TYO', 'OSA', 13, 500).

I have a functor findPaths/4 that returns a list of all ID's to get from one location to another. The following is an example of calling the functor:

| ?- findPaths('TYO','OSA',Path,['TYO']).
Path = [2] ? ;
Path = [1,4] ? ;
no

So it finds the path that is just ID: 2 and the one that is composed of flights ID: 1 and ID: 4.

I would like my functor find/3 to return a list of every path that findPaths/4 finds, but I am quite at a loss of how to do that.

At the moment, this is how I define find/3:

find(Start,Destination,Paths) :-
    findPaths(Start,Destination,Path,[Start]),
    memberchk(Path,Paths).

And here is an example of calling it:

| ?- find('TYO','OSA',List).             
List = [[2]|_] ? ;
List = [[1,4]|_] ? ;
no

I'm not sure what I'm missing here. I expect memberchk/2 to make its first argument a member of its second argument, but I believe I am erroneously thinking about this as if it were an imperative language. I don't know how to correct my reasoning and my functor.

Upvotes: 1

Views: 362

Answers (1)

SQB
SQB

Reputation: 4078

Use findall/3.

findall(Path, findPaths('TYO', 'OSA', Path, ['TYO']), ListOfPathLists).

Upvotes: 3

Related Questions