- string-foldprocedure
- string-fold-rightprocedure
These are the fundamental iterators for strings.
The string-fold operator maps the kons procedure across the string from left to right
(... (kons s[2] (kons s[1] (kons s[0] knil))))
In other words, string-fold obeys the (tail) recursion
(string-fold kons knil s start end) = (string-fold kons (kons s[start] knil) start+1 end)
The string-fold-right operator maps the kons procedure across the string from right to left
(kons s[0] (... (kons s[end-3] (kons s[end-2] (kons s[end-1] knil)))))
obeying the (tail) recursion
(string-fold-right kons knil s start end) = (string-fold-right kons (kons s[end-1] knil) start end-1)
Examples:
;;; Convert a string to a list of chars. (string-fold-right cons '() s) ;;; Count the number of lower-case characters in a string. (string-fold (lambda (c count) (if (char-lower-case? c) (+ count 1) count)) 0 s) ;;; Double every backslash character in S. (let* ((ans-len (string-fold (lambda (c sum) (+ sum (if (char=? c #\\) 2 1))) 0 s)) (ans (make-string ans-len))) (string-fold (lambda (c i) (let ((i (if (char=? c #\\) (begin (string-set! ans i #\\) (+ i 1)) i))) (string-set! ans i c) (+ i 1))) 0 s) ans)
The right-fold combinator is sometimes called a "catamorphism."