[m-rev.] for review: improve string__replace and string__replace_all

Ralph Becket rafe at cs.mu.OZ.AU
Tue Dec 7 11:44:24 AEDT 2004


Peter Ross, Monday,  6 December 2004:
> On Mon, Dec 06, 2004 at 11:40:20AM +1100, Ralph Becket wrote:
> > Peter Ross, Sunday,  5 December 2004:
> > > Index: library/string.m
> > > ===================================================================
> > > RCS file: /home/mercury1/repository/mercury/library/string.m,v
> > > retrieving revision 1.221
> > > diff -u -r1.221 string.m
> > > --- library/string.m	10 Nov 2004 07:12:38 -0000	1.221
> > > +++ library/string.m	5 Dec 2004 16:26:38 -0000
> > > @@ -609,7 +609,9 @@
> > >  
> > >  string__replace_all(Str, Pat, Subst, Result) :-
> > >  	( Pat = "" ->
> > > -		copy(Str, Result)
> > > +		F = (func(C, L) = [char_to_string(C) ++ Subst | L]),
> > > +		Foldl = string__foldl(F, Str, []),
> > > +		Result = append_list([Subst | list__reverse(Foldl)])
> > >  	;
> > >  		PatLength = string__length(Pat),
> > >  		ReversedChunks = replace_all(Str, Pat, Subst, PatLength, 0, []),
> > 
> > Just as a minor efficiency hack, I'd move the char_to_string(C) computation 
> > out of the lambda - loop invariant hoisting isn't turned on until -O5 or
> > 6 IIRC and even then it might not hoist it.
> > 
> I would love to move it out, but then the program wouldn't be correct.
> As the value for C supplied is for each character in the string, so it
> is always changing.

Ah, yes.  I am a fool.

Can I suggest the following implementation for the then-goal?

	F = ( func(C, L) = [Subst, char_to_string(C) | L] ),
	Result = string__append_list(foldr(F, Str, [Subst]))

This avoids the call to reverse and some excess string copying.

-- Ralph
--------------------------------------------------------------------------
mercury-reviews mailing list
post:  mercury-reviews at cs.mu.oz.au
administrative address: owner-mercury-reviews at cs.mu.oz.au
unsubscribe: Address: mercury-reviews-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-reviews-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the reviews mailing list