在不使用内置Findall的情况下实现简单版本的Prolog Findall
我正在尝试在Prolog中实现一个简单的Findall版本,而无需使用内置的Findall或类似的内置谓词 - 就像学习练习一样。
例如,假设我的数据库中有一个关系a/1,
a(1).
a(11).
a(13).
我希望像find_the_as(list)这样的关系给我列表= [1,11,13]。
我可以使用断言和缩回的基于“失败”的循环来执行此操作,但是我认为必须有一种递归方法来使用累加器来执行此操作(而且我只是看不到它)。
提前致谢!
例如:
a(1)。
A(11)。
A(13)。
%
% collect all the N such that a(N)
% into a List
%
collect_n_such_that_a_of_n(List) :-
retractall(the_n_such_that_a_of_n(_)),
assert(the_n_such_that_a_of_n([])),
(
a(N),
the_n_such_that_a_of_n(As),
retractall(the_n_such_that_a_of_n(_)),
assert(the_n_such_that_a_of_n([N|As])),
fail
) ; true,
the_n_such_that_a_of_n(List).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此示例:
然后查询:
返回:
示例使用:
与Findall不同,结果列表不包含重复项。例如。如果添加了额外的
a(11)
,则结果列表仍然只包含一个11
。与Findall不同,结果列表中的元素是相反的(即
[13,11,1]
而不是[1,11,13]
)。Using this example:
then the query:
returns:
The example uses:
Unlike with findall, the resulting list does not contain duplicates. eg. if you add an extra
a(11)
then the resulting list will still only contain one11
.Unlike with findall, the elements in the resulting list are in reverse order to which they were found (i.e.
[13, 11, 1]
rather than[1, 11, 13]
).使用
call_nth/2
((当心具有副作用的程序):样本运行具有以下事实:
Using
call_nth/2
(beware of procedures which have side effects):Sample run having these facts: