Ed1yang
Ed1yang

Reputation: 33

Tuple to list in Prolog

Recently I'm doing a program and it requires me to convert a tuple to a list.

Tuples look like this: [(1,[1,2,3,4]), (1,[2,3,4,5]), ...]

And what I want is a list of: [(1,2,3,4), (2,3,4,5), ...]

Is there any way I can do that?

Upvotes: 2

Views: 1161

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476740

In Prolog, (1, 4, 2, 5), is syntactical sugar for (1, (4, (2, 5))), just like [1, 4, 2, 5] is syntactical sugar for [1|[4|[2|[5|[]]]]] (note however that the list ends with an empty list [], whereas for a tuple, it ends with a (2, 5)).

list_tuple([A, B], (A, B)).
list_tuple([A|T], (A, B)) :-
    list_tuple(T, B).

So then we can write a predicate to unpack the list out of the 2-tuple, and convert the list to a tuple:

conv((_, L), R) :-
    list_tuple(L, R).

and we can use maplist/3 to perform the conversion over the entire list:

convlist(As, Bs) :-
    maplist(conv, As, Bs).

This then yields:

?- convlist([(1,[1,2,3,4]), (1,[2,3,4,5])], R).
R = [(1, 2, 3, 4),  (2, 3, 4, 5)] ;
false.

Tuples are however in Prolog not very common, so I do not see why you do not stick with the list itself.

Upvotes: 2

Related Questions