Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prolog, copying lists

Tags:

logic

prolog

I am attempting to get my arms around some basic prolog but struggling a bit in the process. In specific - I am trying to get through a list of items and copy it, item by item into a new list. I can get it to reverse, but I am finding it trickier doing it without reversing.

Ive been trying the following -

copy(L,R) :- accCp(L,R).

accCp([],R).
accCp([H|T],R) :- accCp(T,H).

When i run a trace on this - i can see the individual items being copied across, but they get 'lost', and dont form a growing list (at R, as i was hoping). How could i achivie this?

Many thanks

like image 481
v_a_bhatia Avatar asked Dec 16 '09 01:12

v_a_bhatia


1 Answers

Your base case needs to set the copy list to empty when the original list is empty. Then, the recursive case needs to take H from list L and add it to the head of list R:

copy(L,R) :- accCp(L,R).
accCp([],[]).
accCp([H|T1],[H|T2]) :- accCp(T1,T2).

When you call copy, it works its way down to the base case, where it sets R to an empty list. Then, as it works back up, it keeps appending the head H of known list [H|T1] to the beginning of variable list [H|T2]. It does that until the original case is reached, at which point R contains a full copy of L.

like image 132
Kaleb Brasee Avatar answered Sep 27 '22 22:09

Kaleb Brasee