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: We traverse the list element by element until we reach the last element, i.e. the empty list. 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).
Comments