[m-rev.] for review: string__substring in Mercury

Ralph Becket rbeck at microsoft.com
Fri Sep 7 23:49:06 AEST 2001


> From: Yoann Dubreuil [mailto:ydu at miscrit.be]
> Sent: 07 September 2001 14:37
> 
> 
> ===================================================================
> 
> 
> Estimated hours taken: 1
> User: ydu
> Branches: main
> 
> library/string.m:
> 	Implementation of string__substring in Mercury.
> 
> Index: string.m
> ===================================================================
> RCS file: /home/mercury1/repository/mercury/library/string.m,v
> retrieving revision 1.158
> diff -u -r1.158 string.m
> --- string.m	6 Sep 2001 12:05:20 -0000	1.158
> +++ string.m	7 Sep 2001 13:33:50 -0000
> @@ -449,7 +449,7 @@
>
%-----------------------------------------------------------------------
------%
> 
>  :- implementation.
> -:- import_module bool, std_util, int, float, require.
> +:- import_module bool, std_util, int, float, require, integer.
> 
>  :- pred string__to_int_list(string, list(int)).
>  :- mode string__to_int_list(out, in) is det.
> @@ -2115,6 +2115,21 @@
>  %	string__substring(String, Start, Count, Substring):
>  */
> 
> +string__substring(Str::in, Start::in, Count::in, SubString::out) :-
> +	string__to_char_list(Str, Chars0),
> +	string__length(Str, Length),
> +	( Count >= Length - Start ->
> +		Count1 = Length - Start
> +	;
> +		Count1 = Count
> +	),
> +	( list__drop(Start, Chars0, Chars1),
> +	  list__take(Count1, Chars1, Chars) ->
> +		SubString = string__from_char_list(Chars)
> +	;
> +			SubString = ""
> +	).
> +

A slightly more efficient way of doing this is

string__substring(Str::in, Start::in, Count::in, SubStr::out) :-
    End    = min(Start + Count, string__length(Str)),
    SubStr = string__from_char_list(strchars(Start, End, Str)).

:- func strchars(int, int, string) = list(char).

strchars(I, End, Str) =
    ( if I >= End
      then []
      else [string__index_det(Str, I) | strchars(I + 1, End, Str)]
    ).

This way we avoid creating any more cons cells than strictly
necessary.

Cheers,

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