I'd like to be able to generate all possible lists of elements, with an ‘and’ between the last two elements (as in normal language). There should be no duplicate elements in any list. So ‘three, two, and, four’ is a correct list, as is ‘two and one’, or ‘five, three, four, one, and, two’. I am not looking for single-element lists.
I’ve written the following program. When I query Prolog about a specific list, it will tell me correctly if it is a valid list. However, when I query list(X), it only generates lists with two elements.
Could someone suggest a way to make it generate all possible lists, using the given elements? Thank you!
I have facts such as
element([one]).
element([two]).
element([three]).
element([four]), etc. etc.
My predicates to generate a list L are:
list(L):-
element(E1),
element(E2),
E1 \= E2,
append(E1, [and], X),
append(X, E2, L).
%recursive case
list(L):-
element(E),
append(E, [','], X),
append(X, Y, L),
list(Y),
not_in(E, Y).
not_in([X], [Y]):- X \= Y.
not_in([X], [H|T]):-
[X] \= [H],
not_in([X], T).