chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Chicken-users] Re: (sorry, ist verlorengegangen)


From: Sven . Hartrumpf
Subject: [Chicken-users] Re: (sorry, ist verlorengegangen)
Date: Sat, 26 Jul 2003 12:21:34 +0200 (CEST)

On 26 Jul 2003, felix <address@hidden> wrote: 
> 
> (define (string-compare3 s1 s2)
>    (##sys#check-string s1 'string-compare3)
>    (##sys#check-string s2 'string-compare3)
>    (let ((len1 (##sys#size s1))
>      (len2 (##sys#size s2)) )
>      (let ([c (##core#inline "C_string_compare" s1 s2 (fxmin len1 len2))])
>        c) ) )
> 
> It uses strncmp(), so it won't work with embedded '\0's.

Therefore calling memcmp() (C_memcmp) could be a plus.

(And memcmp can be implemented more efficiently than strncmp, I hope,
because you don't have to test for \0 and (on bigendian machines only?, with
appropriate string alignment) one can compare more than a byte inside the
comparison loop of memcmp. BTW: string comparison is an area where Scheme can
outperform C :-) )

> The following implementation does it more R5RSly, since
> the standard specifies that strings that are equal, but have
> different lengths, still compare differently, i.e.
> 
>    (string<? "abc" "abcd")
> 
> is true.

Yes, the second specification is definitely more useful.
 
> (define (string-compare3 s1 s2)
>    (##sys#check-string s1 'string-compare3)
>    (##sys#check-string s2 'string-compare3)
>    (let ((len1 (##sys#size s1))
>      (len2 (##sys#size s2)) )
>      (let ([cmp (##core#inline "C_string_compare" s1 s2 (fxmin len1 len2))])
>        (cond [(fx< cmp 0) -1]
>          [(fx> cmp 0) 1]
>          [(fx< len1 len2) -1]
>          [(fx> len1 len2) 1]
>          [else 0] ) ) ) )

Can this be optimized? Maybe like this (maybe we need some benchmarks, so feel
free to integrate your version and I will report runtime comparisons):

(define (string-compare3 s1 s2)
  (##sys#check-string s1 'string-compare3)
  (##sys#check-string s2 'string-compare3)
  (let* ((len1 (##sys#size s1))
         (len2 (##sys#size s2))
         (len-diff (fx- len1 len2))
         (m (if (negative? len-diff) len1 len2))) ; fx-negative? ???
    (let ([cmp (##core#inline "C_string_compare" s1 s2 m)])
      (if (fx= cmp 0)
        len-diff
        cmp))))

Ciao
Sven




reply via email to

[Prev in Thread] Current Thread [Next in Thread]