Murdock
Murdock

Reputation: 123

Prolog List storage

I have a program which generates a list, and at different stages removes certain elements from it. There are 4 removal stages, and calling the 4th will first call 1,2,3 then 4. the predicate is called s4(Q, 100) and there are also s1, s2 ,s3 with the same preicate style, (Q,100).

At stage s1, I remove elements depending on how many factors they have, So i pass Q to another predicate, by calling

removePrimes(Q,L).

This now has the list Q minus the undesired elements. However, Q is unchanged and still has all the original elements.

My question is, is there a way of giving Q the result of L so it's value can be passed up to s2 to be altered again?

Here is the rest of my code so you can better see what I mean

s4(Q,X):-
    s3(Q,X).

s3(Q,X):-
    s2(Q,X).

s2(Q,X):-
    s1(Q,X).

    %Further alter the list here
    %Q is not passed back, since it is unchanged in s1

s1(Q,X):-
    s0(Q,X),
    %remove the undesired elements
    removePrimes(Q,L).

    %L now contains the list we need, but Q is unchanged!!!

s0(Q, N) :-
    %generate the list
    validPair(Q).

Upvotes: 1

Views: 283

Answers (2)

m09
m09

Reputation: 7493

sTotal(L) :-
    validPair(Q),
    s1(Q, Q2),
    s2(Q2, Q3),
    s3(Q3, Q4),
    ...
    sN(QN, L).

should do the trick.

edit, going from your code:

s4(X, N):-
    s3(Q),
    dostuff(Q, X, N).

s3(L):-
    s2(Q),
    doblah(Q, L).

s2(L):-
    s1(Q),
    dosomethingwithalist(Q, L).

s1(L):-
    s0(Q),
    removePrimes(Q,L).
s0(Q) :-
    validPair(Q).

Note that this equivalent and a too verbose version of:

s4(X, N) :-
    validPair(Q),
    removePrimes(Q, Q2),
    dosomethingwithalist(Q2, Q3),
    doblah(Q3, Q4),
    dostuff(Q4, X, N).

Upvotes: 2

thanos
thanos

Reputation: 5858

nope, prolog uses single assignment; you should pass the new list instead of the original.

well, some implementations (swi-prolog for example) support global variables that can be updated (or you can assert/retract) with but it's not really advised to use it, especially in this case

Upvotes: 1

Related Questions