开发者

Prolog out of global stack

Hi guys i'm new on Prolog. I'm trying to combine 1000 elements in class 3 without repetition. I have done the code, but i have out of stack problem.

member(T, [T|R], R) :- !.
member(T, [_|L], R) :- member(T, L, R). 

last_element([H], H) :- !.
last_element([H|[X]], X) :- !.
last_element([H|T], R) :- last_element(T, R). 


    macronutrienti(1).
 开发者_如何学编程   macronutrienti(2).
    macronutrienti(3).
    and so on

percentuale_macronutrienti(Alimento, R) :-
    macronutrienti(Alimento),
    R = Alimento.

combina(NRAlimenti, RIS) :-
    findall(PM, percentuale_macronutrienti(Alimento, PM), PMR),
    f1(NRAlimenti, PMR, PMR, RIS), !.

f1(1, RParz, PMR, RParz) :- !.
f1(Index, RParz, PMR, RIS) :-
    Index1 is Index - 1,
    g2(RParz, PMR, RIS1, RIS1),
    f1(Index1, RIS1, PMR, RIS).
f1(Index, RParz, PMR, RIS) :-
    Index1 is Index - 1,
    g1(RParz, PMR, RIS1, RIS1),
    f1(Index1, RIS1, PMR, RIS).

g1([A|[TA]], A1, OldR, R) :- 
    q([A], L1, A1), 
    h1(A, L1, OldR, OldR), !.
g1([A|T], A1, Risultato,  R) :- 
    q([A], L1, A1), 
    h1(A, L1, OldR, OldR),
    append(OldR, TOldR,Risultato),
    g1(T, A1, TOldR, R).

q(A, R, A1) :- last_element(A, LastElement), member(LastElement, A1, R).

g2([A|[TA]], A1, OldR, R) :-
    q(A, L1, A1), 
    h2(A, L1, OldR, OldR), !.
g2([A|T], A1, Risultato, R) :-
    q(A, L1, A1),  
    h2(A, L1, OldR, OldR),
    append(OldR, TOldR, Risultato),
    g2(T, A1, TOldR, R).

h1(_, [], _,  _) :- !.
h1(Alimento, [Alimento1], [OldM],  R) :- append([Alimento], [Alimento1], OldM).
h1(Alimento, [Alimento1|T1], [OldM|TOldM], NewM) :- 
    append([Alimento], [Alimento1], OldM),
    h1(Alimento, T1, TOldM, NewM).

h2(_, [], _,  _) :- !.
h2(Alimento, [Alimento1], [OldM],  R) :- append(Alimento, [Alimento1], OldM).
h2(Alimento, [Alimento1|T1], [OldM|TOldM], NewM) :- 
    append(Alimento, [Alimento1], OldM),
    h2(Alimento, T1, TOldM, NewM).

:- combinew(3,R).

What is wrong? Thank you in advance


Here's a much shorter code that (I think) does the same as yours:

combine(N,L) :-
    findall(PM, macronutrienti(PM), PMR),
    findall(L0, combine0(N, PMR, L0), LL).

combine0(0, _, []) :- !.
combine0(I, PMR, [X|LR]) :-
    member(X, PMR, PMRR),
    I1 is I-1,
    combine0(I1, PMRR, LR).

member(T, [T|R], R).
member(T, [_|L], R) :- member(T, L, R). 

( I slightly changed your member/3 predicate)

However, this still does not resolve your stack overflow problem. Basically, if I understood your question correctly, you want to extract all sorted subsets of length 3 from the set of 1000 elements. The number of sets you are looking at is 1000!/(1000-3)!, i.e., 997.002.000 lists of length 3. That's quite a lot, so if you'll need a huge stack.

If you don't need the complete list to continue, change your workflow to generate one such item at a time, then process it immediately, and continue with the next.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜