Reputation: 3
The goal is to create pairs/triplets/quartets from short lists, since these lists occur in a list of lists that I flatten. Since I want these elements to stay connected, I need a way to flatten the lists without losing the connection between the items in these particular lists.
In short, [a, b, c] needs to be converted to a-b-c. In theory long lists need to be handled too, but in reality only short lists will be relevant.
What I tried so far (which I know is horribly wrong):
create_pair([], Pair).
create_pair([H, H1|T], Pair):-
NPair = H-H1,
create_pair(T, NPair).
This is just for the case of where the list has 2 elements.
Upvotes: 0
Views: 513
Reputation: 74267
If the data structure you want to convert the short lists to doesn't really matter, you can just use =../2
to convert the list to a term. Something like:
list_term(L,T) :- T =.. [ listlet | L ].
So evaluating list_to_term( [a,b,c], T)
binds T
as listlet(a,b,c)
and evaluating list_to_term( L , listlet(a,b,c,d) )
binds L
as [a,b,c,d]
.
See https://swish.swi-prolog.org/p/list-to-term.pl for a runnable playground.
Upvotes: 0
Reputation: 22585
You can build your pair/triplet/quartet/... by joining the two first items of the list and replacing it with your connection term until the whole list is processed:
create_ntets([H], H).
create_ntets([H,H1|T], NTet):-
create_ntets([H-H1|T], NTet).
This procedure assumes there is no 0-tet. Sample runs
?- create_ntets([a,b,c], Triplet).
Triplet = a-b-c
?- create_ntets([a,b,c,d], Quartet).
Quartet = a-b-c-d
Upvotes: 1