Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a list of lists

Status
Not open for further replies.

west01

Programmer
Mar 5, 2008
1
Hi to all,

I need a help...

I want to regroup a sorted list in a list of lists.
I would like to regroup all the same elements in a sorted list.

Examples:

?- regroup([1,1,2,2,3,4], L).
L = [[1,1], [2,2], [3], [4]];
NO

?- regroup([1,2,3,4], L).
L = [[1], [2], [3], [4]];
NO


Thank you for your help.
 
The problem with the lists is that you almost always have to take the recursively!

Here is the solution:

% Edge case: 1 element turns into a list with one element
regroup([A],[[A]]).
% Every next element it cheks all the memebers of list LL1 you get from Tail and checks if their members are equal to H and adds H into them (delets X and inserts X1 which is for one sam number bigger than X)
regroup([H|T],LL3):-
regroup(T,LL1),
member(X,LL1),
member(H,X),
insert(H,X,X1),
delete(X,LL1,LL2),
insert(X1,LL2,LL3),!.
% ! in above last line prevents us going into next rule if upper succeeds in any case. else it means there is no list contaning H, so we just add a list with H to list LL2
regroup([H|T],LL2):-
regroup(T,LL1),
insert([H],LL1,LL2).

% Here are the also used insert and delete rules, member should be implemented in the newer versions of Prolog.
delete(X,[X|T],T).
delete(X,[Y|T1],[Y|T2]):-
delete(X,T1,T2).

insert(X,L,L1):-
delete(X,L1,L).

Best regards!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top