FrankTan
FrankTan

Reputation: 1686

prolog appending lists

i have a problem i take in input a list, and i want append it's element to another that i want in output

this is my code :

run([],L).
run([X|Y],Lista) :- X =..Total, append(Total,Lista,ListaR), run(Y,ListaR), stamp(ListaR).

stamp([]).
stamp([X|Y]) :- nl, write(X), stamp(Y).

if I run it with:

run([p(X,Y,Z),h(Z,P,Q)],[]).

it will print out:

h
_G238
_G244
_G245
p
_G236
_G237
_G238
p
_G236
_G237
_G238
true.

why it contain 2 time the p ? what is wrong?

_GXXX are variables...

Upvotes: 0

Views: 1683

Answers (2)

svick
svick

Reputation: 244757

It prints p twice, because you print the result at each level of recursion. If you want to print it only once at the end, do so:

run([],L) :- stamp(L).
run([X|Y],Lista) :- X =..Total, append(Total,Lista,ListaR), run(Y,ListaR).

Upvotes: 1

Gökhan Uras
Gökhan Uras

Reputation: 181

For appending lists you don't need to write this recursive function append/3 do that for you.

?- append([a,b],[k,l],NewList).
NewList = [a, b, k, l].

But i tried your code in swi-prolog it doesn't give your output but it produces wrong result because you are printing the list more than one in recursion part. You can try something like that

run(List1,List2) :- append(List1,List2,ListResult), stamp(ListResult).

Hope it helps.

Upvotes: 1

Related Questions