Prolog - Twice List

Viewed 2316

I am practicing prolog and all and this one is killing me. Trying to do this:

twice([1,2,3],X).

the output I want is

X = [1,1,2,2,3,3].

Here's my latest attempt:

twice([HD|TL],[HD2|TL2]):-
    twice(TL,[HD,HD2|TL2]).

twice([],[HD|TL]).

//New

twice([],[]).
twice([A|B],Out):- twice([A|B],[A,A|Rest],
                   twice(B,Rest).
3 Answers

Try this:

twice([], []).
twice([A|B], [A,A|Rest]) :- twice(B, Rest).
Related