Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting all results of a query in a list in Prolog

Tags:

prolog

I'd like to know how to make a predicate that puts all results obtained from some query (so I get a result and press semicolon until I get False) in a list.

For example if I write foo(X,[1,2,3]). in some Prolog listener, let's say the result is

X=[11];
X=[22];
False.

I would like to get all those results in a list, so something like the following would happen.

?-another_foo(X,[1,2,3]).
X=[[11],[22]].

another_foo would somehow use foo to create a list with all the results from foo. I just don't know how.

like image 297
vuzun Avatar asked Dec 02 '10 21:12

vuzun


People also ask

What is S () in Prolog?

They are just terms, a representation of the successor of their argument. So, s(0) is used to represent the successor of 0 (i.e. 1 ), s(s(0)) is used to represent the successor of s(0) (i.e. 2 ), and so on and so forth.

What does \+ mean in Prolog?

Because of the problems of negation-as-failure, negation in Prolog is represented in modern Prolog interpreters using the symbol \+ , which is supposed to be a mnemonic for not provable with the \ standing for not and the + for provable.

Is list empty Prolog?

A list is either empty or it is composed of a first element (head) and a tail, which is a list itself. In Prolog we represent the empty list by the atom [] and a non-empty list by a term [H|T] where H denotes the head and T denotes the tail.


1 Answers

Use the built-in predicate findall/3:

?-findall(X0, foo(X0, [1,2,3]), X).
X = [[11], [22]].

You can define your another_foo/2:

another_foo(X, Input) :-
  findall(X0, foo(X0, Input), X).
like image 128
pts Avatar answered Oct 20 '22 01:10

pts