Prolog回溯时如何获取值列表?
假设我有以下代码:
edge(a, b).
edge(a, c).
edge(a, d).
现在,当我这样做时,
neighbors(V, N) :- edge(V, N), writeln(N), fail.
我可以将邻居列表打印到控制台。但我怎样才能得到它作为结果列表呢?类似的东西
neighbors(V, Vs) :-
edge(V, N),
not(member(N, Vs)),
neighbors(V, [N|Vs]).
(由于 member
的处理方式,上面的部分并没有真正起作用。请问有什么建议吗?
Say I have the following piece of code:
edge(a, b).
edge(a, c).
edge(a, d).
Now when I do
neighbors(V, N) :- edge(V, N), writeln(N), fail.
I can get a list of the neighbors printed out to the console. But how can I get it as a result list? Something like
neighbors(V, Vs) :-
edge(V, N),
not(member(N, Vs)),
neighbors(V, [N|Vs]).
(the above piece doesn't really work due to the way member
is handled. Any suggestion please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您最喜欢的 Prolog 实现手册中阅读有关
findall
、bagof
和setof
的内容,或者例如 立即学习 Prolog!(不幸的是,很难直接链接到这些资源。)
Read about
findall
,bagof
andsetof
in your favorite Prolog implementation's manual, or e.g. the section "11.2 Collecting solutions" in Learn Prolog Now!(Unfortunately it is difficult to directly link to these resources.)
您可以使用
bagof/3
要创建满足目标的顶点列表,“Vs 是 V 的一条边的所有 N”。You can use
bagof/3
to create a list of your verticies that satisfy the goal, "Vs is all N that is an edge of V."