chickadee » srfi-13 » string-fold-right

(string-fold kons knil s [start end]) -> valueprocedure
(string-fold-right kons knil s [start end]) -> valueprocedure

These are the fundamental iterators for strings.

The left-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 right-fold 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."