chickadee » srfi-152 » string-unfold

(string-unfold stop? mapper successor seed [base make-final]) → stringprocedure

This is a fundamental constructor for strings.

  • successor is used to generate a series of "seed" values from the initial seed: seed, (successor seed), (successor² seed), (successor³ seed), …
  • stop? tells us when to stop--when it returns true when applied to one of these seed values.
  • mapper maps each seed value to the corresponding character(s) in the result string, which are assembled into that string in left-to-right order. It is an error for mapper to return anything other than a character or string.
  • base is the optional initial/leftmost portion of the constructed string, which defaults to the empty string "". It is an error if base is anything other than a character or string.
  • make-final is applied to the terminal seed value (on which stop? returns true) to produce the final/rightmost portion of the constructed string. It defaults to (lambda (x) ""). It is an error for make-final to return anything other than a character or string.

string-unfold is a fairly powerful string constructor. You can use it to convert a list to a string, read a port into a string, reverse a string, copy a string, and so forth.

Examples:

(port->string p) = (string-unfold eof-object?
                                  values
                                  (lambda (x) (read-char p))
                                  (read-char p))

(list->string lis) = (string-unfold null? car cdr lis)

(string-tabulate f size) = (string-unfold (lambda (i) (= i size)) f add1 0)

To map f over a list lis, producing a string:

(string-unfold null? (compose f car) cdr lis)

Interested functional programmers may enjoy noting that string-fold-right and string-unfold are in some sense inverses. That is, given operations knull?, kar, kdr, and kons, and a value knil satisfying

(kons (kar x) (kdr x)) = x  and  (knull? knil) = #t

then

(string-fold-right kons knil (string-unfold knull? kar kdr x)) = x

and

(string-unfold knull? kar kdr (string-fold-right kons knil string)) = string.

This combinator pattern is sometimes called an "anamorphism."