Putting all results of a query in a list in Prolog

瘦欲@ 提交于 2021-02-17 21:33:05

问题


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.


回答1:


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).


来源:https://stackoverflow.com/questions/4340022/putting-all-results-of-a-query-in-a-list-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!