diff: added bag__to_list to bag.m

Christopher Rodd SPEIRS crs at students.cs.mu.oz.au
Fri Oct 3 19:25:14 AEST 1997


Fergus, could you review this change to bag.m


library/bag.m:
	Added a bag__to_list/2 predicate which produces a list 
	from a bag.

Index: bag.m
===================================================================
RCS file: /home/mercury1/repository/mercury/library/bag.m,v
retrieving revision 1.11
diff -u -r1.11 bag.m
--- 1.11	1997/07/27 15:06:34
+++ bag.m	1997/08/13 01:55:18
@@ -36,6 +36,11 @@
 :- pred bag__from_list(list(T), bag(T)).
 :- mode bag__from_list(in, out) is det.
 
+	% make a list from a bag.  The constructed list may contain
+	% duplicates.
+:- pred bag__to_list(bag(T), list(T)).
+:- mode bag__to_list(in, out) is det.
+
 	% given a bag, produce a sorted list with no duplicates 
 	% containing all the values in the bag
 :- pred bag__to_list_without_duplicates(bag(T), list(T)).
@@ -127,7 +132,7 @@
 %---------------------------------------------------------------------------%
 :- implementation.
 
-:- import_module map, int, require.
+:- import_module map, int, require, assoc_list, std_util.
 
 :- type bag(T)		==	map(T, int).
 
@@ -161,6 +166,26 @@
 	bag__init(Bag0),
 	bag__insert_list(Bag0, List, Bag).
 
+bag__to_list_without_duplicates(Bag, List) :-
+	map__keys(Bag, List).
+
+bag__to_list(Bag, List) :-
+	map__to_assoc_list(Bag, AssocList),
+	bag__to_list_2(AssocList, List).
+
+:- pred bag__to_list_2(assoc_list(T, int), list(T)).
+:- mode bag__to_list_2(in, out) is det.
+bag__to_list_2([], []).
+bag__to_list_2([X - Int | Xs ], Out) :-
+	( Int =< 0 ->
+		bag__to_list_2(Xs, Out)
+	;
+		NewInt is Int - 1,
+		bag__to_list_2([X - NewInt | Xs], Out0),
+		Out = [X | Out0]
+	).
+		
+
 %---------------------------------------------------------------------------%
 
 bag__delete(Bag0, Item, Bag) :- 	% det
@@ -202,11 +227,6 @@
 
 %---------------------------------------------------------------------------%
 
-bag__to_list_without_duplicates(Bag, List) :-
-	map__keys(Bag, List).
-
-%---------------------------------------------------------------------------%
-
 bag__subtract(Bag0, SubBag, Bag) :-
 	( map__remove_smallest(SubBag, SubKey, SubVal, SubBag0) ->
 		( map__search(Bag0, SubKey, Val) ->



More information about the developers mailing list