[plt-scheme] critique of some code

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Dec 6 22:48:14 EST 2009

You can also assign it to those of your students who understand accumulators (which is what many loops require, but we let students loose on for/do/while/repeat/rinse/one-more-time with nothing but intuition). 

(define (string-index-of str sub)
  (local ([define l2 (explode sub)]
          ;; [Listof 1String] [Listof 1String] -> Boolean 
          ;; is the second string-list a prefix of the first? 
          (define (> l1 l2)
              [(empty? l2) true]
              [(empty? l1) false]
               (and (string=? (first l1) (first l2)) (> (rest l1) (rest l2)))]))
          ;; [Listof 1String] Nat -> Nat u false
          ;; does l2 occur in l
          ;; accumulator: i = (- (length l1) (length l))
          (define (each-position l i)
              ;; could stop when (length  l) < (length l2), needs 2nd accu
              [(empty? l) -1]
              [else (if (> l l2) i (each-position (rest l) (+ i 1)))])))
    (each-position (explode str) 0)))

(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)

Posted on the users mailing list.