[plt-scheme] critique of some code
Todd, your solution looks OK to me, and you have good tests for some
edge cases.
FWIW, here's how I would have done it, if I were constrained to using
"substring" (which will do lots of allocations), because I love using
named-"let" as much as possible:
(define (string-index-of str sub)
(let* ((str-len (string-length str))
(sub-len (string-length sub))
(max-start (- str-len sub-len)))
(let loop ((start 0))
(cond ((> start max-start) #f)
((string=? (substring str start (+ start sub-len))
sub)
start)
(else (loop (+ 1 start)))))))
For efficiency, but constrained to using only R5RS Scheme primitives,
I'd try two more approaches: (1) bursting both strings into lists of
characters and comparing them as lists somehow; (2) using "string-ref"
on each character, rather than "substring", to reduce allocations.
Small nit: I'd return #f rather than -1. Java uses the cryptic -1 value
because its crude type system encourages it to, but you don't have that
problem. Using #f also conveniently means that you can use the result
of the procedure as a Boolean value, including with the sometimes very
convenient "cond" "=>" syntax.
--
http://www.neilvandyke.org/