问题描述
因此,作为我工作的一部分,我的代码需要打印查询的所有解决方案,但不使用 findall/3
谓词.我已经做了一些阅读,有一些方法涉及将解决方案添加到列表等等.我自己尝试过这样做,但没有成功;因此我希望有人能够展示我如何在不使用 findall 的情况下打印所有解决方案.
So as part of my work my code needs to print all the solutions to a query but without using the findall/3
predicate. I've done some reading around and there are ways involving adding the solutions to a list and so on. I tried doing this myself but to with no success; hence I was hoping someone may be able to show how I would print all the solutions without using findall.
程序代码如下:
solutions(Q, 100):-
Q = [X, Y, S],
between(2,50,X),
between(2,50,Y),
S is X+Y,
Y > X,
S =< 50.
Q 和 100 在那里是因为程序的另一部分需要它,所以现在忽略它.当我使用 ?-solutions(Q, 100)
查询时,我得到结果 [2,3,5]
, [2,4,6]
, [2,5,7]
等等,但显然我需要按 ;
来获得每个新结果.我需要在不需要按 ;
和不使用 findall 的情况下显示所有这些.
The Q and the 100 are there because it's needed for another part of the program so ignore that for now. When I query using ?- solutions(Q, 100)
I get the results [2,3,5]
, [2,4,6]
, [2,5,7]
and so on but obviously I need to press ;
to get each new result. I need all these to be displayed without the need to press ;
and without using findall.
推荐答案
一个基于断言的解决方案(这实际上是在 Prolog 教科书中如何实现 findall
的):假设 solution/2
根据您的代码找到每个解决方案.现在我们按照 Paulo 的建议使用故障驱动循环来构建解决方案列表,使用 assert/1
来缓存解决方案.
An assert-based solution (which is actually how findall
was implemented in Prolog textbooks): Assume that solution/2
finds each single solution, as per your code. Now we use a fail-driven loop, as Paulo suggested, to build a list of solutions, using assert/1
to cache solutions.
solutions(_, N) :-
solution(Q, N),
(cache(Qs) -> retractall(cache(_)) ; Qs = []),
assert(cache([Q|Qs])),
fail.
solutions(Qs, _) :-
retract(cache(Qs)).
这篇关于在没有 findall 的情况下收集所有解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!