使用顶层在 SWI-Prolog 中获取多个解决方案

Get multiple solutions in SWI-Prolog using toplevel

我是 SWI-Prolog 的初学者(但对 Borland Prolog 有一些经验),我遇到了以下测试代码的奇怪行为:

test(10).
test(1).

查询 ?-test(A) 预计会得到 2 个解决方案,类似于 A = 10; A = 1。但是,只生成 A = 10。我不在这里使用剪辑。也许回溯在 SWI-Prolog 中默认是关闭的?

提前致谢

抱歉,答案很简单(见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.

bagof/3 可能就是您要找的。

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

其中 Xs 是所有匹配结果的列表。
知道匿名变量不会像您对 bagof 的期望那样工作。在以下示例中:

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

bagof(X, test(X,_), Xs) 只会给出第二项均匀的 X 值;在这种情况下只有偶数。如果你想 return 所有匹配值,你需要做类似

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