SRFI Support Modules
====================

SRFI is an acronym for Scheme Request For Implementation.  The SRFI documents define a lot of syntactic and procedure extensions to standard Scheme as defined in R5RS.

Guile has support for a number of SRFIs.  This chapter gives an overview over the available SRFIs and some usage hints.  For complete documentation, design rationales and further examples, we advise you to get the relevant SRFI documents from the SRFI home page http://srfi.schemers.org.

About SRFI Usage
----------------

SRFI support in Guile is currently implemented partly in the core library, and partly as add-on modules.  That means that some SRFIs are automatically available when the interpreter is started, whereas the other SRFIs require you to use the appropriate support module explicitly.

There are several reasons for this inconsistency.  First, the feature checking syntactic form cond-expand (see SRFI-0) must be available immediately, because it must be there when the user wants to check for the Scheme implementation, that is, before she can know that it is safe to use use-modules to load SRFI support modules.  The second reason is that some features defined in SRFIs had been implemented in Guile before the developers started to add SRFI implementations as modules (for example SRFI-6 (see SRFI-6)).  In the future, it is possible that SRFIs in the core library might be factored out into separate modules, requiring explicit module loading when they are needed.  So you should be prepared to have to use use-modules someday in the future to access SRFI-6 bindings.  If you want, you can do that already.  We have included the module (srfi srfi-6) in the distribution, which currently does nothing, but ensures that you can write future-safe code.

Generally, support for a specific SRFI is made available by using modules named (srfi srfi-NUMBER), where NUMBER is the number of the SRFI needed.  Another possibility is to use the command line option --use-srfi, which will load the necessary modules automatically (see Invoking Guile).

SRFI-0 - cond-expand
--------------------

This SRFI lets a portable Scheme program test for the presence of certain features, and adapt itself by using different blocks of code, or fail if the necessary features are not available.  There's no module to load, this is in the Guile core.

A program designed only for Guile will generally not need this mechanism, such a program can of course directly use the various documented parts of Guile.

 -- syntax: cond-expand (feature body...) ...
     Expand to the BODY of the first clause whose FEATURE specification is satisfied.  It is an error if no FEATURE is satisfied.

     Features are symbols such as srfi-1, and a feature specification can use and, or and not forms to test combinations.  The last clause can be an else, to be used if no other passes.

     For example, define a private version of alist-cons if SRFI-1 is not available.

          (cond-expand (srfi-1
                        )
                       (else
                        (define (alist-cons key val alist)
                          (cons (cons key val) alist))))

     Or demand a certain set of SRFIs (list operations, string ports, receive and string operations), failing if they're not available.

          (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
                        ))

The Guile core has the following features,

     guile
     r5rs
     srfi-0
     srfi-4
     srfi-6
     srfi-13
     srfi-14

Other SRFI feature symbols are defined once their code has been loaded with use-modules, since only then are their bindings available.

The --use-srfi command line option (see Invoking Guile) is a good way to load SRFIs to satisfy cond-expand when running a portable program.

Testing the guile feature allows a program to adapt itself to the Guile module system, but still run on other Scheme systems.  For example the following demands SRFI-8 (receive), but also knows how to load it with the Guile mechanism.

     (cond-expand (srfi-8
                   )
                  (guile
                   (use-modules (srfi srfi-8))))

It should be noted that cond-expand is separate from the *features* mechanism (see Feature Tracking), feature symbols in one are unrelated to those in the other.

SRFI-1 - List library
---------------------

The list library defined in SRFI-1 contains a lot of useful list processing procedures for construction, examining, destructuring and manipulating lists and pairs.

Since SRFI-1 also defines some procedures which are already contained in R5RS and thus are supported by the Guile core library, some list and pair procedures which appear in the SRFI-1 document may not appear in this section.  So when looking for a particular list/pair processing procedure, you should also have a look at the sections Lists and Pairs.

Constructors
............

New lists can be constructed by calling one of the following procedures.

 -- Scheme Procedure: xcons d a
     Like cons, but with interchanged arguments.  Useful mostly when passed to higher-order procedures.

 -- Scheme Procedure: list-tabulate n init-proc
     Return an N-element list, where each list element is produced by applying the procedure INIT-PROC to the corresponding list index.  The order in which INIT-PROC is applied to the indices is not specified.

 -- Scheme Procedure: list-copy lst
     Return a new list containing the elements of the list LST.

     This function differs from the core list-copy (see List Constructors) in accepting improper lists too.  And if LST is not a pair at all then it's treated as the final tail of an improper list and simply returned.

 -- Scheme Procedure: circular-list elt1 elt2 ...
     Return a circular list containing the given arguments ELT1 ELT2 ....

 -- Scheme Procedure: iota count [start step]
     Return a list containing COUNT numbers, starting from START and adding STEP each time.  The default START is 0, the default STEP is 1.  For example,

          (iota 6)        => (0 1 2 3 4 5)
          (iota 4 2.5 -2) => (2.5 0.5 -1.5 -3.5)

     This function takes its name from the corresponding primitive in the APL language.

Predicates
..........

The procedures in this section test specific properties of lists.

 -- Scheme Procedure: proper-list? obj
     Return #t if OBJ is a proper list, or #f otherwise.  This is the same as the core list? (see List Predicates).

     A proper list is a list which ends with the empty list () in the usual way.  The empty list () itself is a proper list too.

          (proper-list? '(1 2 3))  => #t
          (proper-list? '())       => #t

 -- Scheme Procedure: circular-list? obj
     Return #t if OBJ is a circular list, or #f otherwise.

     A circular list is a list where at some point the cdr refers back to a previous pair in the list (either the start or some later point), so that following the cdrs takes you around in a circle, with no end.

          (define x (list 1 2 3 4))
          (set-cdr! (last-pair x) (cddr x))
          x => (1 2 3 4 3 4 3 4 ...)
          (circular-list? x)  => #t

 -- Scheme Procedure: dotted-list? obj
     Return #t if OBJ is a dotted list, or #f otherwise.

     A dotted list is a list where the cdr of the last pair is not the empty list ().  Any non-pair OBJ is also considered a dotted list, with length zero.

          (dotted-list? '(1 2 . 3))  => #t
          (dotted-list? 99)          => #t

It will be noted that any Scheme object passes exactly one of the above three tests proper-list?, circular-list? and dotted-list?.  Non-lists are dotted-list?, finite lists are either proper-list? or dotted-list?, and infinite lists are circular-list?.

 -- Scheme Procedure: null-list? lst
     Return #t if LST is the empty list (), #f otherwise.  If something else than a proper or circular list is passed as LST, an error is signalled.  This procedure is recommended for checking for the end of a list in contexts where dotted lists are not allowed.

 -- Scheme Procedure: not-pair? obj
     Return #t is OBJ is not a pair, #f otherwise. This is shorthand notation (not (pair? OBJ)) and is supposed to be used for end-of-list checking in contexts where dotted lists are allowed.

 -- Scheme Procedure: list= elt= list1 ...
     Return #t if all argument lists are equal, #f otherwise. List equality is determined by testing whether all lists have the same length and the corresponding elements are equal in the sense of the equality predicate ELT=.  If no or only one list is given, #t is returned.

Selectors
.........

 -- Scheme Procedure: first pair
 -- Scheme Procedure: second pair
 -- Scheme Procedure: third pair
 -- Scheme Procedure: fourth pair
 -- Scheme Procedure: fifth pair
 -- Scheme Procedure: sixth pair
 -- Scheme Procedure: seventh pair
 -- Scheme Procedure: eighth pair
 -- Scheme Procedure: ninth pair
 -- Scheme Procedure: tenth pair
     These are synonyms for car, cadr, caddr, ....

 -- Scheme Procedure: car+cdr pair
     Return two values, the CAR and the CDR of PAIR.

 -- Scheme Procedure: take lst i
 -- Scheme Procedure: take! lst i
     Return a list containing the first I elements of LST.

     take! may modify the structure of the argument list LST in order to produce the result.

 -- Scheme Procedure: drop lst i
     Return a list containing all but the first I elements of LST.

 -- Scheme Procedure: take-right lst i
     Return the a list containing the I last elements of LST.

 -- Scheme Procedure: drop-right lst i
 -- Scheme Procedure: drop-right! lst i
     Return the a list containing all but the I last elements of LST.

     drop-right! may modify the structure of the argument list LST in order to produce the result.

 -- Scheme Procedure: split-at lst i
 -- Scheme Procedure: split-at! lst i
     Return two values, a list containing the first I elements of the list LST and a list containing the remaining elements.

     split-at! may modify the structure of the argument list LST in order to produce the result.

 -- Scheme Procedure: last lst
     Return the last element of the non-empty, finite list LST.

Length, Append, Concatenate, etc.
.................................

 -- Scheme Procedure: length+ lst
     Return the length of the argument list LST.  When LST is a circular list, #f is returned.

 -- Scheme Procedure: concatenate list-of-lists
 -- Scheme Procedure: concatenate! list-of-lists
     Construct a list by appending all lists in LIST-OF-LISTS.

     concatenate! may modify the structure of the given lists in order to produce the result.

     concatenate is the same as (apply append LIST-OF-LISTS).  It exists because some Scheme implementations have a limit on the number of arguments a function takes, which the apply might exceed.  In Guile there is no such limit.

 -- Scheme Procedure: append-reverse rev-head tail
 -- Scheme Procedure: append-reverse! rev-head tail
     Reverse REV-HEAD, append TAIL and return the result.  This is equivalent to (append (reverse REV-HEAD) TAIL), but more efficient.

     append-reverse! may modify REV-HEAD in order to produce the result.

 -- Scheme Procedure: zip lst1 lst2 ...
     Return a list as long as the shortest of the argument lists, where each element is a list.  The first list contains the first elements of the argument lists, the second list contains the second elements, and so on.

 -- Scheme Procedure: unzip1 lst
 -- Scheme Procedure: unzip2 lst
 -- Scheme Procedure: unzip3 lst
 -- Scheme Procedure: unzip4 lst
 -- Scheme Procedure: unzip5 lst
     unzip1 takes a list of lists, and returns a list containing the first elements of each list, unzip2 returns two lists, the first containing the first elements of each lists and the second containing the second elements of each lists, and so on.

 -- Scheme Procedure: count pred lst1 ... lstN
     Return a count of the number of times PRED returns true when called on elements from the given lists.

     PRED is called with N parameters (PRED ELEM1 ... ELEMN), each element being from the corresponding LST1 ... LSTN.  The first call is with the first element of each list, the second with the second element from each, and so on.

     Counting stops when the end of the shortest list is reached.  At least one list must be non-circular.

Fold, Unfold & Map
..................

 -- Scheme Procedure: fold proc init lst1 ... lstN
 -- Scheme Procedure: fold-right proc init lst1 ... lstN
     Apply PROC to the elements of LST1 ... LSTN to build a result, and return that result.

     Each PROC call is (PROC ELEM1 ... ELEMN PREVIOUS), where ELEM1 is from LST1, through ELEMN from LSTN.  PREVIOUS is the return from the previous call to PROC, or the given INIT for the first call.  If any list is empty, just INIT is returned.

     fold works through the list elements from first to last.  The following shows a list reversal and the calls it makes,

          (fold cons '() '(1 2 3))

          (cons 1 '())
          (cons 2 '(1))
          (cons 3 '(2 1)
          => (3 2 1)

     fold-right works through the list elements from last to first, ie. from the right.  So for example the following finds the longest string, and the last among equal longest,

          (fold-right (lambda (str prev)
                        (if (> (string-length str) (string-length prev))
                            str
                            prev))
                      ""
                      '("x" "abc" "xyz" "jk"))
          => "xyz"

     If LST1 through LSTN have different lengths, fold stops when the end of the shortest is reached; fold-right commences at the last element of the shortest.  Ie. elements past the length of the shortest are ignored in the other LSTs.  At least one LST must be non-circular.

     fold should be preferred over fold-right if the order of processing doesn't matter, or can be arranged either way, since fold is a little more efficient.

     The way fold builds a result from iterating is quite general, it can do more than other iterations like say map or filter.  The following for example removes adjacent duplicate elements from a list,

          (define (delete-adjacent-duplicates lst)
            (fold-right (lambda (elem ret)
                          (if (equal? elem (first ret))
                              ret
                              (cons elem ret)))
                        (list (last lst))
                        lst))
          (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
          => (1 2 3 4 5)

     Clearly the same sort of thing can be done with a for-each and a variable in which to build the result, but a self-contained PROC can be re-used in multiple contexts, where a for-each would have to be written out each time.

 -- Scheme Procedure: pair-fold proc init lst1 ... lstN
 -- Scheme Procedure: pair-fold-right proc init lst1 ... lstN
     The same as fold and fold-right, but apply PROC to the pairs of the lists instead of the list elements.

 -- Scheme Procedure: reduce proc default lst
 -- Scheme Procedure: reduce-right proc default lst
     reduce is a variant of fold, where the first call to PROC is on two elements from LST, rather than one element and a given initial value.

     If LST is empty, reduce returns DEFAULT (this is the only use for DEFAULT).  If LST has just one element then that's the return value.  Otherwise PROC is called on the elements of LST.

     Each PROC call is (PROC ELEM PREVIOUS), where ELEM is from LST (the second and subsequent elements of LST), and PREVIOUS is the return from the previous call to PROC.  The first element of LST is the PREVIOUS for the first call to PROC.

     For example, the following adds a list of numbers, the calls made to + are shown.  (Of course + accepts multiple arguments and can add a list directly, with apply.)

          (reduce + 0 '(5 6 7)) => 18

          (+ 6 5)  => 11
          (+ 7 11) => 18

     reduce can be used instead of fold where the INIT value is an ``identity'', meaning a value which under PROC doesn't change the result, in this case 0 is an identity since (+ 5 0) is just 5.  reduce avoids that unnecessary call.

     reduce-right is a similar variation on fold-right, working from the end (ie. the right) of LST.  The last element of LST is the PREVIOUS for the first call to PROC, and the ELEM values go from the second last.

     reduce should be preferred over reduce-right if the order of processing doesn't matter, or can be arranged either way, since reduce is a little more efficient.

 -- Scheme Procedure: unfold p f g seed [tail-gen]
     unfold is defined as follows:

          (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 valu.

     seed
          The state value for the unfold.

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

     G produces a series of seed values, which are mapped to list elements by F.  These elements are put into a list in left-to-right order, and P tells when to stop unfolding.

 -- Scheme Procedure: unfold-right p f g seed [tail]
     Construct 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 valu.

     seed
          The state value for the unfold.

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

 -- Scheme Procedure: map f lst1 lst2 ...
     Map the procedure over the list(s) LST1, LST2, ... and return a list containing the results of the procedure applications. This procedure is extended with respect to R5RS, because the argument lists may have different lengths.  The result list will have the same length as the shortest argument lists.  The order in which F will be applied to the list element(s) is not specified.

 -- Scheme Procedure: for-each f lst1 lst2 ...
     Apply the procedure F to each pair of corresponding elements of the list(s) LST1, LST2, ....  The return value is not specified.  This procedure is extended with respect to R5RS, because the argument lists may have different lengths.  The shortest argument list determines the number of times F is called.  F will be applied to the list elements in left-to-right order.

 -- Scheme Procedure: append-map f lst1 lst2 ...
 -- Scheme Procedure: append-map! f lst1 lst2 ...
     Equivalent to

          (apply append (map f clist1 clist2 ...))

     and

          (apply append! (map f clist1 clist2 ...))

     Map F over the elements of the lists, just as in the map function. However, the results of the applications are appended together to make the final result. append-map uses append to append the results together; append-map! uses append!.

     The dynamic order in which the various applications of F are made is not specified.

 -- Scheme Procedure: map! f lst1 lst2 ...
     Linear-update variant of map -- map! is allowed, but not required, to alter the cons cells of LST1 to construct the result list.

     The dynamic order in which the various applications of F are made is not specified. In the n-ary case, LST2, LST3, ... must have at least as many elements as LST1.

 -- Scheme Procedure: pair-for-each f lst1 lst2 ...
     Like for-each, but applies the procedure F to the pairs from which the argument lists are constructed, instead of the list elements.  The return value is not specified.

 -- Scheme Procedure: filter-map f lst1 lst2 ...
     Like map, but only results from the applications of F which are true are saved in the result list.

Filtering and Partitioning
..........................

Filtering means to collect all elements from a list which satisfy a specific condition.  Partitioning a list means to make two groups of list elements, one which contains the elements satisfying a condition, and the other for the elements which don't.

The filter and filter! functions are implemented in the Guile core, see List Modification.

 -- Scheme Procedure: partition pred lst
 -- Scheme Procedure: partition! pred lst
     Split LST into those elements which do and don't satisfy the predicate PRED.

     The return is two values (see Multiple Values), the first being a list of all elements from LST which satisfy PRED, the second a list of those which do not.

     The elements in the result lists are in the same order as in LST but the order in which the calls (PRED elem) are made on the list elements is unspecified.

     partition does not change LST, but one of the returned lists may share a tail with it.  partition! may modify LST to construct its return.

 -- Scheme Procedure: remove pred lst
 -- Scheme Procedure: remove! pred lst
     Return a list containing all elements from LST which do not satisfy the predicate PRED.  The elements in the result list have the same order as in LST.  The order in which PRED is applied to the list elements is not specified.

     remove! is allowed, but not required to modify the structure of the input list.

Searching
.........

The procedures for searching elements in lists either accept a predicate or a comparison object for determining which elements are to be searched.

 -- Scheme Procedure: find pred lst
     Return the first element of LST which satisfies the predicate PRED and #f if no such element is found.

 -- Scheme Procedure: find-tail pred lst
     Return the first pair of LST whose CAR satisfies the predicate PRED and #f if no such element is found.

 -- Scheme Procedure: take-while pred lst
 -- Scheme Procedure: take-while! pred lst
     Return the longest initial prefix of LST whose elements all satisfy the predicate PRED.

     take-while! is allowed, but not required to modify the input list while producing the result.

 -- Scheme Procedure: drop-while pred lst
     Drop the longest initial prefix of LST whose elements all satisfy the predicate PRED.

 -- Scheme Procedure: span pred lst
 -- Scheme Procedure: span! pred lst
 -- Scheme Procedure: break pred lst
 -- Scheme Procedure: break! pred lst
     span splits the list LST into the longest initial prefix whose elements all satisfy the predicate PRED, and the remaining tail.  break inverts the sense of the predicate.

     span! and break! are allowed, but not required to modify the structure of the input list LST in order to produce the result.

     Note that the name break conflicts with the break binding established by while (see while do).  Applications wanting to use break from within a while loop will need to make a new define under a different name.

 -- Scheme Procedure: any pred lst1 lst2 ... lstN
     Test whether any set of elements from LST1 ... lstN satisfies PRED.  If so the return value is the return from the successful PRED call, or if not the return is #f.

     Each PRED call is (PRED ELEM1 ... ELEMN) taking an element from each LST.  The calls are made successively for the first, second, etc elements of the lists, stopping when PRED returns non-#f, or when the end of the shortest list is reached.

     The PRED call on the last set of elements (ie. when the end of the shortest list has been reached), if that point is reached, is a tail call.

 -- Scheme Procedure: every pred lst1 lst2 ... lstN
     Test whether every set of elements from LST1 ... lstN satisfies PRED.  If so the return value is the return from the final PRED call, or if not the return is #f.

     Each PRED call is (PRED ELEM1 ... ELEMN) taking an element from each LST.  The calls are made successively for the first, second, etc elements of the lists, stopping if PRED returns #f, or when the end of any of the lists is reached.

     The PRED call on the last set of elements (ie. when the end of the shortest list has been reached) is a tail call.

     If one of LST1 ... LSTN is empty then no calls to PRED are made, and the return is #t.

 -- Scheme Procedure: list-index pred lst1 ... lstN
     Return the index of the first set of elements, one from each of LST1...LSTN, which satisfies PRED.

     PRED is called as (PRED elem1 ... elemN). Searching stops when the end of the shortest LST is reached. The return index starts from 0 for the first set of elements.  If no set of elements pass then the return is #f.

          (list-index odd? '(2 4 6 9))      => 3
          (list-index = '(1 2 3) '(3 1 2))  => #f

 -- Scheme Procedure: member x lst [=]
     Return the first sublist of LST whose CAR is equal to X.  If X does not appear in LST, return #f.

     Equality is determined by equal?, or by the equality predicate = if given.  = is called (= X elem), ie. with the given X first, so for example to find the first element greater than 5,

          (member 5 '(3 5 1 7 2 9) <) => (7 2 9)

     This version of member extends the core member (see List Searching) by accepting an equality predicate.

Deleting
........

 -- Scheme Procedure: delete x lst [=]
 -- Scheme Procedure: delete! x lst [=]
     Return a list containing the elements of LST but with those equal to X deleted.  The returned elements will be in the same order as they were in LST.

     Equality is determined by the = predicate, or equal? if not given.  An equality call is made just once for each element, but the order in which the calls are made on the elements is unspecified.

     The equality calls are always (= x elem), ie. the given X is first.  This means for instance elements greater than 5 can be deleted with (delete 5 lst <).

     delete does not modify LST, but the return might share a common tail with LST.  delete! may modify the structure of LST to construct its return.

     These functions extend the core delete and delete! in accepting an equality predicate.  (see List Modification)

 -- Scheme Procedure: delete-duplicates lst [=]
 -- Scheme Procedure: delete-duplicates! lst [=]
     Return a list containing the elements of LST but without duplicates.

     When elements are equal, only the first in LST is retained. Equal elements can be anywhere in LST, they don't have to be adjacent.  The returned list will have the retained elements in the same order as they were in LST.

     Equality is determined by the = predicate, or equal? if not given.  Calls (= x y) are made with element X being before Y in LST.  A call is made at most once for each combination, but the sequence of the calls across the elements is unspecified.

     delete-duplicates does not modify LST, but the return might share a common tail with LST.  delete-duplicates! may modify the structure of LST to construct its return.

     In the worst case, this is an O(N^2) algorithm because it must check each element against all those preceding it.  For long lists it is more efficient to sort and then compare only adjacent elements.

Association Lists
.................

Association lists are described in detail in section Association Lists.  The present section only documents the additional procedures for dealing with association lists defined by SRFI-1.

 -- Scheme Procedure: assoc key alist [=]
     Return the pair from ALIST which matches KEY.  Equality is determined by =, which defaults to equal? if not given. ALIST must be an association lists---a list of pairs.

     This function extends the core assoc by accepting an equality predicate.  (see Association Lists)

 -- Scheme Procedure: alist-cons key datum alist
     Equivalent to

          (cons (cons KEY DATUM) ALIST)

     This procedure is used to coons a new pair onto an existing association list.

 -- Scheme Procedure: alist-copy alist
     Return a newly allocated copy of ALIST, that means that the spine of the list as well as the pairs are copied.

 -- Scheme Procedure: alist-delete key alist [=]
 -- Scheme Procedure: alist-delete! key alist [=]
     Return a list containing the elements of ALIST but with those elements whose keys are equal to KEY deleted.  The returned elements will be in the same order as they were in ALIST.

     Equality is determined by the = predicate, or equal? if not given.  The order in which elements are tested is unspecified, but each equality call is made (= key alistkey), ie. the given KEY parameter is first and the key from ALIST second. This means for instance all associations with a key greater than 5 can be removed with (alist-delete 5 alist <).

     alist-delete does not modify ALIST, but the return might share a common tail with ALIST.  alist-delete! may modify the list structure of ALIST to construct its return.

Set Operations on Lists
.......................

Lists can be used for representing sets of objects.  The procedures documented in this section can be used for such set representations. Man combining several sets or adding elements, they make sure that no object is contained more than once in a given list.  Please note that lists are not a too efficient implementation method for sets, so if you need high performance, you should think about implementing a custom data structure for representing sets, such as trees, bitsets, hash tables or something similar.

All these procedures accept an equality predicate as the first argument.  This predicate is used for testing the objects in the list sets for sameness.

 -- Scheme Procedure: lset<= = list1 ...
     Return #t if every LISTI is a subset of LISTI+1, otherwise return #f.  Returns #t if called with less than two arguments. = is used for testing element equality.

 -- Scheme Procedure: lset= = list1 list2 ...
     Return #t if all argument lists are equal. = is used for testing element equality.

 -- Scheme Procedure: lset-adjoin = list elt1 ...
     Add all ELTS to the list LIST, suppressing duplicates and return the resulting list.  = is used for testing element equality.

 -- Scheme Procedure: lset-union = list1 ...
 -- Scheme Procedure: lset-union! = list1 ...
     Return the union of all argument list sets.  The union is the set of all elements which appear in any of the argument sets. lset-union! is allowed, but not required to modify its first argument. = is used for testing element equality.

 -- Scheme Procedure: lset-intersection = list1 list2 ...
 -- Scheme Procedure: lset-intersection! = list1 list2 ...
     Return the intersection of all argument list sets.  The intersection is the set containing all elements which appear in all argument sets. lset-intersection! is allowed, but not required to modify its first argument. = is used for testing element equality.

 -- Scheme Procedure: lset-difference = list1 list2 ...
 -- Scheme Procedure: lset-difference! = list1 list2 ...
     Return the difference of all argument list sets.  The difference is the the set containing all elements of the first list which do not appear in the other lists.  lset-difference!  is allowed, but not required to modify its first argument. = is used for testing element equality.

 -- Scheme Procedure: lset-xor = list1 ...
 -- Scheme Procedure: lset-xor! = list1 ...
     Return the set containing all elements which appear in the first argument list set, but not in the second; or, more generally: which appear in an odd number of sets.  lset-xor!  is allowed, but not required to modify its first argument. = is used for testing element equality.

 -- Scheme Procedure: lset-diff+intersection = list1 list2 ...
 -- Scheme Procedure: lset-diff+intersection! = list1 list2 ...
     Return two values, the difference and the intersection of the argument list sets. This works like a combination of lset-difference and lset-intersection, but is more efficient. lset-diff+intersection!  is allowed, but not required to modify its first argument. = is used for testing element equality.  You have to use some means to deal with the multiple values these procedures return (see Multiple Values).

SRFI-2 - and-let*
-----------------

The following syntax can be obtained with

     (use-modules (srfi srfi-2))

 -- library syntax: and-let* (clause ...) body ...
     A combination of and and let*.

     Each CLAUSE is evaluated in turn, and if #f is obtained then evaluation stops and #f is returned.  If all are non-#f then BODY is evaluated and the last form gives the return value, or if BODY is empty then the result is #t. Each CLAUSE should be one of the following,

     (symbol expr)
          Evaluate EXPR, check for #f, and bind it to SYMBOL. Like let*, that binding is available to subsequent clauses.

     (expr)
          Evaluate EXPR and check for #f.

     symbol
          Get the value bound to SYMBOL and check for #f.

     Notice that (expr) has an ``extra'' pair of parentheses, for instance ((eq? x y)).  One way to remember this is to imagine the symbol in (symbol expr) is omitted.

     and-let* is good for calculations where a #f value means termination, but where a non-#f value is going to be needed in subsequent expressions.

     The following illustrates this, it returns text between brackets [...] in a string, or #f if there are no such brackets (ie. either string-index gives #f).

          (define (extract-brackets str)
            (and-let* ((start (string-index str #\[))
                       (end   (string-index str #\] start)))
              (substring str (1+ start) end)))

     The following shows plain variables and expressions tested too. diagnostic-levels is taken to be an alist associating a diagnostic type with a level.  str is printed only if the type is known and its level is high enough.

          (define (show-diagnostic type str)
            (and-let* (want-diagnostics
                       (level (assq-ref diagnostic-levels type))
                       ((>= level current-diagnostic-level)))
              (display str)))

     The advantage of and-let* is that an extended sequence of expressions and tests doesn't require lots of nesting as would arise from separate and and let*, or from cond with =>.

SRFI-4 - Homogeneous numeric vector datatypes
---------------------------------------------

The SRFI-4 procedures and data types are always available, see Uniform Numeric Vectors.

SRFI-6 - Basic String Ports
---------------------------

SRFI-6 defines the procedures open-input-string, open-output-string and get-output-string.  These procedures are included in the Guile core, so using this module does not make any difference at the moment.  But it is possible that support for SRFI-6 will be factored out of the core library in the future, so using this module does not hurt, after all.

SRFI-8 - receive
----------------

receive is a syntax for making the handling of multiple-value procedures easier.  It is documented in see Multiple Values.

SRFI-9 - define-record-type
---------------------------

This SRFI is a syntax for defining new record types and creating predicate, constructor, and field getter and setter functions.  In Guile this is simply an alternate interface to the core record functionality (see Records).  It can be used with,

     (use-modules (srfi srfi-9))

 -- library syntax: define-record-type type
 (constructor fieldname ...)
 predicate
 (fieldname accessor [modifier]) ...

     Create a new record type, and make various defines for using it.  This syntax can only occur at the top-level, not nested within some other form.

     TYPE is bound to the record type, which is as per the return from the core make-record-type.  TYPE also provides the name for the record, as per record-type-name.

     CONSTRUCTOR is bound to a function to be called as (CONSTRUCTOR fieldval ...) to create a new record of this type.  The arguments are initial values for the fields, one argument for each field, in the order they appear in the define-record-type form.

     The FIELDNAMEs provide the names for the record fields, as per the core record-type-fields etc, and are referred to in the subsequent accessor/modifier forms.

     PREDICTATE is bound to a function to be called as (PREDICATE obj).  It returns #t or #f according to whether OBJ is a record of this type.

     Each ACCESSOR is bound to a function to be called (ACCESSOR record) to retrieve the respective field from a RECORD.  Similarly each MODIFIER is bound to a function to be called (MODIFIER record val) to set the respective field in a RECORD.

An example will illustrate typical usage,

     (define-record-type employee-type
       (make-employee name age salary)
       employee?
       (name    get-employee-name)
       (age     get-employee-age    set-employee-age)
       (salary  get-employee-salary set-employee-salary))

This creates a new employee data type, with name, age and salary fields.  Accessor functions are created for each field, but no modifier function for the name (the intention in this example being that it's established only when an employee object is created).  These can all then be used as for example,

     employee-type => #<record-type employee-type>

     (define fred (make-employee "Fred" 45 20000.00))

     (employee? fred)        => #t
     (get-employee-age fred) => 45
     (set-employee-salary fred 25000.00)  ;; pay rise

The functions created by define-record-type are ordinary top-level defines.  They can be redefined or set! as desired, exported from a module, etc.

SRFI-10 - Hash-Comma Reader Extension
-------------------------------------

This SRFI implements a reader extension #,() called hash-comma. It allows the reader to give new kinds of objects, for use both in data and as constants or literals in source code.  This feature is available with

     (use-modules (srfi srfi-10))

The new read syntax is of the form

     #,(TAG ARG...)

where TAG is a symbol and the ARGs are objects taken as parameters.  TAGs are registered with the following procedure.

 -- Scheme Procedure: define-reader-ctor tag proc
     Register PROC as the constructor for a hash-comma read syntax starting with symbol TAG, ie. #,(TAG arg...). PROC is called with the given arguments (PROC arg...) and the object it returns is the result of the read.

For example, a syntax giving a list of N copies of an object.

     (define-reader-ctor 'repeat
       (lambda (obj reps)
         (make-list reps obj)))

     (display '#,(repeat 99 3))
     -| (99 99 99)

Notice the quote ' when the #,( ) is used.  The repeat handler returns a list and the program must quote to use it literally, the same as any other list.  Ie.

     (display '#,(repeat 99 3))
     =>
     (display '(99 99 99))

When a handler returns an object which is self-evaluating, like a number or a string, then there's no need for quoting, just as there's no need when giving those directly as literals.  For example an addition,

     (define-reader-ctor 'sum
       (lambda (x y)
         (+ x y)))
     (display #,(sum 123 456)) -| 579

A typical use for #,() is to get a read syntax for objects which don't otherwise have one.  For example, the following allows a hash table to be given literally, with tags and values, ready for fast lookup.

     (define-reader-ctor 'hash
       (lambda elems
         (let ((table (make-hash-table)))
           (for-each (lambda (elem)
     		  (apply hash-set! table elem))
     		elems)
           table)))

     (define (animal->family animal)
       (hash-ref '#,(hash ("tiger" "cat")
                          ("lion"  "cat")
                          ("wolf"  "dog"))
                 animal))

     (animal->family "lion") => "cat"

Or for example the following is a syntax for a compiled regular expression (see Regular Expressions).

     (use-modules (ice-9 regex))

     (define-reader-ctor 'regexp make-regexp)

     (define (extract-angs str)
       (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
         (and match
              (match:substring match 1))))

     (extract-angs "foo <BAR> quux") => "BAR"

#,() is somewhat similar to define-macro (see Macros) in that handler code is run to produce a result, but #,() operates at the read stage, so it can appear in data for read (see Scheme Read), not just in code to be executed.

Because #,() is handled at read-time it has no direct access to variables etc.  A symbol in the arguments is just a symbol, not a variable reference.  The arguments are essentially constants, though the handler procedure can use them in any complicated way it might want.

Once (srfi srfi-10) has loaded, #,() is available globally, there's no need to use (srfi srfi-10) in later modules.  Similarly the tags registered are global and can be used anywhere once registered.

There's no attempt to record what previous #,() forms have been seen, if two identical forms occur then two calls are made to the handler procedure.  The handler might like to maintain a cache or similar to avoid making copies of large objects, depending on expected usage.

In code the best uses of #,() are generally when there's a lot of objects of a particular kind as literals or constants.  If there's just a few then some local variables and initializers are fine, but that becomes tedious and error prone when there's a lot, and the anonymous and compact syntax of #,() is much better.

SRFI-11 - let-values
--------------------

This module implements the binding forms for multiple values let-values and let-values*.  These forms are similar to let and let* (see Local Bindings), but they support binding of the values returned by multiple-valued expressions.

Write (use-modules (srfi srfi-11)) to make the bindings available.

     (let-values (((x y) (values 1 2))
                  ((z f) (values 3 4)))
        (+ x y z f))
     =>
     10

let-values performs all bindings simultaneously, which means that no expression in the binding clauses may refer to variables bound in the same clause list.  let-values*, on the other hand, performs the bindings sequentially, just like let* does for single-valued expressions.

SRFI-13 - String Library
------------------------

The SRFI-13 procedures are always available, see Strings.

SRFI-14 - Character-set Library
-------------------------------

The SRFI-14 data type and procedures are always available, see Character Sets.

SRFI-16 - case-lambda
---------------------

The syntactic form case-lambda creates procedures, just like lambda, but has syntactic extensions for writing procedures of varying arity easier.

The syntax of the case-lambda form is defined in the following EBNF grammar.

     <case-lambda>
        --> (case-lambda <case-lambda-clause>)
     <case-lambda-clause>
        --> (<formals> <definition-or-command>*)
     <formals>
        --> (<identifier>*)
          | (<identifier>* . <identifier>)
          | <identifier>

The value returned by a case-lambda form is a procedure which matches the number of actual arguments against the formals in the various clauses, in order.  Formals means a formal argument list just like with lambda (see Lambda). The first matching clause is selected, the corresponding values from the actual parameter list are bound to the variable names in the clauses and the body of the clause is evaluated.  If no clause matches, an error is signalled.

The following (silly) definition creates a procedure FOO which acts differently, depending on the number of actual arguments.  If one argument is given, the constant #t is returned, two arguments are added and if more arguments are passed, their product is calculated.

     (define foo (case-lambda
                   ((x) #t)
                   ((x y) (+ x y))
                   (z
                     (apply * z))))
     (foo 'bar)
     =>
     #t
     (foo 2 4)
     =>
     6
     (foo 3 3 3)
     =>
     27
     (foo)
     =>
     1

The last expression evaluates to 1 because the last clause is matched, Z is bound to the empty list and the following multiplication, applied to zero arguments, yields 1.

SRFI-17 - Generalized set!
--------------------------

This is an implementation of SRFI-17: Generalized set!

It exports the Guile procedure make-procedure-with-setter under the SRFI name getter-with-setter and exports the standard procedures car, cdr, ..., cdddr, string-ref and vector-ref as procedures with setters, as required by the SRFI.

SRFI-17 was heavily criticized during its discussion period but it was finalized anyway.  One issue was its concept of globally associating setter properties with (procedure) values, which is non-Schemy. For this reason, this implementation chooses not to provide a way to set the setter of a procedure.  In fact, (set!  (setter PROC) SETTER) signals an error.  The only way to attach a setter to a procedure is to create a new object (a procedure with setter) via the getter-with-setter procedure. This procedure is also specified in the SRFI.  Using it avoids the described problems.

SRFI-19 - Time/Date Library
---------------------------

This is an implementation of the SRFI-19 time/date library.  The functions and variables described here are provided by

     (use-modules (srfi srfi-19))

SRFI-19 Introduction
....................

This module implements time and date representations and calculations, in various time systems, including universal time (UTC) and atomic time (TAI).

For those not familiar with these time systems, TAI is based on a fixed length second derived from oscillations of certain atoms.  UTC differs from TAI by an integral number of seconds, which is increased or decreased at announced times to keep UTC aligned to a mean solar day (the orbit and rotation of the earth are not quite constant).

So far, only increases in the TAI <-> UTC difference have been needed.  Such an increase is a ``leap second'', an extra second of TAI introduced at the end of a UTC day. When working entirely within UTC this is never seen, every day simply has 86400 seconds.  But when converting from TAI to a UTC date, an extra 23:59:60 is present, where normally a day would end at 23:59:59. Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI seconds.

In the current implementation, the system clock is assumed to be UTC, and a table of leap seconds in the code converts to TAI.  See comments in srfi-19.scm for how to update this table.

Also, for those not familiar with the terminology, a Julian Day is a real number which is a count of days and fraction of a day, in UTC, starting from -4713-01-01T12:00:00Z, ie. midday Monday 1 Jan 4713 B.C.  A Modified Julian Day is the same, but starting from 1858-11-17T00:00:00Z, ie. midnight 17 November 1858 UTC.  That time is julian day 2400000.5.

SRFI-19 Time
............

A time object has type, seconds and nanoseconds fields representing a point in time starting from some epoch.  This is an arbitrary point in time, not just a time of day.  Although times are represented in nanoseconds, the actual resolution may be lower.

The following variables hold the possible time types.  For instance (current-time time-process) would give the current CPU process time.

 -- Variable: time-utc
     Universal Coordinated Time (UTC).

 -- Variable: time-tai
     International Atomic Time (TAI).

 -- Variable: time-monotonic
     Monotonic time, meaning a monotonically increasing time starting from an unspecified epoch.

     Note that in the current implementation time-monotonic is the same as time-tai, and unfortunately is therefore affected by adjustments to the system clock.  Perhaps this will change in the future.

 -- Variable: time-duration
     A duration, meaning simply a difference between two times.

 -- Variable: time-process
     CPU time spent in the current process, starting from when the process began.

 -- Variable: time-thread
     CPU time spent in the current thread.  Not currently implemented.

 -- Function: time? obj
     Return #t if OBJ is a time object, or #f if not.

 -- Function: make-time type nanoseconds seconds
     Create a time object with the given TYPE, SECONDS and NANOSECONDS.

 -- Function: time-type time
 -- Function: time-nanosecond time
 -- Function: time-second time
 -- Function: set-time-type! time type
 -- Function: set-time-nanosecond! time nsec
 -- Function: set-time-second! time sec
     Get or set the type, seconds or nanoseconds fields of a time object.

     set-time-type! merely changes the field, it doesn't convert the time value.  For conversions, see SRFI-19 Time/Date conversions.

 -- Function: copy-time time
     Return a new time object, which is a copy of the given TIME.

 -- Function: current-time [type]
     Return the current time of the given TYPE.  The default TYPE is time-utc.

     Note that the name current-time conflicts with the Guile core current-time function (see Time).  Applications wanting to use both will need to use a different name for one of them.

 -- Function: time-resolution [type]
     Return the resolution, in nanoseconds, of the given time TYPE. The default TYPE is time-utc.

 -- Function: time<=? t1 t2
 -- Function: time<? t1 t2
 -- Function: time=? t1 t2
 -- Function: time>=? t1 t2
 -- Function: time>? t1 t2
     Return #t or #f according to the respective relation between time objects T1 and T2.  T1 and T2 must be the same time type.

 -- Function: time-difference t1 t2
 -- Function: time-difference! t1 t2
     Return a time object of type time-duration representing the period between T1 and T2.  T1 and T2 must be the same time type.

     time-difference returns a new time object, time-difference! may modify T1 to form its return.

 -- Function: add-duration time duration
 -- Function: add-duration! time duration
 -- Function: subtract-duration time duration
 -- Function: subtract-duration! time duration
     Return a time object which is TIME with the given DURATION added or subtracted.  DURATION must be a time object of type time-duration.

     add-duration and subtract-duration return a new time object.  add-duration! and subtract-duration! may modify the given TIME to form their return.

SRFI-19 Date
............

A date object represents a date in the Gregorian calendar and a time of day on that date in some timezone.

The fields are year, month, day, hour, minute, second, nanoseconds and timezone.  A date object is immutable, its fields can be read but they cannot be modified once the object is created.

 -- Function: date? obj
     Return #t if OBJ is a date object, or #f if not.

 -- Function: make-date nsecs seconds minutes hours date month year zone-offset
     Create a new date object.

 -- Function: date-nanosecond date
     Nanoseconds, 0 to 999999999.

 -- Function: date-second date
     Seconds, 0 to 59, or 60 for a leap second.  60 is never seen when working entirely within UTC, it's only when converting to or from TAI.

 -- Function: date-minute date
     Minutes, 0 to 59.

 -- Function: date-hour date
     Hour, 0 to 23.

 -- Function: date-day date
     Day of the month, 1 to 31 (or less, according to the month).

 -- Function: date-month date
     Month, 1 to 12.

 -- Function: date-year date
     Year, eg. 2003.  Dates B.C. are negative, eg. -46 is 46 B.C.  There is no year 0, year -1 is followed by year 1.

 -- Function: date-zone-offset date
     Time zone, an integer number of seconds east of Greenwich.

 -- Function: date-year-day date
     Day of the year, starting from 1 for 1st January.

 -- Function: date-week-day date
     Day of the week, starting from 0 for Sunday.

 -- Function: date-week-number date dstartw
     Week of the year, ignoring a first partial week.  DSTARTW is the day of the week which is taken to start a week, 0 for Sunday, 1 for Monday, etc.

 -- Function: current-date [tz-offset]
     Return a date object representing the current date/time, in UTC offset by TZ-OFFSET.  TZ-OFFSET is seconds east of Greenwich and defaults to the local timezone.

 -- Function: current-julian-day
     Return the current Julian Day.

 -- Function: current-modified-julian-day
     Return the current Modified Julian Day.

SRFI-19 Time/Date conversions
.............................

 -- Function: date->julian-day date
 -- Function: date->modified-julian-day date
 -- Function: date->time-monotonic date
 -- Function: date->time-tai date
 -- Function: date->time-utc date

 -- Function: julian-day->date jdn [tz-offset]
 -- Function: julian-day->time-monotonic jdn
 -- Function: julian-day->time-tai jdn
 -- Function: julian-day->time-utc jdn

 -- Function: modified-julian-day->date jdn [tz-offset]
 -- Function: modified-julian-day->time-monotonic jdn
 -- Function: modified-julian-day->time-tai jdn
 -- Function: modified-julian-day->time-utc jdn

 -- Function: time-monotonic->date time [tz-offset]
 -- Function: time-monotonic->time-tai time
 -- Function: time-monotonic->time-tai! time
 -- Function: time-monotonic->time-utc time
 -- Function: time-monotonic->time-utc! time

 -- Function: time-tai->date time [tz-offset]
 -- Function: time-tai->julian-day time
 -- Function: time-tai->modified-julian-day time
 -- Function: time-tai->time-monotonic time
 -- Function: time-tai->time-monotonic! time
 -- Function: time-tai->time-utc time
 -- Function: time-tai->time-utc! time

 -- Function: time-utc->date time [tz-offset]
 -- Function: time-utc->julian-day time
 -- Function: time-utc->modified-julian-day time
 -- Function: time-utc->time-monotonic time
 -- Function: time-utc->time-monotonic! time
 -- Function: time-utc->time-tai time
 -- Function: time-utc->time-tai! time

     Convert between dates, times and days of the respective types.  For instance time-tai->time-utc accepts a TIME object of type time-tai and returns an object of type time-utc.

     The ! variants may modify their TIME argument to form their return.  The plain functions create a new object.

     For conversions to dates, TZ-OFFSET is seconds east of Greenwich.  The default is the local timezone, at the given time, as provided by the system, using localtime (see Time).

     On 32-bit systems, localtime is limited to a 32-bit time_t, so a default TZ-OFFSET is only available for times between Dec 1901 and Jan 2038.  For prior dates an application might like to use the value in 1902, though some locations have zone changes prior to that.  For future dates an application might like to assume today's rules extend indefinitely.  But for correct daylight savings transitions it will be necessary to take an offset for the same day and time but a year in range and which has the same starting weekday and same leap/non-leap (to support rules like last Sunday in October).

SRFI-19 Date to string
......................

 -- Function: date->string date [format]
     Convert a date to a string under the control of a format. FORMAT should be a string containing ~ escapes, which will be expanded as per the following conversion table.  The default FORMAT is ~c, a locale-dependent date and time.

     Many of these conversion characters are the same as POSIX strftime (see Time), but there are some extras and some variations.

     ~~   literal ~
     ~a   locale abbreviated weekday, eg. Sun
     ~A   locale full weekday, eg. Sunday
     ~b   locale abbreviated month, eg. Jan
     ~B   locale full month, eg. January
     ~c   locale date and time, eg.

     Fri Jul 14 20:28:42-0400 2000
     ~d   day of month, zero padded, 01 to 31

     ~e   day of month, blank padded,  1 to 31
     ~f   seconds and fractional seconds,
     with locale decimal point, eg. 5.2
     ~h   same as ~b
     ~H   hour, 24-hour clock, zero padded, 00 to 23
     ~I   hour, 12-hour clock, zero padded, 01 to 12
     ~j   day of year, zero padded, 001 to 366
     ~k   hour, 24-hour clock, blank padded,  0 to 23
     ~l   hour, 12-hour clock, blank padded,  1 to 12
     ~m   month, zero padded, 01 to 12
     ~M   minute, zero padded, 00 to 59
     ~n   newline
     ~N   nanosecond, zero padded, 000000000 to 999999999
     ~p   locale AM or PM
     ~r   time, 12 hour clock, ~I:~M:~S ~p
     ~s   number of full seconds since ``the epoch'' in UTC
     ~S   second, zero padded 00 to 60

     (usual limit is 59, 60 is a leap second)
     ~t   horizontal tab character
     ~T   time, 24 hour clock, ~H:~M:~S
     ~U   week of year, Sunday first day of week,
     00 to 52
     ~V   week of year, Monday first day of week,
     01 to 53
     ~w   day of week, 0 for Sunday, 0 to 6
     ~W   week of year, Monday first day of week,
     00 to 52

     ~y   year, two digits, 00 to 99
     ~Y   year, full, eg. 2003
     ~z   time zone, RFC-822 style
     ~Z   time zone symbol (not currently implemented)
     ~1   ISO-8601 date, ~Y-~m-~d
     ~2   ISO-8601 time+zone, ~k:~M:~S~z
     ~3   ISO-8601 time, ~k:~M:~S
     ~4   ISO-8601 date/time+zone, ~Y-~m-~dT~k:~M:~S~z
     ~5   ISO-8601 date/time, ~Y-~m-~dT~k:~M:~S

Conversions ~D, ~x and ~X are not currently described here, since the specification and reference implementation differ.

Currently Guile doesn't implement any localizations for the above, all outputs are in English, and the ~c conversion is POSIX ctime style ~a ~b ~d ~H:~M:~S~z ~Y.  This may change in the future.

SRFI-19 String to date
......................

 -- Function: string->date input template
     Convert an INPUT string to a date under the control of a TEMPLATE string.  Return a newly created date object.

     Literal characters in TEMPLATE must match characters in INPUT and ~ escapes must match the input forms described in the table below.  ``Skip to'' means characters up to one of the given type are ignored, or ``no skip'' for no skipping.  ``Read'' is what's then read, and ``Set'' is the field affected in the date object.

     For example ~Y skips input characters until a digit is reached, at which point it expects a year and stores that to the year field of the date.

     Skip to
     Read
     Set

     ~~
     no skip
     literal ~
     nothing

     ~a
     char-alphabetic?
     locale abbreviated weekday name
     nothing

     ~A
     char-alphabetic?
     locale full weekday name
     nothing

     ~b
     char-alphabetic?
     locale abbreviated month name
     date-month

     ~B
     char-alphabetic?
     locale full month name
     date-month

     ~d
     char-numeric?
     day of month
     date-day

     ~e
     no skip
     day of month, blank padded
     date-day

     ~h
     same as ~b

     ~H
     char-numeric?
     hour
     date-hour

     ~k
     no skip
     hour, blank padded
     date-hour

     ~m
     char-numeric?
     month
     date-month

     ~M
     char-numeric?
     minute
     date-minute

     ~S
     char-numeric?
     second
     date-second

     ~y
     no skip
     2-digit year
     date-year within 50 years

     ~Y
     char-numeric?
     year
     date-year

     ~z
     no skip
     time zone
     date-zone-offset

     Notice that the weekday matching forms don't affect the date object returned, instead the weekday will be derived from the day, month and year.

     Currently Guile doesn't implement any localizations for the above, month and weekday names are always expected in English.  This may change in the future.

SRFI-26 - specializing parameters
---------------------------------

This SRFI provides a syntax for conveniently specializing selected parameters of a function.  It can be used with,

     (use-modules (srfi srfi-26))

 -- library syntax: cut slot ...
 -- library syntax: cute slot ...
     Return a new procedure which will make a call (SLOT ...) but with selected parameters specialized to given expressions.

     An example will illustrate the idea.  The following is a specialization of write, sending output to my-output-port,

          (cut write <> my-output-port)
          =>
          (lambda (obj) (write obj my-output-port))

     The special symbol <> indicates a slot to be filled by an argument to the new procedure.  my-output-port on the other hand is an expression to be evaluated and passed, ie. it specializes the behaviour of write.

     <>
          A slot to be filled by an argument from the created procedure. Arguments are assigned to <> slots in the order they appear in the cut form, there's no way to re-arrange arguments.

          The first argument to cut is usually a procedure (or expression giving a procedure), but <> is allowed there too.  For example,

               (cut <> 1 2 3)
               =>
               (lambda (proc) (proc 1 2 3))

     <...>
          A slot to be filled by all remaining arguments from the new procedure. This can only occur at the end of a cut form.

          For example, a procedure taking a variable number of arguments like max but in addition enforcing a lower bound,

               (define my-lower-bound 123)

               (cut max my-lower-bound <...>)
               =>
               (lambda arglist (apply max my-lower-bound arglist))

     For cut the specializing expressions are evaluated each time the new procedure is called.  For cute they're evaluated just once, when the new procedure is created.  The name cute stands for ``cut with evaluated arguments''.  In all cases the evaluations take place in an unspecified order.

     The following illustrates the difference between cut and cute,

          (cut format <> "the time is ~s" (current-time))
          =>
          (lambda (port) (format port "the time is ~s" (current-time)))

          (cute format <> "the time is ~s" (current-time))
          =>
          (let ((val (current-time)))
            (lambda (port) (format port "the time is ~s" val))

     (There's no provision for a mixture of cut and cute where some expressions would be evaluated every time but others evaluated only once.)

     cut is really just a shorthand for the sort of lambda forms shown in the above examples.  But notice cut avoids the need to name unspecialized parameters, and is more compact.  Use in functional programming style or just with map, for-each or similar is typical.

          (map (cut * 2 <>) '(1 2 3 4))

          (for-each (cut write <> my-port) my-list)

SRFI-31 - A special form `rec' for recursive evaluation
-------------------------------------------------------

SRFI-31 defines a special form that can be used to create self-referential expressions more conveniently.  The syntax is as follows:

     <rec expression> --> (rec <variable> <expression>)
     <rec expression> --> (rec (<variable>+) <body>)

The first syntax can be used to create self-referential expressions, for example:

       guile> (define tmp (rec ones (cons 1 (delay ones))))

The second syntax can be used to create anonymous recursive functions:

       guile> (define tmp (rec (display-n item n)
                            (if (positive? n)
                                (begin (display n) (display-n (- n 1))))))
       guile> (tmp 42 3)
       424242
       guile>

SRFI-39 - Parameters
--------------------

This SRFI provides parameter objects, which implement dynamically bound locations for values.  The functions below are available from

     (use-modules (srfi srfi-39))

A parameter object is a procedure.  Called with no arguments it returns its value, called with one argument it sets the value.

     (define my-param (make-parameter 123))
     (my-param) => 123
     (my-param 456)
     (my-param) => 456

The parameterize special form establishes new locations for parameters, those new locations having effect within the dynamic scope of the parameterize body.  Leaving restores the previous locations, or re-entering through a saved continuation will again use the new locations.

     (parameterize ((my-param 789))
       (my-param) => 789
       )
     (my-param) => 456

Parameters are like dynamically bound variables in other Lisp dialets. They allow an application to establish parameter settings (as the name suggests) just for the execution of a particular bit of code, restoring when done.  Examples of such parameters might be case-sensitivity for a search, or a prompt for user input.

Global variables are not as good as parameter objects for this sort of thing.  Changes to them are visible to all threads, but in Guile parameter object locations are per-thread, thereby truely limiting the effect of parameterize to just its dynamic execution.

Passing arguments to functions is thread-safe, but that soon becomes tedious when there's more than a few or when they need to pass down through several layers of calls before reaching the point they should affect.  And introducing a new setting to existing code is often easier with a parameter object than adding arguments.

 -- Function: make-parameter init [converter]
     Return a new parameter object, with initial value INIT.

     A parameter object is a procedure.  When called (param) it returns its value, or a call (param val) sets its value.  For example,

          (define my-param (make-parameter 123))
          (my-param) => 123

          (my-param 456)
          (my-param) => 456

     If a CONVERTER is given, then a call (CONVERTER val) is made for each value set, its return is the value stored. Such a call is made for the INIT initial value too.

     A CONVERTER allows values to be validated, or put into a canonical form.  For example,

          (define my-param (make-parameter 123
                             (lambda (val)
                               (if (not (number? val))
                                   (error "must be a number"))
                               (inexact->exact val))))
          (my-param 0.75)
          (my-param) => 3/4

 -- library syntax: parameterize ((param value) ...) body ...
     Establish a new dynamic scope with the given PARAMs bound to new locations and set to the given VALUEs.  BODY is evaluated in that environment, the result is the return from the last form in BODY.

     Each PARAM is an expression which is evaluated to get the parameter object.  Often this will just be the name of a variable holding the object, but it can be anything that evaluates to a parameter.

     The PARAM expressions and VALUE expressions are all evaluated before establishing the new dynamic bindings, and they're evaluated in an unspecified order.

     For example,

          (define prompt (make-parameter "Type something: "))
          (define (get-input)
            (display (prompt))
            ...)

          (parameterize ((prompt "Type a number: "))
            (get-input)
            ...)

 -- Parameter object: current-input-port [new-port]
 -- Parameter object: current-output-port [new-port]
 -- Parameter object: current-error-port [new-port]
     This SRFI extends the core current-input-port and current-output-port, making them parameter objects.  The Guile-specific current-error-port is extended too, for consistency.  (see Default Ports.)

     This is an upwardly compatible extension, a plain call like (current-input-port) still returns the current input port, and set-current-input-port can still be used.  But the port can now also be set with (current-input-port my-port) and bound dynamically with parameterize.

 -- Function: with-parameters* param-list value-list thunk
     Establish a new dynamic scope, as per parameterize above, taking parameters from PARAM-LIST and corresponding values from VALUES-LIST.  A call (THUNK) is made in the new scope and the result from that THUNK is the return from with-parameters*.

     This function is a Guile-specific addition to the SRFI, it's similar to the core with-fluids* (see Fluids and Dynamic States).

Parameter objects are implemented using fluids (see Fluids and Dynamic States), so each dynamic state has it's own parameter locations.  That includes the separate locations when outside any parameterize form.  When a parameter is created it gets a separate initial location in each dynamic state, all initialized to the given INIT value.

As alluded to above, because each thread usually has a separate dynamic state, each thread has it's own locations behind parameter objects, and changes in one thread are not visible to any other.  When a new dynamic state or thread is created, the values of parameters in the originating context are copied, into new locations.

SRFI-39 doesn't specify the interaction between parameter objects and threads, so the threading behaviour described here should be regarded as Guile-specific.

SRFI-55 - Requiring Features
----------------------------

SRFI-55 provides require-extension which is a portable mechanism to load selected SRFI modules.  This is implemented in the Guile core, there's no module needed to get SRFI-55 itself.

 -- library syntax: require-extension clause...
     Require each of the given CLAUSE features, throwing an error if any are unavailable.

     A CLAUSE is of the form (IDENTIFIER arg...).  The only IDENTIFIER currently supported is srfi and the arguments are SRFI numbers.  For example to get SRFI-1 and SRFI-6,

          (require-extension (srfi 1 6))

     require-extension can only be used at the top-level.

     A Guile-specific program can simply use-modules to load SRFIs not already in the core, require-extension is for programs designed to be portable to other Scheme implementations.

SRFI-60 - Integers as Bits
--------------------------

This SRFI provides various functions for treating integers as bits and for bitwise manipulations.  These functions can be obtained with,

     (use-modules (srfi srfi-60))

Integers are treated as infinite precision twos-complement, the same as in the core logical functions (see Bitwise Operations).  And likewise bit indexes start from 0 for the least significant bit.  The following functions in this SRFI are already in the Guile core,

     logand, logior, logxor, lognot, logtest, logcount, integer-length, logbit?, ash

 -- Function: bitwise-and n1 ...
 -- Function: bitwise-ior n1 ...
 -- Function: bitwise-xor n1 ...
 -- Function: bitwise-not n
 -- Function: any-bits-set? j k
 -- Function: bit-set? index n
 -- Function: arithmetic-shift n count
 -- Function: bit-field n start end
 -- Function: bit-count n
     Aliases for logand, logior, logxor, lognot, logtest, logbit?, ash, bit-extract and logcount respectively.

     Note that the name bit-count conflicts with bit-count in the core (see Bit Vectors).

 -- Function: bitwise-if mask n1 n0
 -- Function: bitwise-merge mask n1 n0
     Return an integer with bits selected from N1 and N0 according to MASK.  Those bits where MASK has 1s are taken from N1, and those where MASK has 0s are taken from N0.

          (bitwise-if 3 #b0101 #b1010) => 9

 -- Function: log2-binary-factors n
 -- Function: first-set-bit n
     Return a count of how many factors of 2 are present in N.  This is also the bit index of the lowest 1 bit in N.  If N is 0, the return is -1.

          (log2-binary-factors 6) => 1
          (log2-binary-factors -8) => 3

 -- Function: copy-bit index n newbit
     Return N with the bit at INDEX set according to NEWBIT.  NEWBIT should be #t to set the bit to 1, or #f to set it to 0.  Bits other than at INDEX are unchanged in the return.

          (copy-bit 1 #b0101 #t) => 7

 -- Function: copy-bit-field n newbits start end
     Return N with the bits from START (inclusive) to END (exclusive) changed to the value NEWBITS.

     The least significant bit in NEWBITS goes to START, the next to START+1, etc.  Anything in NEWBITS past the END given is ignored.

          (copy-bit-field #b10000 #b11 1 3) => #b10110

 -- Function: rotate-bit-field n count start end
     Return N with the bit field from START (inclusive) to END (exclusive) rotated upwards by COUNT bits.

     COUNT can be positive or negative, and it can be more than the field width (it'll be reduced modulo the width).

          (rotate-bit-field #b0110 2 1 4) => #b1010

 -- Function: reverse-bit-field n start end
     Return N with the bits from START (inclusive) to END (exclusive) reversed.

          (reverse-bit-field #b101001 2 4) => #b100101

 -- Function: integer->list n [len]
     Return bits from N in the form of a list of #t for 1 and #f for 0.  The least significant LEN bits are returned, and the first list element is the most significant of those bits.  If LEN is not given, the default is (integer-length N) (see Bitwise Operations).

          (integer->list 6)   => (#t #t #f)
          (integer->list 1 4) => (#f #f #f #t)

 -- Function: list->integer lst
 -- Function: booleans->integer bool...
     Return an integer formed bitwise from the given LST list of booleans, or for booleans->integer from the BOOL arguments.

     Each boolean is #t for a 1 and #f for a 0.  The first element becomes the most significant bit in the return.

          (list->integer '(#t #f #t #f)) => 10