Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - Twice List

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).
like image 316
HTLINK Avatar asked Feb 14 '23 09:02

HTLINK


1 Answers

Start with the base case,

twice([], 

"twice of nothing is" ... nothing, right?

          []).

Now, what if there is something there?

twice([A|B], 

then what? do we want the result to start from A? You bet,

              [A,

what next goes there?

                  ...

(fill it in, please). Then, there's the rest:

                       | Rest] ):-

so, we continue. The Rest is taken from B:

      twice(B, ...).

fill this in too, please.

like image 115
Will Ness Avatar answered Feb 23 '23 15:02

Will Ness