递归填充列表 [英] Filling a list recursively

查看:52
本文介绍了递归填充列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个规则来耗尽数据库并用一些项目填充一个列表,但 prolog 解释器总是返回:超出全局堆栈.

I want to write a rule to exhaust the database and fill a list with some items but the prolog interpreter always returns with: Out of global stack.

fill(SomeParams, List) :- append(List, [NewItem], List), fail.

有没有办法在不进行统一的情况下扩展列表?

Is there a way to extend a list without doing unification?

推荐答案

您的 append 无法工作,因为它指出 List 是附加 的结果[NewItem]List,所以 List 应该是两个东西.请记住,Prolog 中的变量是逻辑变量,一旦绑定就永远无法更改.

Your append can't work because it states that List is the result of appending [NewItem]to List, so List is supposed to be two things at once. Remember, variables in Prolog are logical variables that can never be changed, once they are bound.

您可以使用 findall/3,正如 CapelliC 所说,或者如果你想要更多的控制,你可以这样做:

You can use findall/3, as CapelliC said, or if you want more control, you can do something like this:

%% some facts
fact(1).
fact(2).
fact(3).

fill(List, NewList) :-
    fact(X),
    not(member(X, List)), !,
    fill([X|List], NewList).
fill(List, List).

%%
fill(NewList) :- fill([], NewList).

然后

try ?- fill(L).

这篇关于递归填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆