for review again: Additions to list module.

Peter David ROSS petdr at cs.mu.OZ.AU
Tue Jun 23 17:42:40 AEST 1998


Fergus,

Here is the new diff.

I had to look at the source code to determine what the indexing scheme
was used, so I think that the comment is useful.  What confused me was
the fact that we had to list__index{0,1}.

Pete.


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


Estimated hours taken: 0.5

Add some more utility functions into the list module.

library/list.m:
    Add the predicate 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/23 07:32:56
@@ -229,6 +229,14 @@
 :- 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 replaced with R.
+	% Aborts if N < 1 and fails if length of List0 < N.
+	% (Position numbers start from 1.)
+	%
+:- 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.
 	%
@@ -256,6 +264,7 @@
 
 	% list__nth_member_search(List, Elem, Position):
 	%	Elem is the Position'th member of List.
+	% 	(Position numbers start from 1.)
 	%
 :- pred list__nth_member_search(list(T), T, int).
 :- mode list__nth_member_search(in, in, out) is semidet.
@@ -583,6 +599,29 @@
 	;
 		L = [X | L0],
 		list__replace_all(Xs, Y, Z, L0)
+	).
+
+list__replace_nth(Xs, P, R, L) :-
+	(
+		P =< 0
+	->
+		error("list__replace_nth: Can't replace element whose index position is less then 1.")
+	;
+		list__replace_nth_2(Xs, P, R, L)
+	).
+
+:- pred list__replace_nth_2(list(T), int, T, list(T)).
+:- mode list__replace_nth_2(in, in, in, out) is semidet.
+
+list__replace_nth_2([X | Xs], P, R, L) :-
+	(
+		P = 1 
+	->
+		L = [R | Xs]
+	;
+		P1 is P - 1,
+		list__replace_nth(Xs, P1, R, L0),
+		L = [X | L0]
 	).
 
 %-----------------------------------------------------------------------------%

----
 +----------------------------------------------------------------------+
 | Peter Ross      M Sci/Eng Melbourne Uni                              |
 | petdr at cs.mu.oz.au  WWW: www.cs.mu.oz.au/~petdr/ ph: +61 3 9344 9158  |
 +----------------------------------------------------------------------+



More information about the developers mailing list