diff options
Diffstat (limited to 'csc/strings.csc')
| -rw-r--r-- | csc/strings.csc | 69 |
1 files changed, 34 insertions, 35 deletions
diff --git a/csc/strings.csc b/csc/strings.csc index 75175f0..255a2fd 100644 --- a/csc/strings.csc +++ b/csc/strings.csc @@ -1,26 +1,24 @@ (define-library (csc strings) (export - contains - find + contains? + has-prefix? + index join - not-found-error? - prefix? split str-quote) (import (scheme base) (only (scheme case-lambda) case-lambda) (only (scheme write) write) (only (csc list) intercalate) - (only (csc loop) loop)) + (only (csc loop) + loop + return)) (begin - (define prefix? - (case-lambda - ((prefix str) (prefix? prefix str 0)) - ((prefix str start) - (and (<= (string-length prefix) (- (string-length str) start)) - (string=? prefix (substring str start (+ start (string-length prefix)))))))) + (define (has-prefix? str prefix) + (and (<= (string-length prefix) (string-length str)) + (string=? prefix (substring str 0 (string-length prefix))))) (define (str-quote s) @@ -29,37 +27,38 @@ (get-output-string out))) - (define-record-type <not-found-error> - (make-not-found-error) - not-found-error?) - + (define (index s substr) + (loop for i from 0 + for s = s then (string-copy s 1) + until (string=? "" s) + if (has-prefix? s substr) + return i + finally (return -1))) - (define find - (case-lambda - ((match str) (find match str 0 (string-length str))) - ((match str start) (find match str start (string-length str))) - ((match str start end) - (let loop ((i start)) - (cond ((>= i end) (raise (make-not-found-error))) - ((prefix? match str i) i) - (else (loop (+ 1 i)))))))) - - (define (contains s substr) + (define (contains? s substr) (if (string=? "" substr) #t - (guard (e ((not-found-error? e) #f)) - (find substr s) - #t))) + (not (negative? (index s substr))))) (define (join sep strings) (apply string-append (intercalate sep strings))) - (define (split s sep) - (loop for s* = s then (string-copy s* (+ i (string-length sep))) - for i = (guard (e ((not-found-error? e) (string-length s*))) - (find sep s*)) - collect (substring s* 0 i) - while (< i (string-length s*)))))) + (define split + (case-lambda + ((s sep n) + (if (= 0 n) + '() + (loop for n = n then (- n 1) + for s = s then (string-copy s (+ i (string-length sep))) + for i = (let ((i (index s sep))) + (if (or (negative? i) + (= 1 n)) + (string-length s) + i)) + collect (substring s 0 i) + while (< i (string-length s))))) + ((s sep) + (split s sep -1)))))) |
