1
votes

I am new to Prolog, and got stuck trying to make an auxiliary function that takes elements from a list, 2 at a time, and makes a vector. For example:

L=[0,0,0,0,0,0,0,0], v_form([2,3,1,1],L). L = [0,1,3,0,0,0,0,0] .

It should be like that, but im getting this:

?- L=[0,0,0,0,0,0,0,0], v_form([2,3,1,1],L).
L = [0, 0, 0, 0, 0, 0, 0, 0] .

My code is:

 replace([_|T], 0, X, [X|T]).
 replace([H|T], I, X, [H|R]):- I > 0, I1 is I-1, replace(T, I1, X, R).

 v_form([],R).
 v_form([X,Y|Z],R) :- replace(R,X,Y,K), v_form(Z,K).

I found this "A is not being Unified with anything in the body of your rules. The way Prolog works is via unification of terms. You cannot "return" A as in procedural languages as such", so im guessing R in my predicate is not being unified, but if thats the case, i dont understand why i get the desired value, when i change v_form([],R). for v_form([],R).:- write(R). i get:

 ?- L=[0,0,0,0,0,0,0,0], v_form([2,3,1,1],L).
 [0,1,3,0,0,0,0,0]
 L = [0, 0, 0, 0, 0, 0, 0, 0]

So, if its true that im not unifying R, why wrtie(R) dont throw an error/exception/prints []/ tell me its not unified, or something among those lines, but instead write the R i want the predicate to return.

1

1 Answers

1
votes

You are 'returning' K instead of R, and must add another output parameter, because in Prolog you cannot 'reassign' a variable. That's the meaning of the statement you cite.

Try

v_form([],R,R).
v_form([X,Y|Z],I,R) :- replace(I,X,Y,K), v_form(Z,K,R).

?- L=[0,0,0,0,0,0,0,0], v_form([2,3,1,1],L,R).
L = [0, 0, 0, 0, 0, 0, 0, 0],
R = [0, 1, 3, 0, 0, 0, 0, 0] .