Why would you use something like (a,b)
? It works fine for arity 2, but add more elements — (a,b,c,d,e)
— and it gets ugly:
','( a , ','( b , ','( c , ','( d , e ) ) ) )
Prolog's lists are simple syntactic sugar on top of the term ./2
, with the atom []
representing the empty list. Hence, the list [a,b]
is actually the term .(a,.(b,[]))
. Congratulations! — you've just reinvented Prolog's list in a clumsy way.
Use a term instead.
Turning a list into such a tuple is trivial — just prepend the list with the desired functor (name) you want to use for the tuple and use the in-built =../2
to map between the list and the tuple:
list_tuple( L , T ) :- T =.. [ tuple | L ] .
Once you have that, turning a list of lists into a list of tuples is likewise trivial:
lists_tuples( [] , [] ) .
lists_tuples( [L|Ls] , [T|Ts] ) :- list_tuple(L,T), lists_tuples(Ls,Ts) .
Evaluating
?- lists_tuples( [ [] , [a] , [a,b] , [a,b,c] , [a,b,c,d], [a,b,c,d,e] ] , Ts ) .
Yields the expected
Ts = [
tuple,
tuple(a),
tuple(a,b),
tuple(a,b,c),
tuple(a,b,c,d),
tuple(a,b,c,d,e)
]
And evaluating
?- lists_tuples( L, [tuple,tuple(a),tuple(a,b),tuple(a,b,c),tuple(a,b,c,d),tuple(a,b,c,d,e)] ).
Similarly yields the expected
L = [[], [a], [a,b], [a,b,c], [a,b,c,d], [a,b,c,d,e]]
You can fiddle with it at https://swish.swi-prolog.org/p/JDhVptgN.pl