for review: additions to list module

Peter David ROSS petdr at cs.mu.OZ.AU
Tue Jun 23 15:54:45 AEST 1998


Hi,

Could someone please review this?

===================================================================


Estimated hours taken: 0.5

Add some more utility functions into the list module.

library/list.m:
    Add the predicateds list__repeat and list__replace_nth.
    Also update the comment on list__nth_member_search to indicate which
    index numbering scheme it uses.
    


Index: list.m
===================================================================
RCS file: /home/staff/zs/imp/mercury/library/list.m,v
retrieving revision 1.82
diff -u -r1.82 list.m
--- list.m	1998/04/08 14:45:42	1.82
+++ list.m	1998/06/03 05:32:02
@@ -229,6 +229,12 @@
 :- pred list__replace_all(list(T), T, T, list(T)).
 :- mode list__replace_all(in, in, in, out) is det.
 
+	% list__replace_nth(List0, N, R, List) is true iff List is List0 
+	% with Nth element (starting from 1) replaced with R.
+	%
+:- pred list__replace_nth(list(T), int, T, list(T)).
+:- mode list__replace_nth(in, in, in, out) is semidet.
+
 	% list__sort_and_remove_dups(List0, List):
 	%	List is List0 sorted with duplicates removed.
 	%
@@ -255,7 +261,7 @@
 :- mode list__perm(in, out) is nondet.
 
 	% list__nth_member_search(List, Elem, Position):
-	%	Elem is the Position'th member of List.
+	%	Elem is the Position'th (starting from 1) member of List.
 	%
 :- pred list__nth_member_search(list(T), T, int).
 :- mode list__nth_member_search(in, in, out) is semidet.
@@ -317,6 +323,13 @@
 :- pred list__all_same(list(T)).
 :- mode list__all_same(in) is semidet.
 
+	% list__repeat(X, N, L)
+	%
+	% Make a list L which has X in all N positions.
+	%
+:- pred list__repeat(T, int, list(T)).
+:- mode list__repeat(in, in, out) is det.
+
 	% list__last(List, Last) is true
 	%	if Last is the last element of List.
 :- pred list__last(list(T), T).
@@ -585,6 +598,15 @@
 		list__replace_all(Xs, Y, Z, L0)
 	).
 
+list__replace_nth([X | Xs], P, R, L) :-
+	( P = 1 ->
+		L = [R | Xs]
+	;
+		P1 is P - 1,
+		list__replace_nth(Xs, P1, R, L0),
+		L = [X | L0]
+	).
+
 %-----------------------------------------------------------------------------%
 
 list__member(X, [X | _]).
@@ -896,6 +918,19 @@
 list__all_same_2(_, []).
 list__all_same_2(H, [H|T]) :-
 	list__all_same_2(H, T).
+
+%-----------------------------------------------------------------------------%
+
+list__repeat(X, N, Out) :-
+	(
+		N = 0
+	->
+		Out = []
+	;
+		N1 is N - 1,
+		list__repeat(X, N1, T),
+		Out = [X|T]
+	).
 
 %-----------------------------------------------------------------------------%



More information about the developers mailing list