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

;+doc
; procedure: string:split-by-whitespace
; arguments: string
; signature: string -> list[string]
;
; Returns a list of whitespace delimited words in STRING
; If STRING is empty or contains only whitespace, then the
; empty list is returned
;
; This is based on the split function in Python, which I believe is
; based on the Perl/Awk one.
;
; > (string:split-by-whitespace " abc d e f  ")
; ("abc" "d" "e" "f")
;
; > (string:split-by-whitespace "")
; ()
;
; > (string:split-by-whitespace "a")
; ("a")
;-doc

(define string:split-by-whitespace
  (lambda (s)
    (let ((result '()) (sl (string-length s)))
      (if (zero? sl)
	  result
	  (let loop ((s s) (sp sl) (r result))
	    (let ((nwp (string::skip-white s sp)))
	      (if (zero? nwp)
		  r
		  (let* ((nsp (string::skip-non-white s nwp))
			 (nr (cons (substring s nsp nwp) r)))
		    (if (zero? nsp) nr (loop s (- nsp 1) nr))))))))))

; This could be written in terms of STRING:FIND-CHARS, but don't
; bother unless you can manage to make it tail recursive like the
; above.

(define string::skip-white
  (lambda (s i)
    (cond
     ((zero? i) i)
     ((char-whitespace? (string-ref s (- i 1))) (string::skip-white s (- i 1)))
     (else i))))
    
(define string::skip-non-white
  (lambda (s i)
    (cond
     ((zero? i) i)
     ((char-whitespace? (string-ref s (- i 1))) i)
     (else (string::skip-non-white s (- i 1))))))

; eof
