Search code examples
prolog

All lists with three repeating elements


All lists with one single element is easy to define using the Prolog prologue:

?- maplist(=(_),L).
   L = []
;  L = [_A]
;  L = [_A,_A]
;  L = [_A,_A,_A]
;  ... .

So this element is repeated over and over again. Fine. But how can I define all lists that repeat three elements in always the same order? Such that I get as answer:

?- Query_with_L.
   L = []
;  L = [_A]
;  L = [_A,_B]
;  L = [_A,_B,_C]
;  L = [_A,_B,_C,_A]
;  L = [_A,_B,_C,_A,_B]
;  L = [_A,_B,_C,_A,_B,_C]
;  L = [_A,_B,_C,_A,_B,_C,_A]
;  ... .
?- L = [a,_,_,b|_], Query_with_L.
   false.
?- L = [_,a,_,_,b|_], Query_with_L.
   false.
?- L = [_,_,a,_,_,b|_], Query_with_L.
   false.

All this just using the Prolog prologue.


Solution

  • Minimal:

    repeat3(Es) :-
        append(Es, _, [_,_,_|Es]).