Friday, July 03, 2009

Adventures In Prolog - Duplicate List Members

Today's post is about problem 14 from the list of 99 Prolog problems (see here):

(*) Duplicate the elements of a list.
Example:
?- dupli([a,b,c,c,d],X).
X = [a,a,b,b,c,c,c,c,d,d]

Since the problem is marked with one star, a solution should be within reach. Now, to duplicate each element of the list, we do the following:


  1. We traverse the list element by element until we reach the last element, i.e. the empty list.

  2. For each element (excluding the empty list), the element is added twice to a newly built output list.

Given the above solution statement, a possible translation to Prolog code might look like this:



dupli([], []).
dupli(L, O) :- dupli_t(L, [], O).

dupli_t([], Current, Current).
dupli_t([H|T], CList, OutList) :-
append(CList, [H, H], IntermediateList),
dupli_t(T, IntermediateList, OutList).

2 comments:

Anonymous said...

What about:

list_twice([], []).
list_twice([E|Es], [E,E|Rest]) :-
    list_twice(Es, Rest).

Bittis Blog said...

works too - and is clearly more succinct and compact.