; -*- Scheme -*-
;
; $Id: string09.scm,v 1.1 1998/03/16 07:59:35 foner Exp $
;
;------------

;+doc
; procedure: substring:find-by-substring
; arguments: pattern string start end if-found if-not-found state
; signature: substring-searcher
;
; Searches for the PATTERN in the STRING by taking substrings
; and checking if they are string=?.  Unless your Scheme compiler
; optimizes away the substring (which I doubt), this will generate a
; lot of garbage and therefore be quite slow.
; 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-substring
  (lambda (p)
    (let ((pl (string-length p)))
      (lambda (st s e if-found if-not-found r)
	(let ((se (- e pl)))
	  (if (or (>= s e) (< se 0) (> e (string-length st)))
	      (if-not-found r)
	      (let loop ((i s) (r r))
		(cond ((> i se) (if-not-found r))
		      ((string=? p (substring st i (+ i pl)))
		       (if-found i (lambda (r) (loop (+ 1 i) r)) r))
		      (else (loop (+ 1 i) r))))))))))

;+doc
; procedure: string:find-by-substring
; arguments: pattern source if-found if-not-found state
;
; Equivalent to SUBSTRING:FIND-BY-SUBSTRING with a START of 0 and an
; END of (STRING-LENGTH SOURCE)
;-doc

(define string:find-by-substring
  (lambda (p s yes no state)
    (substring:find-by-substring p s 0 (string-length s) yes no state)))

; eof
