Daniel Bastos
Daniel Bastos

Reputation: 150

How to get a list with all the possible combinations of the elements inside another list?

I have a list that has as elements: atoms and other lists. I ask the following:

-? totobola([1,x,2,1,x,2,1,x,2,1,x,[1,x],[1,x,2]],LS).


I want the LS to be a list where I would show every atom followed by the possible combinations of the lists inside the given list.

LS=[1,x,2,1,x,2,1,x,2,1,x,1,1];
LS=[1,x,2,1,x,2,1,x,2,1,x,1,x];
LS=[1,x,2,1,x,2,1,x,2,1,x,1,2];
LS=[1,x,2,1,x,2,1,x,2,1,x,x,1];
LS=[1,x,2,1,x,2,1,x,2,1,x,x,x];
LS=[1,x,2,1,x,2,1,x,2,1,x,x,2];
no

My current solution:

lista([_|_]):- true, !.
lista(_):- false.

totobola([],[]).
totobola([X|T1],[Y|T2]):-
    lista(X),
    !,
    member(Y,X),
    totobola(T1,T2).
totobola([X|T1],[X|T2]):-
    totobola(T1,T2).

With lista I check if X is a list or not but instead of getting LS=[1,x,2,1,x,2,1,x,2,1,x,1,1]; I get LS = [1, x, 2, 1, x, 2, 1, x, 2|...]

Can someone guide me or at least tell me what I'm doing wrong or less right?

Thanks in advance!

Upvotes: 1

Views: 269

Answers (2)

Fred
Fred

Reputation: 1

We had this exercise in ALGAV class,ISEP (Portugal) , and the solution was:

is_list(X) :- var(X), !, fail.
is_list([]).
is_list([_|T]) :- is_list(T).

totobola([],[]).
totobola([H|T],[X|LR]):- is_list(H), !, member(X,H), totobola(T,LR). 
totobola([H|T],[H|LR]):- totobola(T,LR).

Upvotes: 0

Ricardo Gomes
Ricardo Gomes

Reputation: 140

Make a 'repeat.' query then press 'w' key and '.' you will enter write mode and see all the values within the list.

?- repeat.
true [write] --> after pressing w once
true . --> enter a dot to exit

Upvotes: 0

Related Questions