Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All lists with three repeating elements

Tags:

prolog

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.

like image 679
false Avatar asked Aug 22 '26 20:08

false


1 Answers

Single clause, not subject to occurs-check:

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

Finally:

repeat3(Es) :-
    append(Es, [_,_,_], [_,_,_|Es]).
like image 78
notoria Avatar answered Aug 26 '26 04:08

notoria