;; Two versions of naive string matching ;; John David Stone ;; Department of Mathematics and Computer Science ;; Grinnell College ;; stone@cs.grinnell.edu ;; created November 21, 1999 ;; last revised November 20, 2000 ;; The naive string matcher folds over the number of possible positions at ;; which a match might occur, attempting a match at each position and ;; adding the guide (namely, SHIFT) to the result set if a match is found ;; by direct comparison of substrings. (define (naive-string-matcher text pattern) (let ((pattern-length (string-length pattern))) (lower-ply-natural (max 0 (successor (- (string-length text) pattern-length))) (lambda (shift valid-shifts) (if (string=? (substring text shift (+ shift pattern-length)) pattern) (adjoin-to-set shift valid-shifts) valid-shifts)) (set)))) ;; We can avoid allocating storage for substrings copied out of TEXT by ;; doing the character-by-character in place, directly matching each ;; character of PATTERN to a character at a computed position within TEXT. (define (naive-string-matcher text pattern) (let ((pattern-length (string-length pattern))) (let ((matches? (lambda (shift) (letrec ((matches-from? (lambda (position) (or (= position pattern-length) (and (char=? (string-ref pattern position) (string-ref text (+ shift position))) (matches-from? (successor position))))))) (matches-from? 0))))) (lower-ply-natural (max 0 (successor (- (string-length text) pattern-length))) (lambda (shift valid-shifts) (if (matches? shift) (adjoin-to-set shift valid-shifts) valid-shifts)) (set)))))