Filling a list recursively

2019-09-21 00:25发布

问题:

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?

回答1:

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.

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).

Then

try ?- fill(L).


标签: prolog