0

I am new to Prolog. I wrote the basic code below.

flight(acompany, paris, 7).
flight(bcompany,paris,7).
flight(ccompany,paris,7).
flight(dcompany,paris,7).

search([X],Y,Z) :- flight(X,Y,Z).

search([X|T],Y,Z) :- search(T,Y,Z) , flight(X,Y,Z).

I want to do two things. First when I query as

?- search(X, paris,7).

the first thing prolog show me is

X = [acompany]

But I want to see all element in the list at the first query.

i.e

X = [acompany, bcompany, ccompany, dcompany]

And the second thing I want is avoiding duplicating the elements in the list.

For example;

X = [acompany] ;
X = [bcompany] ;
X = [ccompany] ;
X = [dcompany] ;
X = [acompany, acompany] ;

I don't want such a last list.

How can I fix these two things? Thanks.

false
  • 10,264
  • 13
  • 101
  • 209
stedkka
  • 345
  • 2
  • 4
  • 14
  • What is `search` meant to do? Try to give predicates descriptive names, and avoid naming all your variables `X`, `Y` and `Z` unless they're supposed to work on arbitrary data. Prefer domain-specific variable names such as `Company`, `Destination`, etc. – Fred Foo Apr 24 '11 at 10:41
  • Yes, I admit giving the bad names to the variables. I just want to figure out how the things I want work.So the code may be seen untidy. – stedkka Apr 24 '11 at 12:08
  • @stedkka: my point is that your question would be a lot easier to answer, beyond what Kaarel has posted, if we knew what your `search` predicate searches for. – Fred Foo Apr 24 '11 at 12:55
  • `search` means searching all airlines companies providing the flights to Paris at the same time(at here, 7's). That's what I want to do. – stedkka Apr 24 '11 at 13:11
  • Then Kaarel's solution, wrapped in a predicate, is what you need. `search(Companies,Dest,Time) :- setof(C, flight(C,Dest,Time), Companies).` – Fred Foo Apr 24 '11 at 14:23
  • @larsmans: This works, thanks. There is one thing I want to do.(Maybe I should ask this in a new question) I change `flight(acompany, paris, 7)` to `flight(acompany, paris, 9)`. And when I query `?- search(Companies, paris,7)`, I want to get the flights at 7pm and after 7pm.(So it must include `acompany`). In other words, I want to apply greater than or equal to operator . How can I do? Thanks for helps. – stedkka Apr 24 '11 at 16:21
  • @stedkka, yes, ask that in a new question, and maybe rethink your timestamp representation as well. – Kaarel Apr 25 '11 at 07:26

1 Answers1

1
?- setof(X, flight(X, _, _), Xs).
Xs = [acompany, bcompany, ccompany, dcompany].
Kaarel
  • 10,554
  • 4
  • 56
  • 78
  • Thanks for reply. But what I want is querying with `search` predicate. Can I get the same result by using `setof` in my code? – stedkka Apr 24 '11 at 12:13