/************************************************
File: gen0.pl
Author: Mihaela Malita
Title: Generate words over an alphabet [a,b]
Example.
Generate all words of length 3.
?- gen(3,[a,b],L).
L = [a, a, a] ; % type ; for more solutions
L = [a, a, b] ;
L = [a, b, a] ;
L = [a, b, b] ;
L = [b, a, a] ;
L = [b, a, b] ;
L = [b, b, a] ;
L = [b, b, b] ;
No % means there are no more solutions
Generate all words of length from 1 to 3
?- generate(3,[a,b],L),write(L),nl,fail. % provoke backtracking with fail
[a]
[b]
[a, a]
[a, b]
[b, a]
[b, b]
[a, a, a]
[a, a, b]
[a, b, a]
[a, b, b]
[b, a, a]
[b, a, b]
[b, b, a]
[b, b, b]
No
***************************************************/
/* mem(L1,L2). Force all elements from L1 to be members of L2.
?- mem([X,Y],[a,b,c]).
X = Y = a ;
X = a ,Y = b ;
X = a ,Y = c ;
X = b ,Y = a ;
X = Y = b ;
X = b ,Y = c ;
X = c ,Y = a ;
X = c ,Y = b ;
X = Y = c ;
*/
mem([],L2).
mem([H|T],L2):-member(H,L2),mem(T,L2).
% Make a list with variables of length N and fill it with elements from L
gen(N,L,R):-length(R,N),mem(R,L).
% Generate all words with length 1 to N
generate(N,L,R):- between(1,N,K),gen(K,[a,b],R).