0

ex [[a,b],[b,c]] to [(a,b),(b,c)].

% Define a predicate that takes a list of lists and returns a list of tuples
convert_list_to_tuple(ListOfLists, ListOfTuples) :-
    % Base case: if the input list is empty, return an empty list
    ListOfLists = [],
    ListOfTuples = [].

convert_list_to_tuple(ListOfLists, ListOfTuples) :-

    [Head|Tail] = ListOfLists,
    Head =.. Tuple,
    convert_list_to_tuple(Tail, TailTuples),
    ListOfTuples = [Tuple|TailTuples].

How to convert a list of list to a list of tuples in prolog? Ex [[a,b],[c.d]]---> [(a,b),(c,d)]

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135

2 Answers2

1

Can just use maplist:

conv([A,B], (A,B)).
?- maplist(conv, [[a,b],[b,c]], L).
L = [(a, b), (b, c)].

Such tuples ("comma lists") are a bad (i.e. confusing) choice. Better to use named atoms:

conv_term(Lst, Term) :-
    Term =.. [v|Lst].
?- maplist(conv_term, [[a,b],[c,d,e]], L).
L = [v(a, b), v(c, d, e)].
brebs
  • 3,462
  • 2
  • 3
  • 12
1

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

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135