; -*- Scheme -*-
;
; $Id: string54.scm,v 1.1 1998/03/16 08:00:01 foner Exp $

;+doc
; procedure: substring:find-by-string-ref
; arguments: pattern string start end if-found if-not-found state
; signature: substring-searcher
;
; Searches for the PATTERN in the STRING by (naively) comparing
; PATTERN against each substring of STRING in turn.  The matching is
; done with a simple loop and character comparison.  For small
; patterns and strings this is likely to be quicker than more
; complicated methods such as Knuth-Morris-Pratt.
; See SUBSTRING:FIND-STRING for a full explanation of all the parameters.
;
; The worst case performance of this algorithm is :- mn -m^2 + m
; where m and n are the lengths of the pattern and string respectively.
;-doc

(define substring:find-by-string-ref
  (lambda (p)
    (let ((pl (string-length p)))
      (lambda (s ss se yes no r)
	(let ((e (- se pl)))
	  (if (or (<= se ss) (< e 0))
	      (no r)
	      (let outer ((ss ss) (r r))
		(if (> ss e)
		    (no r)
		    (let inner ((sp ss) (pp 0))
		      (cond ((= pp pl)
			     (yes ss (lambda (r) (outer (+ 1 ss) r)) r))
			    ((char=? (string-ref s sp) (string-ref p pp))
			     (inner (+ 1 sp) (+ 1 pp)))
			    (else (outer (+ ss 1) r))))))))))))

; eof
