Get multiple solutions in SWI-Prolog

白昼怎懂夜的黑 提交于 2020-01-14 10:32:21

问题


I'm beginner in SWI-Prolog (but have some experience in Borland Prolog), and I've faced with a strange behavior for the following test code:

test(10).
test(1).

It is expected for query ?-test(A) to get 2 solutions, something like A = 10; A = 1. However, only A = 10 is produced. I don't use the cut here. Maybe backtracking is off by default in SWI-Prolog?

Thanks in advance


回答1:


Sorry, the answer is very simple (see SWI-Prolog doc):

The user can type the semi-colon (;) or spacebar, if (s)he wants another solution. Use the return key if you do not want to see the more answers. Prolog completes the output with a full stop (.) if the user uses the return key or Prolog knows there are no more answers. If Prolog cannot find (more) answers, it writes false.




回答2:


bagof/3 is probably what you're looking for.

?- bagof(X, test(X), Xs).

where Xs is a list of all matching results.
Know that anonymous variables don't work how you might expect with bagof. In the following example:

test(1,odd).
test(2,even).
test(3,odd).
test4(even).

bagof(X, test(X,_), Xs) will only give values of X where the second term is uniform; in this case only the even numbers. If you want to return all matching value you need to do something like

?- bagof(X, A^test(X,A), Xs).


来源:https://stackoverflow.com/questions/44354455/get-multiple-solutions-in-swi-prolog

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