chickadee » srfi-130 » string-unfold

string-unfoldprocedure

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^2 seed), (successor^3 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 in the result string. These chars are assembled into the string in a left-to-right order.
  • base is the optional initial/leftmost portion of the constructed string; it defaults to the empty 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) "").

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, kons, and 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 s)) = s.

The final string constructed does not share storage with either base or the value produced by make-final.

This combinator sometimes is called an "anamorphism."