[plt-scheme] critique of some code
Thanks for both suggestions. I actually tried (in-range ...), but
didn't know about for/first.
Here's the regexp-match-positions version. (I knew PLT Scheme did
regexes, but didn't think about using them.)
(define (string-index-of str sub)
(let
([result (regexp-match-positions sub str)])
(if result
(caar result)
-1)))
On Sun, Dec 6, 2009 at 10:38 PM, Matthias Felleisen
<matthias at ccs.neu.edu> wrote:
>
> Alternatively,
>
> #lang scheme
>
> (require test-engine/scheme-tests)
>
> (define (string-index-of str sub)
> [define l1 (string-length str)]
> [define l2 (string-length sub)]
> (or (for/first ((i (in-range (- l1 l2 -1)))
> #:when (string=? (substring str i (+ i l2)) sub))
> i)
> -1))
>
> (check-expect (string-index-of "abcd" "a") 0)
> (check-expect (string-index-of "abc" "bc") 1)
> (check-expect (string-index-of "abcd" "d") 3)
> (check-expect (string-index-of "abcd" "de") -1)
> (check-expect (string-index-of "abcd" "abcde") -1)
>
> (test)
>
>
> On Dec 6, 2009, at 10:31 PM, Matthias Felleisen wrote:
>
>>
>> Why not use regexp-match-positions?
>>
>> On Dec 6, 2009, at 10:27 PM, Todd O'Bryan wrote:
>>
>>> I still think imperatively, but I'm working on it.
>>>
>>> I just wrote the equivalent of Java's String indexOf() method and am
>>> wondering if I got something that a Schemer would be satisfied with.
>>>
>>> Here's the code, with tests:
>>>
>>> (define (string-index-of str sub)
>>> (let ([l1 (string-length str)]
>>> [l2 (string-length sub)])
>>> (or (and (>= l1 l2)
>>> (ormap
>>> (lambda (start)
>>> (if (string=? (substring str start (+ start l2))
>>> sub)
>>> start
>>> #f))
>>> (build-list (add1 (- l1 l2)) (lambda (x) x))))
>>> -1)))
>>>
>>> (check-expect (string-index-of "abcd" "a") 0)
>>> (check-expect (string-index-of "abc" "bc") 1)
>>> (check-expect (string-index-of "abcd" "d") 3)
>>> (check-expect (string-index-of "abcd" "de") -1)
>>> (check-expect (string-index-of "abcd" "abcde") -1)
>>>
>>> Did I miss something that would have made this clearer or more succinct?
>>>
>>> Todd
>>> _________________________________________________
>>> For list-related administrative tasks:
>>> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>>
>> _________________________________________________
>> For list-related administrative tasks:
>> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
>