[plt-scheme] critique of some code

From: Todd O'Bryan (toddobryan at gmail.com)
Date: Sun Dec 6 22:27:10 EST 2009

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


Posted on the users mailing list.