bleda
bleda

Reputation: 115

SWI-Prolog List and Recursion

I have a database looks like;

airport(ist, 90).
airport(saw, 45).
airport(esb, 60).
airport(adb, 60).
airport(erz, 30).
airport(ayt, 90).
airport(mlx, 30).
airport(tzx, 30).

airplane(f1, ist, [esb,tzx,saw]).
airplane(f2, ist, [mlx,esb,erz,esb]).
airplane(f3, ist, [esb,ist,esb,ist]).
airplane(f4, saw, [ayt,saw,ayt,saw]).
airplane(f5, erz, [esb,erz,esb]).
airplane(f6, mlx, [ist,esb,tzx,saw]).

and I have a predicate called "testing" takes two lists as parameter. So, if you write testing([ist],X). you should get X=[esb,mlx]. I wrote this code.

testing([],[]).

testing([D|D1],[L|L1]) :-
    airport(D,_),
    airplane(_,D,[L|_]),
    testing(D1,L1).

This works and the output is:

[8] 60 ?- listConnections([ist],X).
X = [esb] ;
X = [mlx] ;
X = [esb].

But this is not that I want. So the first problem is I need a single line answer like X=[esb,mlx]. The second problem is there shouldn't duplicate elements in the list. I hope my problem is clear. Any help would be greatly appreciated.

Upvotes: 2

Views: 375

Answers (1)

m09
m09

Reputation: 7493

You can use setof/3:

testing_set(List, Result) :-
    setof(L, testing(List, L), Result).

A page that might interest you is this SWI-Prolog documentation page.

Note that it doesn't return [esb,mlx] but [[esb], [mlx]], it's easily fixed though.

Upvotes: 3

Related Questions