Revised7 Report on the Algorithmic Language Scheme
Batteries

1: R7RS List library

1.1: Argument names

In addition to the naming conventions used in the rest of the Report, Add xref. [wcm] this library uses the following names to indicate the types of procedure arguments and return values:

clist
clist1, … clistj, …

proper or circular list

flist
flist1, … flistj, …

finite proper or improper list

equals

boolean procedure taking two arguments

1.2: Constructors

1.2.1: xcons

  • (xcons obj1 obj2) → (pair) procedure

Equivalent to

(lambda (obj1 obj2) (cons obj2 obj1))

Of utility only as a value to be conveniently passed to higher-order procedures.

Example
(xcons '(b c) 'a)⇒ (a b c)

1.2.2: cons*

  • (cons* obj1 obj2 …) → (obj) procedure

Like list, but the last argument provides the tail of the constructed list, returning

(cons obj1 (cons obj2 (cons … objn)))
Examples
(cons* 1 2 3 4)⇒ (1 2 3 . 4)
(cons* 1)⇒ 1

1.2.3: list-tabulate

  • (list-tabulate k proc) → (list) procedure

‘list-tabulate’ should be continuation-safe. [wcm]

Returns a k-element list. Element i of the list, where 0≤i<k, is produced by (proc i). No guarantee is made about the dynamic order in which init-proc is applied to these indices.

Example
(list-tabulate 4 values)⇒ (0 1 2 3)

1.2.4: circular-list

  • (circular-list obj1 obj2 …) → (clist) procedure

Added 'newly allocated'. [wcm]

Constructs a newly allocated circular list of the elements.

Example
(circular-list 'z 'q)⇒ (z q z q z q …)

1.2.5: iota

  • (iota count [start [step]]) → (list) procedure

Returns a list containing the elements

start, start+step …, start+(count−1)×step

The start and step parameters default to 0 and 1, respectively.

Examples
(iota 5)⇒ (0 1 2 3 4)
(iota 5 0 -0.1)⇒ (0 -0.1 -0.2 -0.3 -0.4)

1.3: Predicates

1.3.1: circular-list?

  • (circular-list? obj) → (boolean) procedure

True if obj is a circular list. A circular list is a value such that for every n≥0, cdrn⁡(obj) is a pair.

1.3.2: dotted-list?

  • (dotted-list? obj) → (boolean) procedure

Since R7RS-small 6.4 defines an improper list, I've suppressed Olin's long definition.

True if obj is a finite improper list.

1.3.3: null-list?

  • (null-list? list) → (boolean) procedure

Returns true if list is the empty list, and false otherwise.

Does this follow the usual error conventions when it's passed a non-pair, non-null value, or does it signal something special? [wcm]

1.3.4: not-pair?

  • (not-pair? obj) → (boolean) procedure

Equivalent to

(lambda (x) (not (pair? x)))

Rationale: Provided as a procedure as it can be useful as the termination condition for list-processing procedures that wish to handle all finite lists, both proper and dotted.

1.3.5: list=

  • (list= elt=? list1 …) → (boolean) procedure

Determines list equality, given an element-equality procedure. Proper list A equals proper list B if they are of the same length, and their corresponding elements are equal, as determined by elt=?. If the element-comparison procedure’s first argument is from listi, then its second argument is from listi+1, i.e. it is always called as (elt=?ab) for a an element of list A and b an element of list B.

In the n-ary case, every listi is compared to listi+1 (as opposed, for example, to comparing list1 to every listi, for i≥1). If there are no list arguments at all, list= simply returns true.

It is an error to apply list= to anything except proper lists. While implementations may choose to extend it to circular lists, note that it cannot reasonably be extended to dotted lists, as it provides no way to specify an equality procedure for comparing the list terminators.

Note that the dynamic order in which the elt=? procedure is applied to pairs of elements is not specified. For example, if list= is applied to three lists, A, B, and C, it may first completely compare A to B, then compare B to C, or it may compare the first elements of A and B, then the first elements of B and C, then the second elements of A and B, and so forth.

The equality procedure must be consistent with eq?. That is, it must be the case that (eq? x y) implies (elt=? x y).

Note that this implies that two lists which are eq? are always list=, as well; implementations may exploit this fact to “short-cut” the element-by-element comparisons.

Examples

This needs some more useful examples. [wcm]

;; Trivial cases:
(list= eq?)⇒ #t
(list= eq? '(a))⇒ #t

1.4: Selectors

1.4.1: Numeric list-element selectors

  • (first list) → (obj) procedure
  • (second list) → (obj) procedure
  • (third list) → (obj) procedure
  • (fourth list) → (obj) procedure
  • (fifth list) → (obj) procedure
  • (sixth list) → (obj) procedure
  • (seventh list) → (obj) procedure
  • (eighth list) → (obj) procedure
  • (ninth list) → (obj) procedure
  • (tenth list) → (obj) procedure

Synonyms for car, cadr, caddr, …

Example
(third '(a b c d e))⇒ c

1.4.2: car+cdr

  • (car+cdr pair) → (obj obj) procedure

Equivalent to

(lambda (p) (values (car p) (cdr p)))

but may be implemented more efficiently.

1.4.3: take

  • (take obj k) → (list) procedure

FIXME: Specify improper list semantics. [wcm]

take returns the first k elements of list obj.

If the argument is a list of non-zero length, take is guaranteed to return a freshly-allocated list, even in the case where the entire list is taken, e.g. (take lis (length lis)).

Examples
(take '(a b c d e)  2)⇒ (a b)
(take '(1 2 3 . d) 2)⇒ (1 2)
(take '(1 2 3 . d) 3)⇒ (1 2 3)

1.4.4: drop

  • (drop obj k) → (obj) procedure

FIXME: Specify improper list semantics. [wcm]

drop returns all but the first k elements of list obj.

drop is exactly equivalent to performing k cdr operations on obj; the returned value shares a common tail with obj.

Examples
(drop '(a b c d e)  2)⇒ (c d e)
(drop '(1 2 3 . d) 2)⇒ (3 . d)
(drop '(1 2 3 . d) 3)⇒ d

1.4.5: take-right

  • (take-right flist k) → (obj) procedure

take-right returns the last k elements of flist.

take-right’s return value is guaranteed to share a common tail with flist.

Examples
(take-right '(a b c d e) 2)⇒ (d e)
(take-right '(1 2 3 . d) 2)⇒ (2 3 . d)
(take-right '(1 2 3 . d) 0)⇒ d

1.4.6: drop-right

  • (drop-right flist k) → (list) procedure

drop-right returns all but the last k elements of flist.

drop-right is guaranteed to return a freshly-allocated list, even in the case where nothing is dropped, e.g. (drop-right lis 0).

Examples
(drop-right '(a b c d e) 2)⇒ (a b c)
(drop-right '(1 2 3 . d) 2)⇒ (1)
(drop-right '(1 2 3 . d) 0)⇒ (1 2 3)

1.4.7: take!

  • (take! obj k) → (list) procedure

take! is a linear-update variant of take: it is allowed, but not required, to alter obj to produce the result.

Note: Yecch! Are we stuck with this behavior? [wcm]

If obj is circular, take! may return a shorter-than-expected list:

(take! (circular-list 1 3 5) 8)⇒ (1 3)
(take! (circular-list 1 3 5) 8)⇒ (1 3 5 1 3 5 1 3)

1.4.8: drop-right!

  • (drop-right! flist k) → (list) procedure

drop-right! is a linear-update variant of drop-right: it is allowed, but not required, to alter flist to produce the result.

1.4.9: split-at

  • (split-at obj k) → (list obj) procedure

split-at splits obj at index k, returning a list of the first k elements, and the remaining tail. It is equivalent to

(values (take obj k) (drop obj k))
Examples

Example returns 2 values. [wcm]

(split-at '(a b c d e f g h) 3)⇒ (a b c)
(d e f g h)

1.4.10: split-at!

  • (split-at! obj k) → (list obj) procedure

split-at! is the linear-update variant of split-at. It is allowed, but not required, to alter obj to produce the result.

1.4.11: last

  • (last pair) → (obj) procedure

Returns the last element of pair.

Examples
(last '(a b c))⇒ c

1.4.12: last-pair

  • (last-pair pair) → (pair) procedure

Returns the last pair of pair.

Examples
(last-pair '(a b c))⇒ (c)

1.5: Miscellaneous

This section could use a better name. [wcm]

1.5.1: length+

  • (length+ clist) → (obj) procedure

FIXME?: SRFI 1 doesn’t define length+’s behavior on improper lists. The definition here returns #f for improper lists, but there may be reasons to restrict #f to circular lists. (See issue 426 on the R7RS issue tracker.) [wcm]

Returns the length of clist if it is a finite proper list. Otherwise, returns #f.

1.5.2: append!

  • (append! list … [obj]) → (obj) procedure

append! is a linear-update variant of append — it is allowed, but not required, to alter cons cells in the argument lists to construct the result list. The last argument is never altered; the result list shares structure with this parameter.

1.5.3: concatenate

  • (concatenate list) → (obj) procedure

Appends the elements of list together. That is, concatenate returns the value of

(apply append list).

As with append and append!, the last element of the input list may be any value at all.

Rationale: Some Scheme implementations do not support passing more than a certain number (e.g., 64) of arguments to an n-ary procedure. In these implementations, the (apply append …) idiom would fail when applied to long lists, but concatenate would continue to function properly.

1.5.4: concatenate!

  • (concatenate! list) → (obj) procedure

concatenate! is the linear-update variant of concatenate, defined in terms of append! instead of append.

1.5.5: reverse!

  • (reverse! list) → (list) procedure

reverse! is the linear-update variant of reverse. It is permitted, but not required, to alter list’s cons cells to produce the reversed list.

1.5.6: append-reverse

  • (append-reverse list obj) → (obj) procedure

Returns the value of

(append (reverse list) obj).

Rationale: append-reverse is provided because it is a common operation — a common list-processing style calls for this exact operation to transfer values accumulated in reverse order onto the front of another list, and because the implementation is significantly more efficient than the simple composition it replaces.

1.5.7: append-reverse!

  • (append-reverse! list obj) → (obj) procedure

append-reverse! is the linear-update variant of append-reverse. It is allowed, but not required, to alter list’s cons cells to construct the result.

1.5.8: zip

  • (zip clist1 clist2 …) → (list) procedure

If zip is passed n lists, it returns a list as long as the shortest of these lists, each element of which is an n-element list comprised of the corresponding elements from the parameter lists. At least one of the argument lists must be finite.

Examples
(zip '(one two three)
     '(1 2 3)
     '(odd even odd even odd even odd even))⇒ ((one 1 odd) (two 2 even) (three 3 odd))
(zip '(1 2 3))⇒ ((1) (2) (3))

1.5.9: Unzip procedures

  • (unzip1 list) → (list) procedure
  • (unzip2 list) → (list list) procedure
  • (unzip3 list) → (list list list) procedure
  • (unzip4 list) → (list list list list) procedure
  • (unzip5 list) → (list list list list list) procedure

unzip1 takes a list of lists, where every list must contain at least one element, and returns a list containing the initial element of each such list. That is, it returns (map car lists). unzip2 takes a list of lists, where every list must contain at least two elements, and returns two values: a list of the first elements, and a list of the second elements. unzip3 does the same for the first three elements of the lists, and so forth.

Examples
(unzip2 '((1 one) (2 two) (3 three)))⇒ (1 2 3)
(one two three)

1.5.10: count

  • (count proc clist1 clist2 …) → (k) procedure

proc is a procedure taking as many arguments as there are lists and returning a single value. It is applied element-wise to the elements of the clists, and a count is tallied of the number of elements that produce a true value. This count is returned. count is guaranteed to apply proc to the clist elements in a left-to-right order. At least one of the clists must be finite. The counting stops when the shortest list expires.

Examples
(count even? '(3 1 4 1 5 9 2 5 6))⇒ 3
(count < '(1 2 4 8) '(2 4 6 8 10 12 14 16))⇒ 3
(count < '(3 1 4 1) (circular-list 1 10))⇒ 2

1.6: Fold, unfold, & map

1.6.1: fold

  • (fold kons knil clist1 clist2 …) → (obj) procedure

First, consider the single list-parameter case. If clist1 equals (e1 e2 … en), then this procedure returns

(kons en … (kons e1 knil)) … )

That is, it obeys the (tail) recursion

(fold kons knil lis) = (fold kons (kons (car lis) knil) (cdr lis))
(fold kons knil '()) = knil

If n clist arguments are provided, then the kons function must take n+1 parameters: one element from each list, and the “seed” or fold state, which is initially knil. The fold operation terminates when the shortest list runs out of values. At least one of the clist arguments must be finite.

Examples

Maybe the first four examples should be converted to actual evaluations? [wcm]

(fold + 0 lis)  ; Add up the elements of lis.

(fold cons '() lis)  ; Reverse list.

(fold cons tail rev-head)  ; See append-reverse.

;; How many symbols in lis?
(fold (lambda (x count) (if (symbol? x) (+ count 1) count))
      0
      lis)

;; Length of the longest string in lis:
(fold (lambda (s max-len) (max max-len (string-length s)))
      0
      lis)
(fold cons* '() '(a b c) '(1 2 3 4 5))⇒ (c 3 b 2 a 1)

1.6.2: fold-right

  • (fold-right kons knil clist1 clist2 …) → (obj) procedure

First, consider the single list-parameter case. If clist1 equals (e1 e2 … en), then this procedure returns

(kons e1 (kons e2 … (kons en knil)))

That is, it obeys the recursion

(fold-right kons knil lis) = (kons (car lis) (fold-right kons knil (cdr lis)))
(fold-right kons knil '()) = knil

If n list arguments are provided, then the kons function must take n+1 parameters: one element from each list, and the “seed” or fold state, which is initially knil. The fold operation terminates when the shortest list runs out of values. At least one of the clist arguments must be finite.

Examples

Maybe the first two examples should be converted to actual evaluations? [wcm]

(fold-right cons '() lis)  ; Copy lis.

;; Filter the even numbers out of lis.
(fold-right (lambda (x l) (if (even? x) (cons x l) l)) '() lis))
(fold-right cons* '() '(a b c) '(1 2 3 4 5))⇒ (a 1 b 2 c 3)

1.6.3: pair-fold

  • (pair-fold kons knil clist1 clist2 …) → (obj) procedure

Analogous to fold, but kons is applied to successive sublists of the clists, rather than successive elements — that is, kons is applied to the pairs making up the lists, giving this (tail) recursion:

(pair-fold kons knil lis) = (let ((tail (cdr lis))) (pair-fold kons (kons lis knil) tail))
(pair-fold kons knil '()) = knil

At least one of the clists must be finite.

For finite lists, the kons function may reliably apply set-cdr! to the pairs it is given without altering the sequence of execution.

Example
;;; Destructively reverse a list.
(pair-fold (lambda (pair tail) (set-cdr! pair tail) pair) '() lis)

1.6.4: pair-fold-right

  • (pair-fold-right kons knil clist1 clist2 …) → (obj) procedure

This could be clearer. In particular, does 'pair-fold-right' support mutation of the *list*s in a way similar to 'pair-fold'? [wcm]

Holds the same relationship with fold-right that pair-fold holds with fold. Obeys the recursion

Two rows, again. Don't delete the literal newline. [wcm]

(pair-fold-right kons knil lis) = (kons lis (pair-fold-right kons knil (cdr lis)))
(pair-fold-right kons knil '()) = knil

At least one of the clist arguments must be finite.

1.6.5: reduce

  • (reduce proc ridentity list) → (obj) procedure

The 'reduce' spec. has never seemed clear to me. [wcm]

reduce is a variant of fold.

ridentity should be a “right identity” of the procedure proc — that is, for any value x acceptable to proc,

(proc x ridentity) = x

If list is (), reduce returns ridentity. Otherwise, it returns (fold proc (car list) (cdr list)). In other words, we compute (fold proc ridentity list).

Note: ridentity is used only in the empty-list case. You typically use reduce when applying proc is expensive and you’d like to avoid the extra application incurred when fold applies proc to the head of list and the identity value, redundantly producing the same value passed in to proc. For example, if proc involves searching a file directory or performing a database query, this can be significant. In general, however, fold is useful in many contexts where reduce is not (consider the examples given in the fold definition — only one of the five folds uses a function with a right identity. The other four may not be performed with reduce).

Example
;; Take the max of a list of non-negative integers.
(reduce max 0 nums)

1.6.6: reduce-right

  • (reduce-right proc ridentity list) → (obj) procedure

reduce-right is the fold-right variant of reduce. It obeys the following definition:

(reduce-right proc ridentity  '()) = ridentity
(reduce-right proc ridentity '(e1)) = (proc e1 ridentity) = e1
(reduce-right proc ridentity '(e1 e2 …)) = (fold-right proc e1 '(e2 …))

In other words, we compute (fold-right proc ridentity list), but as with reduce, only use ridentity in the empty-list case.

Example
;; Append a bunch of lists together.
(reduce-right append '() list-of-lists)

1.6.7: unfold

  • (unfold p f g seed [tail-gen]) → (list) procedure

‘unfold’ should be continuation-safe. [wcm]

Should the more descriptive names (mapper, etc.) from other SRFIs be used instead of p, f, g? [wcm]

unfold is best described by its basic recursion:

(unfold p f g seed) = (if (p seed)
                          (tail-gen seed)
                             (cons (f seed)
                                   (unfold p f g (g seed)))
p

Determines when to stop unfolding.

f

Maps each seed value to the corresponding list element.

g

Maps each seed value to next seed value.

seed

The “state” value for the unfold.

tail-gen

Creates the tail of the list; defaults to (lambda (x) '()).

In other words, we use g to generate a sequence of seed values

seed, g⁡(seed), g2⁡(seed), g3⁡(seed),…

These seed values are mapped to list elements by f, producing the elements of the result list in a left-to-right order. P says when to stop.

Examples
;; List of squares: 1² … 10²
(unfold (lambda (x) (> x 10))
        (lambda (x) (* x x))
        (lambda (x) (+ x 1))
        1)

(unfold null-list? car cdr lis) ; Copy a proper list.

;; Read current input port into a list of values.
(unfold eof-object? values (lambda (x) (read)) (read))

;; Copy a possibly non-proper list:
(unfold not-pair? car cdr lis
              values)

;; Append head onto tail:
(unfold null-list? car cdr head
              (lambda (x) tail))

1.6.8: unfold-right

  • (unfold-right p f g seed [tail]) → (list) procedure

‘unfold-right’ should be continuation-safe. [wcm]

Should the more descriptive names (mapper, etc.) from other SRFIs be used instead of p, f, g? [wcm]

unfold-right constructs a list with the following loop:

(let lp ((seed seed) (lis tail))
  (if (p seed)
      lis
      (lp (g seed)
          (cons (f seed) lis))))
p

Determines when to stop unfolding.

f

Maps each seed value to the corresponding list element.

g

Maps each seed value to next seed value.

seed

The “state” value for the unfold.

tail

list terminator; defaults to '().

In other words, we use g to generate a sequence of seed values

seed, g⁡(seed), g2⁡(seed), g3⁡(seed),…

These seed values are mapped to list elements by f, producing the elements of the result list in a right-to-left order. P says when to stop.

Examples
;; List of squares: 1² ... 10²
(unfold-right zero?
              (lambda (x) (* x x))
              (lambda (x) (- x 1))
              10)

;; Reverse a proper list.
(unfold-right null-list? car cdr lis)

;; Read current input port into a list of values.
(unfold-right eof-object? values (lambda (x) (read)) (read))

;; (append-reverse rev-head tail)
(unfold-right null-list? car cdr rev-head tail)

1.6.9: append-map

  • (append-map proc clist1 clist2 …) → (obj) procedure

Redundant 'equivalent to' paragraph omitted. [wcm]

Map proc over the elements of the lists, just as in the map function. However, the results of the applications are appended together (as with append) to make the final result. The dynamic order in which the various applications of proc are made is not specified. At least one of the clist arguments must be finite.

Example

Example adapted from append-map!. (There is no example for append-map in the SRFI) [wcm]

(append-map (lambda (x) (list x (- x))) '(1 3 8))⇒ (1 -1 3 -3 8 -8)

1.6.10: append-map!

  • (append-map! proc clist1 clist2 …) → (obj) procedure

Redundant 'equivalent to' paragraph omitted. [wcm]

Map proc over the elements of the lists, just as in the map function. However, the results of the applications are appended together (as with append!) to make the final result. The dynamic order in which the various applications of proc are made is not specified. At least one of the clist arguments must be finite.

Example
(append-map! (lambda (x) (list x (- x))) '(1 3 8))⇒ (1 -1 3 -3 8 -8)

1.6.11: map!

  • (map! proc list1 clist2 …) → (list) procedure

Linear-update variant of map — map! is allowed, but not required, to alter the cons cells of list1 to construct the result list. The dynamic order in which the various applications of proc are made is not specified.

In the n-ary case, clist2, clist3, … must have at least as many elements as list1.

1.6.12: map-in-order

  • (map-in-order proc clist1 clist2 …) → (list) procedure

A variant of the map procedure that guarantees to apply proc across the elements of the clist arguments in a left-to-right order. This is useful for mapping procedures that both have side effects and return useful values. At least one of the clist arguments must be finite.

1.6.13: pair-for-each

  • (pair-for-each proc clist1 clist2 …) procedure

Like for-each, but proc is applied to successive sublists of the argument lists. That is, proc is applied to the cons cells of the lists, rather than the lists’ elements. These applications occur in left-to-right order. At least one of the clist arguments must be finite.

Proc may reliably apply set-cdr! to the pairs it is given without altering the sequence of execution.

Example
(pair-for-each (lambda (pair)
                 (display pair)
                 (newline))
               '(a b c))
(a b c)
(b c)
(c)

1.6.14: filter-map

  • (filter-map proc clist1 clist2 …) → (list) procedure

‘filter-map’ should be continuation-safe. [wcm]

Like map, but if the result of applying proc to an element is false, then it is not included in the returned list. The dynamic order in which the various applications of proc are made is not specified. At least one of the clist arguments must be finite.

(filter-map (lambda (x) (and (number? x) (* x x))) '(a 1 b 3 c 7))⇒ (1 9 49)

1.7: Filtering & partitioning

1.7.1: filter

  • (filter pred list) → (list) procedure

Return all the elements of list that satisfy predicate pred. Elements that appear in the result list occur in the same order as they occur in list. The returned list may share a common tail with list. The dynamic order in which the various applications of pred are made is not specified.

Example
(filter even? '(0 7 8 8 43 -4))⇒ (0 8 8 -4)

1.7.2: filter!

  • (filter! pred list) → (list) procedure

Linear-update variant of filter. filter! is allowed, but not required, to alter the cons cells in list to construct the result list.

1.7.3: partition

  • (partition pred list) → (list list) procedure

Partitions the elements of list with predicate pred, and returns two values: the list of in-elements and the list of out-elements. Elements occur in the result lists in the same order as they occur in list. The dynamic order in which the various applications of pred are made is not specified. One of the returned lists may share a common tail with list.

Example
(partition symbol? '(one 2 3 four five 6))⇒ (one four five)
(2 3 6)

1.7.4: partition!

  • (partition! pred list) → (list list) procedure

Linear-update variant of partition. partition! is allowed, but not required, to alter the cons cells in list to construct the result lists.

1.7.5: remove

  • (remove pred list) → (list) procedure

Returns list without the elements that satisfy predicate pred. Elements that appear in the result list occur in the same order as they occur in list. The returned list may share a common tail with list. The dynamic order in which the various applications of pred are made is not specified.

Example
(remove even? '(0 7 8 8 43 -4))⇒ (7 43)

1.7.6: remove!

  • (remove! pred list) → (list) procedure

Linear-update variant of remove. remove! is allowed, but not required, to alter the cons cells in list to construct the result list.

1.8: Searching

The following procedures all search lists for a leftmost element satisfying some criteria. This means they do not always examine the entire list; thus, there is no efficient way for them to reliably detect and signal an error when passed a dotted or circular list. Here are the general rules describing how these procedures work when applied to different kinds of lists:

1.8.1: Proper lists

The standard, canonical behavior happens in this case.

1.8.2: Improper lists

Simplified drastically from the original, which says that it is UB if the list contains an element satisfying the search criteria and an error if it doesn't. 'UB' and 'it is an error' are the same notion in Scheme these days. [wcm]

It is an error to pass these procedures an improper list.

1.8.3: Circular lists

It is an error to pass these procedures a circular list that does not contain an element satisfying the search criteria. Note that the procedure is not required to detect this case; it may simply diverge. It is, however, acceptable to search a circular list if the search is successful — that is, if the list contains an element satisfying the search criteria.

1.8.4: Examples

Here are some examples, using the find and any procedures as canonical representatives:

;; Proper list — success
(find even? '(1 2 3))⇒ 2
(any even? '(1 2 3))⇒ #t
;; Proper list — failure
(find even? '(1 7 3))⇒ #f
(any even? '(1 7 3))⇒ #f
;; Circular list — success
(find even? (circular-list 1 6 3))⇒ 6
(any even? (circular-list 1 6 3))⇒ #t

1.8.5: find

  • (find pred clist) → (obj) procedure

Return the first element of clist that satisfies predicate pred; false if no element does.

Note: Note that find has an ambiguity in its lookup semantics — if find returns #f, you cannot tell (in general) if it found a #f element that satisfied pred, or if it did not find any element at all. In many situations, this ambiguity cannot arise — either the list being searched is known not to contain any #f elements, or the list is guaranteed to have an element satisfying pred. However, in cases where this ambiguity can arise, you should use find-tail instead of find — find-tail has no such ambiguity:

(cond ((find-tail pred lis) =>
       (lambda (pair) …)) ; Handle (car pair)
      (else …)) ; Search failed.
Examples
(find even? '(3 1 4 1 5 9))⇒ 4

1.8.6: find-tail

The return type name here is a kluge. [wcm]

  • (find-tail pred clist) → (pair-or-false) procedure

Return the first pair of clist whose car satisfies pred. If no pair does, return false.

In the circular-list case, this procedure “rotates” the list.

Note: Find-tail is essentially drop-while, where the sense of the predicate is inverted: Find-tail searches until it finds an element satisfying the predicate; drop-while searches until it finds an element that doesn’t satisfy the predicate.

Examples
(find-tail even? '(3 1 37 -8 -5 0 0))⇒ (-8 -5 0 0)
(find-tail even? '(3 1 37 -5))⇒ #f
;; member x lis:
(find-tail (lambda (elt) (equal? x elt)) lis)

1.8.7: take-while

  • (take-while pred clist) → (list) procedure

Returns the longest initial prefix of clist whose elements all satisfy the predicate pred.

Examples
(take-while even? '(2 18 3 10 22 9))⇒ (2 18)

1.8.8: take-while!

  • (take-while! pred clist) → (list) procedure

Linear-update variant of take-while. It is allowed, but not required, to alter the argument clist to produce the result.

1.8.9: drop-while

  • (drop-while pred clist) → (list) procedure

Drops the longest initial prefix of clist whose elements all satisfy the predicate pred, and returns the rest of the list.

The circular-list case may be viewed as “rotating” the list.

Examples
(drop-while even? '(2 18 3 10 22 9))⇒ (3 10 22 9)

1.8.10: span

  • (span pred clist) → (list clist) procedure

Splits clist into the longest initial prefix whose elements all satisfy pred, and the remaining tail.

span is equivalent to

(values (take-while pred clist)
        (drop-while pred clist))
Example
(span even? '(2 18 3 10 22 9))⇒ (2 18)
(3 10 22 9)

1.8.11: span!

  • (span! pred list) → (list list) procedure

Linear-update variant of span. span! is allowed, but not required, to alter the argument list to produce the results.

1.8.12: break

  • (break pred clist) → (list clist) procedure

break is like span, but it inverts the sense of pred: the tail commences with the first element of the input clist that satisfies the predicate.

Example
(break even? '(3 1 4 1 5 9))⇒ (3 1)
(4 1 5 9)

1.8.13: break!

  • (break! pred list) → (list list) procedure

Linear-update variant of break. break! is allowed, but not required, to alter the argument list to produce the results.

1.8.14: any

  • (any pred clist1 clist1 …) → (obj) procedure

Applies pred across the lists, returning true if the predicate returns true on any application.

If there are n list arguments clist1 … clistn, then pred must be a procedure taking n arguments and returning a single value.

any applies pred to the first elements of the clisti parameters. If this application returns a true value, any immediately returns that value. Otherwise, it iterates, applying pred to the second elements of the clisti parameters, then the third, and so forth. The iteration stops when a true value is produced or one of the lists runs out of values; in the latter case, any returns #f. The application of pred to the last element of the lists is a tail call.

Note: Note the difference between find and any — find returns the element that satisfied the predicate; any returns the true value that the predicate produced.

This rationale is contradicted by other procedures in the library (e.g. lset=) which always returns booleans. [wcm]

Like every, any’s name does not end with a question mark — this is to indicate that it does not return a simple boolean (#t or #f), but a general value.

Example
(any integer? '(a 3 b 2.7))⇒ #t
(any integer? '(a 3.1 b 2.7))⇒ #f
(any < '(3 1 4 1 5) '(2 7 1 8 2))⇒ #t

1.8.15: every

  • (every pred clist1 clist1 …) → (obj) procedure

Applies pred across the lists, returning true if the predicate returns true on every application.

If there are n list arguments clist1 … clistn, then pred must be a procedure taking n arguments and returning a single value.

every applies pred to the first elements of the clisti parameters. If this application returns false, every immediately returns false. Otherwise, it iterates, applying pred to the second elements of the clisti parameters, then the third, and so forth. The iteration stops when a false value is produced or one of the lists runs out of values. In the latter case, every returns the true value produced by its final application of pred. The application of pred to the last element of the lists is a tail call.

If one of the clisti has no elements, every simply returns #t.

This rationale is contradicted by other procedures in the library (e.g. lset=) which always returns booleans. [wcm]

Note: Like any, every’s name does not end with a question mark — this is to indicate that it does not return a simple boolean (#t or #f), but a general value.

An example would be nice. [wcm]

1.8.16: list-index

The return type name here is a kluge. [wcm]

  • (list-index pred clist1 clist2 …) → (integer-or-false) procedure

Return the index of the leftmost element that satisfies pred.

If there are n list arguments clist1 … clistn, then pred must be a function taking n arguments and returning a single value.

list-index applies pred to the first elements of the clisti parameters. If this application returns true, list-index immediately returns zero. Otherwise, it iterates, applying pred to the second elements of the clisti parameters, then the third, and so forth. When it finds a tuple of list elements that cause pred to return true, it stops and returns the zero-based index of that position in the lists.

The iteration stops when one of the lists runs out of values; in this case, list-index returns #f.

Examples
(list-index even? '(3 1 4 1 5 9))⇒ 2
(list-index < '(3 1 4 1 5 9 2 5 6) '(2 7 1 8 2))⇒ 1
(list-index = '(3 1 4 1 5 9 2 5 6) '(2 7 1 8 2))⇒ #f

1.9: Deletion

1.9.1: delete

  • (delete obj list [equals]) → (list) procedure

delete uses the comparison procedure equals, which defaults to equal?, to find all elements of list that are equal to obj, and deletes them from list. The dynamic order in which the various applications of equals are made is not specified.

The list is not disordered — elements that appear in the result list occur in the same order as they occur in the argument list. The result may share a common tail with the argument list.

The comparison procedure is used in this way:

(equals obj ei).

That is, obj is always the first argument, and a list element is always the second argument. The comparison procedure will be used to compare each element of list exactly once; the order in which it is applied to the various ei is not specified.

Note: Fully general element deletion can be performed with the remove and remove! procedures, e.g.:

;; Delete all the even elements from lis:
(remove even? lis)
Example

Expanded to an actual example. [wcm]

(delete 5 '(3 5 1 7) <)⇒ (3 5 1)

1.9.2: delete!

  • (delete! obj list [equals]) → (list) procedure

delete! is the linear-update variant of delete. It is allowed, but not required, to alter the cons cells in its argument list to construct the result.

1.9.3: delete-duplicates

  • (delete-duplicates list [equals]) → (list) procedure

delete-duplicates removes duplicate elements from the list argument. If there are multiple equal elements in the argument list, the result list only contains the first or leftmost of these elements in the result. The order of these surviving elements is the same as in the original list — delete-duplicates does not disorder the list.

The equals parameter is used to compare the elements of the list; it defaults to equal?. If x comes before y in list, then the comparison is performed (equals x y). The comparison procedure will be used to compare each pair of elements in list no more than once; the order in which it is applied to the various pairs is not specified.

Implementations of delete-duplicates are allowed to share common tails between argument and result lists — for example, if the list argument contains only unique elements, it may simply return exactly this list.

Note: Be aware that, in general, delete-duplicates runs in time O⁡(n2) for n-element lists.

Example
(delete-duplicates '(a b a c a b c z))⇒ (a b c z)
;; Clean up an association list:
(delete-duplicates '((a . 3) (b . 7) (a . 9) (c . 1))
                   (lambda (x y) (eq? (car x) (car y))))⇒ ((a . 3) (b . 7) (c . 1))

1.9.4: delete-duplicates!

  • (delete-duplicates! list [equals]) → (list) procedure

delete-duplicates! is the linear-update variant of delete-duplicates; it is allowed, but not required, to alter the cons cells in its argument list to construct the result.

1.10: Association lists

An association list (or alist) is a list of pairs. The car of each pair contains a key value, and the cdr contains the associated data value. They can be used to construct simple look-up tables in Scheme. Note that association lists are probably inappropriate for performance-critical use on large data; in these cases, hash tables or some other alternative should be employed.

1.10.1: alist-cons

  • (alist-cons key value alist) → (alist) procedure

Cons a new alist entry mapping key to value onto alist.

1.10.2: alist-copy

  • (alist-copy alist) → (alist) procedure

This one could use a rationale explaining when you'd prefer it over 'list-copy'. (As far as I can tell, 'alist-copy' is only useful for alists you intend to mutate.) [wcm]

Make a fresh copy of alist. This means copying each pair that forms an association as well as the spine of the list, i.e.

(lambda (a)
  (map (lambda (elt) (cons (car elt) (cdr elt)))
       a))

1.10.3: alist-delete

  • (alist-delete key alist [equals]) → (alist) procedure

Deletes all associations from alist with the given key, using key-comparison procedure equals, which defaults to equal?. The dynamic order in which the various applications of equals are made is not specified.

Return values may share common tails with the alist argument. The alist is not disordered — elements that appear in the result alist occur in the same order as they occur in the argument alist.

The comparison procedure is used to compare the element keys ki of alist’s entries to the key parameter in this way:

(equals key ki).

Thus, one can reliably remove all entries of alist whose keys are greater than five with (alist-delete 5 alist >).

1.10.4: alist-delete!

  • (alist-delete! key alist [equals]) → (alist) procedure

alist-delete! is the linear-update variant of alist-delete. It is allowed, but not required, to alter cons cells from the alist parameter to construct the result.

1.11: Set operations on lists

Arguably this should require the comparison to be consistent with 'eqv?' instead of with 'eq?'. But I guess this ship has sailed. [wcm]

These procedures implement operations on sets represented as lists of elements. They all take an equals argument used to compare elements of lists. This equality procedure is required to be consistent with eq?. That is, it must be the case that

(eq? x y) ⇒ (equals x y).

Note that this implies, in turn, that two lists that are eq? are also set-equal by any legal comparison procedure. This allows for constant-time determination of set operations on eq? lists.

Note: Be aware that these procedures typically run in time O⁡(n⁢m) for n- and m-element list arguments. Performance-critical applications operating upon large sets will probably wish to use other data structures and algorithms.

1.11.1: lset<=

  • (lset<= equals list1 …) → (boolean) procedure

Returns true iff every listi is a subset of listi+1, using equals for the element-equality procedure. List A is a subset of list B if every element in A is equal to some element of B. When performing an element comparison, the equals procedure’s first argument is an element of A; its second, an element of B.

Examples
(lset<= eq? '(a) '(a b a) '(a b c c))⇒ #t

It would be better to define these trivial cases explicitly. [wcm]

;; Trivial cases:
(lset<= eq?)⇒ #t
(lset<= eq? '(a))⇒ #t

1.11.2: lset=

In the SRFI this procedure has an incorrect signature which mandates at least one list argument. See https://srfi-email.schemers.org/srfi-1/msg/44057568 [wcm]

  • (lset= equals list1 …) → (boolean) procedure

Returns true iff every listi is set-equal to listi+1, using equals for the element-equality procedure. “Set-equal” simply means that listi is a subset of listi+1, and listi+1 is a subset of listi. The equals procedure’s first argument is an element of listi; its second is an element of listi+1.

Examples
(lset= eq? '(b e a) '(a e b) '(e e b a))⇒ #t

It would be better to define these trivial cases explicitly. [wcm]

;; Trivial cases:
(lset= eq?)⇒ #t
(lset= eq? '(a))⇒ #t

1.11.3: lset-adjoin

  • (lset-adjoin equals list elt1 …) → (list) procedure

Adds the elti elements not already in the list parameter to the result list. The result shares a common tail with the list parameter. The new elements are added to the front of the list, but no guarantees are made about their order. The equals parameter is an equality procedure used to determine if an elti is already a member of list. Its first argument is an element of list; its second is one of the elti.

The list parameter is always a suffix of the result — even if the list parameter contains repeated elements, these are not reduced.

Example
(lset-adjoin eq? '(a b c d c e) 'a 'e 'i 'o 'u)⇒ (u o i a b c d c e)

Note that the order of the first three elements of the result list is unspecified.

1.11.4: lset-union

  • (lset-union equals list1 …) → (list) procedure

Returns the union of the lists, using equals for the element-equality procedure.

The union of lists A and B is constructed as follows:

  • If A is the empty list, the result is B (or a copy of B).

  • Otherwise, the result is initialised to be list A (or a copy of A).

  • Proceed through the elements of list B in a left-to-right order. If b is such an element of B, compare every element r of the current result list to b: (equals r b). If all comparisons fail, b is consed onto the front of the result.

However, there is no guarantee that equals will be applied to every pair of arguments from A and B. In particular, if A is eq? to B, the operation may immediately terminate.

In the n-ary case, the two-argument list-union operation is simply folded across the argument lists.

Example
(lset-union eq? '(a b c d e) '(a e i o u))⇒ (u o i a b c d e)
;; Repeated elements in list1 are preserved:
(lset-union eq? '(a a c) '(x a x))⇒ (x a a c)

It would be better to define these trivial cases a little more explicitly. The paragraph immediately before the examples defines them, gnomically. [wcm]

;; Trivial cases:
(lset-union eq?)⇒ ()
(lset-union eq? '(a b c))⇒ (a b c)

1.11.5: lset-union!

  • (lset-union! equals list1 …) → (list) procedure

Linear-update variant of lset-union which is allowed, but not required, to alter the cons cells from any of its list parameters to construct its result.

1.11.6: lset-intersection

  • (lset-intersection equals list1 list2 …) → (list) procedure

Returns the intersection of the lists, using equals for the element-equality procedure.

The intersection of lists A and B comprises every element of A that is equal in the sense of equals to some element of B: (equals a b), for a in A, and b in B. Note this implies that an element which appears in B and multiple times in list A will also appear multiple times in the result.

The order in which elements appear in the result is the same as the order in which they appear in list1 — that is, lset-intersection essentially filters list1, without disarranging element order. The result may share a common tail with list1.

In the n-ary case, the two-argument list-intersection operation is simply folded across the argument lists. However, the dynamic order in which the applications of equals are made is not specified. The procedure may check an element of list1 for membership in every other list before proceeding to consider the next element of list1, or it may completely intersect list1 and list2 before proceeding to list3, or it may go about its work in some third order.

Example
(lset-intersection eq? '(a b c d e) '(a e i o u))⇒ (a e)
;; Repeated elements in list1 are preserved:
(lset-intersection eq? '(a x y a) '(x a x z))⇒ '(a x a)
;; Trivial case:
(lset-intersection eq? '(a b c))⇒ (a b c)

1.11.7: lset-intersection!

  • (lset-intersection! equals list1 list2 …) → (list) procedure

Linear-update variant of lset-intersection which is allowed, but not required, to alter the cons cells in its first list parameter to construct its result.

1.11.8: lset-difference

  • (lset-difference equals list1 list2 …) → (list) procedure

Returns the difference of the lists, using equals for the element-equality procedure — all the elements of list1 that are not equals to any element from one of the other listi parameters.

The equals procedure’s first argument is always an element of list1; its second is an element of one of the other listi. Elements that are repeated multiple times in the list1 parameter will occur multiple times in the result.

The order in which elements appear in the result is the same as they appear in list1 — that is, lset-difference essentially filters list1, without disarranging element order. The result may share a common tail with list1.

The dynamic order in which the applications of equals are made is not specified. The procedure may check an element of list1 for membership in every other list before proceeding to consider the next element of list1, or it may completely compute the difference of list1 and list2 before proceeding to list3, or it may go about its work in some third order.

Example
(lset-difference eq? '(a b c d e) '(a e i o u))⇒ (b c d)
;; Trivial case:
(lset-difference eq? '(a b c))⇒ (a b c)

1.11.9: lset-difference!

  • (lset-difference! equals list1 list2 …) → (list) procedure

Linear-update variant of lset-difference which is allowed, but not required, to alter the cons cells in its first list parameter to construct its result.

1.11.10: lset-xor

  • (lset-xor equals list1 …) → (list) procedure

Returns the exclusive-or of the sets, using equals for the element-equality procedure. If there are exactly two lists, this is all the elements that appear in exactly one of the two lists. The operation is associative, and thus extends to the n-ary case — the elements that appear in an odd number of the lists. The result may share a common tail with any of the listi parameters.

More precisely, for two lists A and B, A xor B is a list of

  • every element a of A such that there is no element b of B such that (equals a b), and

  • every element b of B such that there is no element a of A such that (equals b a).

However, an implementation is allowed to assume that equals is symmetric — that is, that

(equals a b) ⇒ (equals b a).

This means, for example, that if a comparison (equals a b) produces true for some a in A and b in B, both a and b may be removed from inclusion in the result.

In the n-ary case, the binary-xor operation is simply folded across the lists.

Example
(lset-xor eq? '(a b c d e) '(a e i o u))⇒ (d c b i o u)

It would be better to define these trivial cases a little more explicitly. The paragraph immediately before the examples defines them, gnomically. [wcm]

;; Trivial cases:
(lset-xor eq?)⇒ ()
(lset-xor eq? '(a b c d e))⇒ (a b c d e)

1.11.11: lset-xor!

  • (lset-xor! equals list1 …) → (list) procedure

Linear-update variant of lset-xor which is allowed, but not required, to alter the cons cells in its first list parameter to construct its result.

1.11.12: lset-diff+intersection

  • (lset-diff+intersection equals list1 list2 …) → (list list) procedure

Returns two values — the difference and the intersection of the lists. Is equivalent to

(values (lset-difference equals list1 list2 …)
        (lset-intersection equals list1 (lset-union equals list2 …)))

but can be implemented more efficiently.

The equals procedure’s first argument is an element of list1; its second is an element of one of the other listi.

Either of the answer lists may share a common tail with list1. This operation essentially partitions list1.

1.11.13: lset-diff+intersection!

  • (lset-diff+intersection! equals list1 list2 …) → (list list) procedure

Linear-update variant of lset-diff+intersection which is allowed, but not required, to alter the cons cells in its first list parameter to construct its result.

2: R7RS Box library

Pasted from the SRFI rationale to serve as a brief intro. [wcm]

A box is a container for an object of any Scheme type, including another box. It is like a single-element vector, or half of a pair, or a direct representation of state. Boxes are normally used as minimal mutable storage, and can inject a controlled amount of mutability into an otherwise immutable data structure (or one that is conventionally treated as immutable).

2.1: Procedures

2.1.1: box

  • (box obj) → (box) procedure

Returns a newly allocated box initialized to obj.

2.1.2: box?

  • (box? obj) → (boolean) procedure

Returns #t if obj is a box, and #f otherwise.

2.1.3: unbox

  • (unbox box) → (obj) procedure

Returns the current value of box.

2.1.4: set-box!

  • (set-box! box obj) procedure

Stores obj in box.

2.2: Box equivalence

The behavior of boxes with the equivalence predicates eq?, eqv?, and equal? is the same as if they were implemented with records. That is, two boxes are both eq? and eqv? iff they are the product of the same call to box and not otherwise, and while they must be equal? if they are eqv?, the converse is implementation-dependent.

3: R7RS string library

3.1: Storage model

Except as noted, the results returned from the procedures of this library must be newly allocated strings. However, the empty string need not be newly allocated.

3.2: Argument names

In addition to the naming conventions used in the rest of the Report, Add xref. [wcm] this library uses the following names to indicate the types of procedure arguments and return values:

pred

A unary character predicate, taking a character as its one argument and returning a value that will be interpreted as true or false. Unless noted otherwise, as with string-every and string-any, all predicates passed to procedures specified in this SRFI may be called in any order and any number of times. It is an error if pred has side effects or does not behave functionally (returning the same result whenever it is called with the same character); the sample implementation does not detect those errors.

3.3: Predicates

3.3.1: string-null?

  • (string-null? string) → (boolean) procedure

R7RS-small doesn't define “the empty string”, so I’ve written it in as a reminder. [wcm]

Returns #t if string is the empty string (""), otherwise returns #f.

3.3.2: string-every

  • (string-every pred string [start [end]]) → (obj) procedure
  • (string-any pred string [start [end]]) → (obj) procedure

Checks to see if every/any character in string satisfies pred, proceeding from left (index start) to right (index end). These procedures are short-circuiting: if pred returns false, string-every does not call pred on subsequent characters; if pred returns true, string-any does not call pred on subsequent characters. Both procedures are “witness-generating”:

  • If string-every is given an empty interval (with start = end), it returns #t.

  • If string-every returns true for a non-empty interval (with start < end), the returned true value is the one returned by the final call to the predicate on (string-ref (string-copy string) (- end 1)).

  • If string-any returns true, the returned true value is the one returned by the predicate.

Note: The names of these procedures do not end with a question mark. This indicates a general value is returned instead of a simple boolean (#t or #f).

3.4: Constructors

3.4.1: string-tabulate

  • (string-tabulate proc k) → (string) procedure

‘string-tabulate’ should be continuation-safe. [wcm]

Proc is a procedure that accepts an exact integer as its argument and returns a character. Constructs a string of size k by calling proc on each value from 0 (inclusive) to k (exclusive) to produce the corresponding element of the string. The order in which proc is called on those indexes is not specified.

Rationale: Although string-unfold is more general, string-tabulate is likely to run faster for the common special case it implements.

3.4.2: string-unfold

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

‘string-unfold’ should be continuation-safe. [wcm]

Can we come up with a more helpful paragraph to lead off this spec? We know it’s a constructor; it’s in the “Constructors” section. [wcm]

This is a fundamental constructor for strings.

SRFI 152 added string-character polymorphism to the string unfolds, but it seems no one currently implements it. (See https://srfi-email.schemers.org/srfi-152/msg/44371731/) Should this and ‘string-unfold-right’ be reverted to their SRFI 13 forms, which don’t allow strings and chars to be used interchangeably? If not, some more explanation of how string are incorporated into the result would be nice. (string-unfold-right provides some more details.) [wcm]

successor

Used to generate a series of “seed” values from the initial seed:

Converted to mathematical notation, which is used for the analogous list in SRFI 1. [wcm]

seed, successor⁡(seed), successor2⁡(seed), successor3⁡(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

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

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.

Implementations should not allow the size of strings created by string-unfold to be limited by limits on stack size.

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.

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)

3.4.3: string-unfold-right

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

‘string-unfold-right’ should be continuation-safe. [wcm]

See note about string-character polymorphism above. [wcm]

This is a fundamental constructor for strings. It is the same as string-unfold except the results of mapper are assembled into the string in right-to-left order. Base is the optional rightmost portion of the constructed string, and make-final produces the leftmost portion of the constructed string. If mapper returns a string, the string is prepended to the constructed string (without reversal).

Example
(string-unfold-right (lambda (n) (< n (char->integer #A)))
                     (lambda (n) (char-downcase (integer->char n)))
                     (lambda (n) (- n 1))
                     (char->integer #Z)
                     #space
                     (lambda (n) " The English alphabet: "))⇒ " The English alphabet: abcdefghijklmnopqrstuvwxyz "
(string-unfold-right null?
                     (lambda (x) (string  #[ (car x) #]))
                     cdr
                     '(#\a #\b #\c))⇒ "[c][b][a]"

3.5: Conversion

3.5.1: reverse-list->string

  • (reverse-list->string list) → (string) procedure

Add start & end parameters? [wcm]

It is an error if any element of list is not a character.

Semantically equivalent to (compose list->string reverse):

(reverse-list->string '(#\a #\B #\c))⇒ cBa

Rationale: This is a common idiom in the epilogue of string-processing loops that accumulate their result using a list in reverse order. (See also string-concatenate-reverse for the “chunked” variant.

3.6: Selection

3.6.1: string-take

  • (string-take string k) → (string) procedure

string-take returns a string containing the first k characters of string. It is an error to take more characters than are in the string.

Examples
(string-take "Pete Szilagyi" 6)⇒ "Pete S"
(string-take "foo" 37)⇒ error

3.6.2: string-drop

  • (string-drop string k) → (string) procedure

string-drop returns a string containing all but the first k characters of string. It is an error to drop more characters than are in the string.

Example
(string-drop "Pete Szilagyi" 6)⇒ "zilagyi"

3.6.3: string-take-right

  • (string-take-right string k) → (string) procedure

string-take-right returns a string containing the last k characters of string. It is an error to take more characters than are in the string.

Example
(string-take-right "Beta rules" 5)⇒ "rules"

3.6.4: string-drop-right

  • (string-drop-right string k) → (string) procedure

string-drop-right returns a string containing all but the last k characters of string. It is an error to drop more characters than are in the string.

Example
(string-drop-right "Beta rules" 5)⇒ "Beta "

3.6.5: string-pad

  • (string-pad string k [char [start [end]]]) → (string) procedure

Returns a string of length k comprised of the characters drawn from the given subrange of string, padded on the left by as many occurrences of char as needed. If string has more than k characters, it is truncated on the left to length k. char defaults to #\space.

Examples
(string-pad "325" 5)⇒ "  325"
(string-pad "71325" 5)⇒ "71325"
(string-pad "8871325" 5)⇒ "71325"

3.6.6: string-pad-right

  • (string-pad-right string k [char [start [end]]]) → (string) procedure

Returns a string of length k comprised of the characters drawn from the given subrange of string, padded on the right by as many occurrences of char as needed. If string has more than k characters, it is truncated on the right to length k. char defaults to #\space.

Examples needed. [wcm]

3.6.7: string-trim

  • (string-trim string [pred [start [end]]]) → (string) procedure

Returns a string obtained from the given subrange of string by skipping over all characters on the left side that satisfy pred. pred defaults to char-whitespace?.

Examples needed. [wcm]

3.6.8: string-trim-right

  • (string-trim-right string [pred [start [end]]]) → (string) procedure

Returns a string obtained from the given subrange of string by skipping over all characters on the right side that satisfy pred. pred defaults to char-whitespace?.

Examples needed. [wcm]

3.6.9: string-trim-both

  • (string-trim-both string [pred [start [end]]]) → (string) procedure

Returns a string obtained from the given subrange of string by skipping over all characters on both sides that satisfy pred. pred defaults to char-whitespace?.

Example
(string-trim-both "  The outlook wasn't brilliant,  \n\r")⇒ "The outlook wasn't brilliant,"

3.7: Replacement

3.7.1: string-replace

  • (string-replace string1 string2 start1 end1 [start2 [end2]]) → (string) procedure

Returns

(string-append (substring string1 0 start1)
               (substring string2 start2 end2)
               (substring string1 end1 (string-length string1)))

That is, the segment of characters in string1 from start1 to end1 is replaced by the segment of characters in string2 from start2 to end2. If start1 is equal to end1, this simply splices the characters drawn from string2 into string1 at that position.

Example

Update insults? The set of bad popular languages has changed. ;-) [wcm]

(string-replace "The TCL programmer endured daily ridicule."
                "another miserable perl drone" 4 7 8 22)⇒ "The miserable perl programmer endured daily ridicule."
(string-replace "It's easy to code it up in Scheme."
                "lots of fun" 5 9)⇒ "It's lots of fun to code it up in Scheme."
(define (string-insert s i t) (string-replace s t i i))
(string-insert "It's easy to code it up in Scheme." 5 "really ")⇒ "It's really easy to code it up in Scheme."
(define (string-set s i c)
        (string-replace s (string c) i (+ i 1)))
(string-set "String-ref runs in O(n) time." 21 #\1)⇒ "String-ref runs in O(1) time."

3.8: Prefixes and suffixes

3.8.1: string-prefix-length

  • (string-prefix-length string1 string2 [start1 [end1 [start2 [end2]]]]) → (k) procedure

Return the length of the longest common prefix of string1 and string2. For prefixes, this is equivalent to their “mismatch index” (relative to the start indexes).

The optional start/end indexes restrict the comparison to the indicated substrings of string1 and string2.

3.8.2: string-suffix-length

  • (string-suffix-length string1 string2 [start1 [end1 [start2 [end2]]]]) → (k) procedure

Return the length of the longest common suffix of string1 and string2.

The optional start/end indexes restrict the comparison to the indicated substrings of string1 and string2.

3.8.3: string-prefix?

  • (string-prefix? string1 string2 [start1 [end1 [start2 [end2]]]]) → (boolean) procedure

Is string1 a prefix of string2?

The optional start/end indexes restrict the comparison to the indicated substrings of string1 and string2.

3.8.4: string-suffix?

  • (string-suffix? string1 string2 [start1 [end1 [start2 [end2]]]]) → (boolean) procedure

Is string1 a suffix of string2?

The optional start/end indexes restrict the comparison to the indicated substrings of string1 and string2.

3.9: Searching

3.9.1: string-index

  • (string-index string pred [start [end]]) → (integer-or-false) procedure

string-index searches through the given substring of string from the left, returning the index of the leftmost character satisfying the predicate pred. If no such character is found, returns #f.

Examples needed. [wcm]

3.9.2: string-index-right

  • (string-index-right string pred [start [end]]) → (integer-or-false) procedure

string-index-rightsearches through the given substring of string from the right, returning the index of the rightmost character satisfying the predicate pred. If no such character is found, returns #f.

Examples needed. [wcm]

3.9.3: string-skip

  • (string-skip string pred [start [end]]) → (integer-or-false) procedure

string-skip searches through the given substring of string from the left, returning the index of the leftmost character that doesn’t satisfy the predicate pred. If no such character is found, returns #f.

Example
;; Skip over initial whitespace:
(substring string
           (or (string-skip string char-whitespace?)
               (string-length string))
           (string-length string))

3.9.4: string-skip-right

  • (string-skip-right string pred [start [end]]) → (integer-or-false) procedure

string-skip searches through the given substring of string from the right, returning the index of the rightmost character that doesn’t satisfy the predicate pred. If no such character is found, returns #f.

Examples needed. [wcm]

3.9.5: string-contains

  • (string-contains string1 string2 [start1 [end1 [start2 [end2]]]]) → (integer-or-false) procedure

Does the substring of string1 specified by start1 and end1 contain the sequence of characters given by the substring of string2 specified by start2 and end2?

TODO: MathML for intervals? [wcm]

Returns #f if there is no match. If start2 equals end2, returns start1. Otherwise returns the index in string1 for the first character of the first match; that index lies within the half-open interval [start1,end1), and the match lies entirely within the [start1,end1) range of string1.

Example
(string-contains "eek -- what a geek." "ee" 12 18)⇒ 15

3.9.6: string-take-while

  • (string-take-while string pred [start [end]]) → (string) procedure

Returns the longest prefix of the substring of string specified by start and end whose elements all satisfy the predicate pred.

Examples needed. [wcm]

3.9.7: string-take-while-right

  • (string-take-while-right string pred [start [end]]) → (string) procedure

Returns the longest suffix of the substring of string specified by start and end whose elements all satisfy the predicate pred.

Examples needed. [wcm]

3.9.8: string-drop-while

  • (string-drop-while string pred [start [end]]) → (string) procedure

SRFI 152 says “returns the rest of the string”, which is ambiguous. I’ve replaced ‘string’ with ‘substring’. [wcm]

Drops the longest prefix of the substring of string specified by start and end whose elements all satisfy the predicate pred, and returns the rest of the substring.

Note: This is the same as string-trim but with a different order of arguments.

Examples needed. [wcm]

3.9.9: string-drop-while-right

  • (string-drop-while-right string pred [start [end]]) → (string) procedure

SRFI 152 says “returns the rest of the string”, which is ambiguous. I’ve replaced ‘string’ with ‘substring’. [wcm]

Drops the longest suffix of the substring of string specified by start and end whose elements all satisfy the predicate pred, and returns the rest of the substring.

Note: This is the same as string-trim-right but with a different order of arguments.

Examples needed. [wcm]

3.9.10: string-span

  • (string-span string pred [start [end]]) → (string string) procedure

String-span splits the substring of string specified by start and end into the longest initial prefix whose elements all satisfy pred, and the remaining tail.

Without start and end arguments, string-span is equivalent to

(values (string-take-while pred string)
        (string-drop-while pred string))

Examples needed. [wcm]

3.9.11: string-break

  • (string-break string pred [start [end]]) → (string string) procedure

String-break is like string-span, but it inverts the sense of the predicate: the tail commences with the first element of the input substring that satisfies pred.

Examples needed. [wcm]

3.10: Concatenation

3.10.1: string-concatenate

  • (string-concatenate list) → (string) procedure

It is an error if any element of list is not a string.

Concatenates the elements of list together into a single string.

Rationale: Some implementations of Scheme limit the number of arguments that may be passed to an n-ary procedure, so the (apply string-append list) idiom, which is otherwise equivalent to using this procedure, is not as portable.

3.10.2: string-concatenate-reverse

  • (string-concatenate-reverse list [final-string [end]]) → (string) procedure

It is an error if any element of list is not a string.

With no optional arguments, calling this procedure is equivalent to

(string-concatenate (reverse list))

If the optional argument final-string is given, it is effectively consed onto the beginning of string-list before performing the reverse and string-concatenate operations.

If the optional argument end is given, only the characters up to but not including end in final-string are added to the result, thus producing

(string-concatenate
 (reverse (cons (substring final-string 0 end)
          list)))

Rationale: I’m not so sure about this. At the very least it needs an example of the case Olin has in mind. Maybe we’d be better off without the weird optional arguments? [wcm]

This procedure is useful when constructing procedures that accumulate character data into lists of string buffers, and wish to convert the accumulated data into a single string when done. The optional end argument accommodates that use case by allowing the final buffer to be only partially full without having to copy it a second time, as string-take would require.

Caution: Note that reversing a string simply reverses the sequence of code points it contains. Caution should be taken if a grapheme cluster is divided between two string arguments.

Example
(string-concatenate-reverse '(" must be" "Hello, I") " going.XXXX" 7)⇒ "Hello, I must be going."

3.10.3: string-join

  • (string-join list [delimiter [grammar]]) → (string) procedure

I’ve removed the quotes from the symbol values. It’s a mistake to say 'foo is the value of the symbol written 'foo. In the worst case, this might lead someone to pass '|'suffix| instead of 'suffix! [wcm]

It is an error if any element of list is not a string, if delimiter is not a string, or if grammar is not one of the symbols infix, string-infix, suffix, or prefix.

string-join is a simple unparser; it pastes strings together using delimiter (which defaults to a single space: " "). The grammar argument is a symbol that determines how the delimiter is used, and defaults to infix:

  • infix means an infix or separator grammar: insert delimiter between list elements. An empty list will produce an empty string.

  • strict-infix means the same as infix if list is non-empty, but will signal an error if given an empty list. (This avoids an ambiguity shown in the examples below.)

  • suffix means a suffix or terminator grammar: insert delimiter after every list element.

  • prefix means a prefix grammar: insert delimiter before every list element.

Example
(string-join '("foo" "bar" "baz"))⇒ "foo bar baz"
(string-join '("foo" "bar" "baz") "")⇒ "foobarbaz"
(string-join '("foo" "bar" "baz") ":")⇒ "foo:bar:baz"
(string-join '("foo" "bar" "baz") ":" 'suffix)⇒ "foo:bar:baz:"
;; Infix grammar is ambiguous with regard to empty
;; list vs. empty string:
(string-join '()   ":")⇒ ""
(string-join '("") ":")⇒ ""
;; Suffix and prefix grammars are not:
(string-join '()   ":" 'suffix))⇒ ""
(string-join '("") ":" 'suffix))⇒ ":"

3.11: Fold and map and friends

3.11.1: string-fold

  • (string-fold kons knil string [start [end]]) → (obj) procedure

It is an error if kons is not a procedure accepting at least two arguments and returning a single value.

Folds the kons procedure across the given string from left to right:

In the SRFI this ignores start and end. [wcm]

(kons stringend−1 … (kons stringstart+1 (kons stringstart knil))))

In other words, string-fold obeys the (tail) recursion

(string-fold kons knil string start end) = (string-fold  kons (kons stringstart knil) string (+ 1 start) end)
Example
;; Count the number of lower-case characters in a string.
(string-fold (lambda (c count)
               (if (char-lower-case? c)
                   (+ count 1)
                   count))
             0
             string)

3.11.2: string-fold-right

  • (string-fold-right kons knil string [start [end]]) → (obj) procedure

It is an error if kons is not a procedure accepting at least two arguments and returning a single value.

Folds the kons procedure across the given string from right to left:

Fixed and shortened. In the SRFI this ignores start. [wcm]

(konsstringstart (… (kons stringend−2 (kons stringend−1 knil))))

That is, string-fold-right obeys the (tail) recursion

(string-fold-right kons knil string start end) = (string-fold-right kons (kons stringend−1 knil) string start (- end 1))
Example
;; Convert a string to a list of chars.
(string-fold-right cons '() string)

3.11.3: string-map

Included because this version of string-map differs from that of R7RS in a few ways: it allows proc to return strings, and it doesn't include the sentence about multiple returns. These differences will have to be reconciled. [wcm]

  • (string-map proc string1 string2 …) → (string) procedure

It is an error if proc does not accept as many arguments as the number of string arguments passed to string-map, does not accept characters as arguments, or returns a value that is not a character or string.

The string-map procedure applies proc element-wise to the characters of the string arguments, converts each value returned by proc to a string, and returns the concatenation of those strings. If more than one string argument is given and not all have the same length, then string-map terminates when the shortest string argument runs out. The dynamic order in which proc is called on the characters of the string arguments is unspecified, as is the dynamic order in which the coercions are performed. The possibility of proc results being mutated isn’t considered in R7RS-small map or vector-map. We might want to tighten up those procedures, too. [wcm] If any strings returned by proc are mutated after they have been returned and before the call to string-map has returned, then string-map returns a string with unspecified contents; the string-map procedure itself does not mutate those strings.

Example
(string-map (lambda (c0 c1 c2)
              (case c0
                ((#\1) c1)
                ((#\2) (string c2))
                ((#\-) (string #\- c1))))
            "1222-1111-2222"
            "Hi There!"
            "Dear John")⇒ "Hear-here!"

3.11.4: string-count

  • (string-count string pred [start [end]]) → (integer) procedure

Returns a count of the number of characters in the specified substring of string that satisfy the predicate pred.

Examples needed. [wcm]

3.11.5: string-filter

  • (string-filter pred string [start [end]]) → (string) procedure

Filter the given substring of string, retaining only those characters that satisfy pred.

Examples needed. [wcm]

3.11.6: string-remove

  • (string-remove pred string [start [end]]) → (string) procedure

Filter the given substring of string, retaining only those characters that do not satisfy pred.

Examples needed. [wcm]

3.12: Replication and splitting

3.12.1: string-replicate

  • (string-replicate string from to [start [end]]) → (string) procedure

It is an error if either of from or to is not an exact integer, or if from is greater than to. It is also an error if start equals end, unless from equals to, which is allowed as a special case.

This is an “extended substring” procedure that implements replicated copying of a substring. This substring is conceptually replicated both up and down the index space, in both the positive and negative directions. For example, if string is "abcdefg", start is 3, and end is 6, then we have the conceptual bidirectionally-infinite string

…  d  e  f  d  e  f  d  e  f  d  e  f  d  e  f  d  e  f  d  …
  −9 −8 −7 −6 −5 −4 −3 −2 −1  0 +1 +2 +3 +4 +5 +6 +7 +8 +9

string-replicate returns the substring of this string beginning at index from, and ending at to. It is an error if from is greater than to.

Note that

  • The from/to arguments give a half-open range containing the characters from index from up to, but not including, index to.

  • The from/to indexes are not expressed in the index space of string. They refer instead to the replicated index space of the substring defined by string, start, and end.

Example
;; Rotate a string left:
(string-replicate "abcdef" 2 8)⇒ "cdefab"
;; Rotate a string right:
(string-replicate "abcdef" -2 4)⇒ "efabcd"
;; Replicate a string:
(string-replicate "abc" 0 7)⇒ "abcabca"

3.12.2: string-segment

  • (string-segment string k) → (list) procedure

Revised. See https://srfi-email.schemers.org/srfi-152/msg/44472348/ [wcm]

Returns a list of strings representing the consecutive substrings of string of length k. It is an error if k is zero. The last string may be shorter than k but it is never empty; if string is "", then string-segment returns the empty list.

Examples needed. [wcm]

3.12.3: string-split

  • (string-split string delimiter [grammar [limit [start [end]]]]) → (list) procedure

Collect info about argument types in first paragraph? [wcm]

Returns a list of strings representing the words contained in the substring of string from start (inclusive) to end (exclusive). The delimiter is a string to be used as the word separator. The returned list will have one more item than the number of non-overlapping occurrences of the delimiter in the string. If delimiter is an empty string, then the returned list contains a list of strings, each of which contains a single character.

The grammar is a symbol with the same meaning as in the string-join procedure. If it is infix, which is the default, processing is done as described above, except an empty string produces the empty list; if grammar is strict-infix, then an empty string signals an error. The values prefix and suffix cause a leading/trailing empty string in the result to be suppressed.

If limit is a non-negative exact integer, at most that many splits occur, and the remainder of string is returned as the final element of the list (so the result will have at most limit+1 elements). If limit is not specified or is #f, then as many splits as possible are made. It is an error if limit is any other value.

Examples needed. [wcm]