1This is guile.info, produced by makeinfo version 6.7 from guile.texi.
2
3This manual documents Guile version 3.0.7.
4
5   Copyright (C) 1996-1997, 2000-2005, 2009-2021 Free Software
6Foundation, Inc.
7
8   Permission is granted to copy, distribute and/or modify this document
9under the terms of the GNU Free Documentation License, Version 1.3 or
10any later version published by the Free Software Foundation; with no
11Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
12copy of the license is included in the section entitled “GNU Free
13Documentation License.”
14INFO-DIR-SECTION The Algorithmic Language Scheme
15START-INFO-DIR-ENTRY
16* Guile Reference: (guile).     The Guile reference manual.
17END-INFO-DIR-ENTRY
18
19
20File: guile.info,  Node: URIs,  Next: HTTP,  Prev: Types and the Web,  Up: Web
21
227.3.2 Universal Resource Identifiers
23------------------------------------
24
25Guile provides a standard data type for Universal Resource Identifiers
26(URIs), as defined in RFC 3986.
27
28   The generic URI syntax is as follows:
29
30     URI-reference := [scheme ":"] ["//" [userinfo "@"] host [":" port]] path \
31                      [ "?" query ] [ "#" fragment ]
32
33   For example, in the URI, ‘http://www.gnu.org/help/’, the scheme is
34‘http’, the host is ‘www.gnu.org’, the path is ‘/help/’, and there is no
35userinfo, port, query, or fragment.
36
37   Userinfo is something of an abstraction, as some legacy URI schemes
38allowed userinfo of the form ‘USERNAME:PASSWD’.  But since passwords do
39not belong in URIs, the RFC does not want to condone this practice, so
40it calls anything before the ‘@’ sign “userinfo”.
41
42     (use-modules (web uri))
43
44   The following procedures can be found in the ‘(web uri)’ module.
45Load it into your Guile, using a form like the above, to have access to
46them.
47
48   The most common way to build a URI from Scheme is with the
49‘build-uri’ function.
50
51 -- Scheme Procedure: build-uri scheme [#:userinfo=‘#f’] [#:host=‘#f’]
52          [#:port=‘#f’] [#:path=‘""’] [#:query=‘#f’] [#:fragment=‘#f’]
53          [#:validate?=‘#t’]
54     Construct a URI. SCHEME should be a symbol, PORT either a positive,
55     exact integer or ‘#f’, and the rest of the fields are either
56     strings or ‘#f’.  If VALIDATE? is true, also run some consistency
57     checks to make sure that the constructed URI is valid.
58 -- Scheme Procedure: uri? obj
59     Return ‘#t’ if OBJ is a URI.
60
61   Guile, URIs are represented as URI records, with a number of
62associated accessors.
63
64 -- Scheme Procedure: uri-scheme uri
65 -- Scheme Procedure: uri-userinfo uri
66 -- Scheme Procedure: uri-host uri
67 -- Scheme Procedure: uri-port uri
68 -- Scheme Procedure: uri-path uri
69 -- Scheme Procedure: uri-query uri
70 -- Scheme Procedure: uri-fragment uri
71     Field accessors for the URI record type.  The URI scheme will be a
72     symbol, or ‘#f’ if the object is a relative-ref (see below).  The
73     port will be either a positive, exact integer or ‘#f’, and the rest
74     of the fields will be either strings or ‘#f’ if not present.
75
76 -- Scheme Procedure: string->uri string
77     Parse STRING into a URI object.  Return ‘#f’ if the string could
78     not be parsed.
79
80 -- Scheme Procedure: uri->string uri [#:include-fragment?=‘#t’]
81     Serialize URI to a string.  If the URI has a port that is the
82     default port for its scheme, the port is not included in the
83     serialization.  If INCLUDE-FRAGMENT? is given as false, the
84     resulting string will omit the fragment (if any).
85
86 -- Scheme Procedure: declare-default-port! scheme port
87     Declare a default port for the given URI scheme.
88
89 -- Scheme Procedure: uri-decode str [#:encoding=‘"utf-8"’]
90          [#:decode-plus-to-space? #t]
91     Percent-decode the given STR, according to ENCODING, which should
92     be the name of a character encoding.
93
94     Note that this function should not generally be applied to a full
95     URI string.  For paths, use ‘split-and-decode-uri-path’ instead.
96     For query strings, split the query on ‘&’ and ‘=’ boundaries, and
97     decode the components separately.
98
99     Note also that percent-encoded strings encode _bytes_, not
100     characters.  There is no guarantee that a given byte sequence is a
101     valid string encoding.  Therefore this routine may signal an error
102     if the decoded bytes are not valid for the given encoding.  Pass
103     ‘#f’ for ENCODING if you want decoded bytes as a bytevector
104     directly.  *Note ‘set-port-encoding!’: Ports, for more information
105     on character encodings.
106
107     If DECODE-PLUS-TO-SPACE? is true, which is the default, also
108     replace instances of the plus character ‘+’ with a space character.
109     This is needed when parsing ‘application/x-www-form-urlencoded110     data.
111
112     Returns a string of the decoded characters, or a bytevector if
113     ENCODING was ‘#f’.
114
115 -- Scheme Procedure: uri-encode str [#:encoding=‘"utf-8"’]
116          [#:unescaped-chars]
117     Percent-encode any character not in the character set,
118     UNESCAPED-CHARS.
119
120     The default character set includes alphanumerics from ASCII, as
121     well as the special characters ‘-’, ‘.’, ‘_’, and ‘~’.  Any other
122     character will be percent-encoded, by writing out the character to
123     a bytevector within the given ENCODING, then encoding each byte as
124     ‘%HH’, where HH is the hexadecimal representation of the byte.
125
126 -- Scheme Procedure: split-and-decode-uri-path path
127     Split PATH into its components, and decode each component, removing
128     empty components.
129
130     For example, ‘"/foo/bar%20baz/"’ decodes to the two-element list,
131     ‘("foo" "bar baz")’.
132
133 -- Scheme Procedure: encode-and-join-uri-path parts
134     URI-encode each element of PARTS, which should be a list of
135     strings, and join the parts together with ‘/’ as a delimiter.
136
137     For example, the list ‘("scrambled eggs" "biscuits&gravy")’ encodes
138     as ‘"scrambled%20eggs/biscuits%26gravy"’.
139
140Subtypes of URI
141...............
142
143As we noted above, not all URI objects have a scheme.  You might have
144noted in the “generic URI syntax” example that the left-hand side of
145that grammar definition was URI-reference, not URI. A “URI-reference” is
146a generalization of a URI where the scheme is optional.  If no scheme is
147specified, it is taken to be relative to some other related URI. A
148common use of URI references is when you want to be vague regarding the
149choice of HTTP or HTTPS – serving a web page referring to ‘/foo.css150will use HTTPS if loaded over HTTPS, or HTTP otherwise.
151
152 -- Scheme Procedure: build-uri-reference [#:scheme=‘#f’]
153          [#:userinfo=‘#f’] [#:host=‘#f’] [#:port=‘#f’] [#:path=‘""’]
154          [#:query=‘#f’] [#:fragment=‘#f’] [#:validate?=‘#t’]
155     Like ‘build-uri’, but with an optional scheme.
156 -- Scheme Procedure: uri-reference? obj
157     Return ‘#t’ if OBJ is a URI-reference.  This is the most general
158     URI predicate, as it includes not only full URIs that have schemes
159     (those that match ‘uri?’) but also URIs without schemes.
160
161   It’s also possible to build a “relative-ref”: a URI-reference that
162explicitly lacks a scheme.
163
164 -- Scheme Procedure: build-relative-ref [#:userinfo=‘#f’] [#:host=‘#f’]
165          [#:port=‘#f’] [#:path=‘""’] [#:query=‘#f’] [#:fragment=‘#f’]
166          [#:validate?=‘#t’]
167     Like ‘build-uri’, but with no scheme.
168 -- Scheme Procedure: relative-ref? obj
169     Return ‘#t’ if OBJ is a “relative-ref”: a URI-reference that has no
170     scheme.  Every URI-reference will either match ‘uri?’ or
171     ‘relative-ref?’ (but not both).
172
173   In case it’s not clear from the above, the most general of these URI
174types is the URI-reference, with ‘build-uri-reference’ as the most
175general constructor.  ‘build-uri’ and ‘build-relative-ref’ enforce
176enforce specific restrictions on the URI-reference.  The most generic
177URI parser is then ‘string->uri-reference’, and there is also a parser
178for when you know that you want a relative-ref.
179
180   Note that ‘uri?’ will only return ‘#t’ for URI objects that have
181schemes; that is, it rejects relative-refs.
182
183 -- Scheme Procedure: string->uri-reference string
184     Parse STRING into a URI object, while not requiring a scheme.
185     Return ‘#f’ if the string could not be parsed.
186
187 -- Scheme Procedure: string->relative-ref string
188     Parse STRING into a URI object, while asserting that no scheme is
189     present.  Return ‘#f’ if the string could not be parsed.
190
191
192File: guile.info,  Node: HTTP,  Next: HTTP Headers,  Prev: URIs,  Up: Web
193
1947.3.3 The Hyper-Text Transfer Protocol
195--------------------------------------
196
197The initial motivation for including web functionality in Guile, rather
198than rely on an external package, was to establish a standard base on
199which people can share code.  To that end, we continue the focus on data
200types by providing a number of low-level parsers and unparsers for
201elements of the HTTP protocol.
202
203   If you are want to skip the low-level details for now and move on to
204web pages, *note Web Client::, and *note Web Server::.  Otherwise, load
205the HTTP module, and read on.
206
207     (use-modules (web http))
208
209   The focus of the ‘(web http)’ module is to parse and unparse standard
210HTTP headers, representing them to Guile as native data structures.  For
211example, a ‘Date:’ header will be represented as a SRFI-19 date record
212(*note SRFI-19::), rather than as a string.
213
214   Guile tries to follow RFCs fairly strictly—the road to perdition
215being paved with compatibility hacks—though some allowances are made for
216not-too-divergent texts.
217
218   Header names are represented as lower-case symbols.
219
220 -- Scheme Procedure: string->header name
221     Parse NAME to a symbolic header name.
222
223 -- Scheme Procedure: header->string sym
224     Return the string form for the header named SYM.
225
226   For example:
227
228     (string->header "Content-Length")
229     ⇒ content-length
230     (header->string 'content-length)
231     ⇒ "Content-Length"
232
233     (string->header "FOO")
234     ⇒ foo
235     (header->string 'foo)
236     ⇒ "Foo"
237
238   Guile keeps a registry of known headers, their string names, and some
239parsing and serialization procedures.  If a header is unknown, its
240string name is simply its symbol name in title-case.
241
242 -- Scheme Procedure: known-header? sym
243     Return ‘#t’ if SYM is a known header, with associated parsers and
244     serialization procedures, or ‘#f’ otherwise.
245
246 -- Scheme Procedure: header-parser sym
247     Return the value parser for headers named SYM.  The result is a
248     procedure that takes one argument, a string, and returns the parsed
249     value.  If the header isn’t known to Guile, a default parser is
250     returned that passes through the string unchanged.
251
252 -- Scheme Procedure: header-validator sym
253     Return a predicate which returns ‘#t’ if the given value is valid
254     for headers named SYM.  The default validator for unknown headers
255     is ‘string?’.
256
257 -- Scheme Procedure: header-writer sym
258     Return a procedure that writes values for headers named SYM to a
259     port.  The resulting procedure takes two arguments: a value and a
260     port.  The default writer is ‘display’.
261
262   For more on the set of headers that Guile knows about out of the box,
263*note HTTP Headers::.  To add your own, use the ‘declare-header!’
264procedure:
265
266 -- Scheme Procedure: declare-header! name parser validator writer
267          [#:multiple?=‘#f’]
268     Declare a parser, validator, and writer for a given header.
269
270   For example, let’s say you are running a web server behind some sort
271of proxy, and your proxy adds an ‘X-Client-Address’ header, indicating
272the IPv4 address of the original client.  You would like for the HTTP
273request record to parse out this header to a Scheme value, instead of
274leaving it as a string.  You could register this header with Guile’s
275HTTP stack like this:
276
277     (declare-header! "X-Client-Address"
278       (lambda (str)
279         (inet-pton AF_INET str))
280       (lambda (ip)
281         (and (integer? ip) (exact? ip) (<= 0 ip #xffffffff)))
282       (lambda (ip port)
283         (display (inet-ntop AF_INET ip) port)))
284
285 -- Scheme Procedure: declare-opaque-header! name
286     A specialised version of ‘declare-header!’ for the case in which
287     you want a header’s value to be returned/written “as-is”.
288
289 -- Scheme Procedure: valid-header? sym val
290     Return a true value if VAL is a valid Scheme value for the header
291     with name SYM, or ‘#f’ otherwise.
292
293   Now that we have a generic interface for reading and writing headers,
294we do just that.
295
296 -- Scheme Procedure: read-header port
297     Read one HTTP header from PORT.  Return two values: the header name
298     and the parsed Scheme value.  May raise an exception if the header
299     was known but the value was invalid.
300
301     Returns the end-of-file object for both values if the end of the
302     message body was reached (i.e., a blank line).
303
304 -- Scheme Procedure: parse-header name val
305     Parse VAL, a string, with the parser for the header named NAME.
306     Returns the parsed value.
307
308 -- Scheme Procedure: write-header name val port
309     Write the given header name and value to PORT, using the writer
310     from ‘header-writer’.
311
312 -- Scheme Procedure: read-headers port
313     Read the headers of an HTTP message from PORT, returning them as an
314     ordered alist.
315
316 -- Scheme Procedure: write-headers headers port
317     Write the given header alist to PORT.  Doesn’t write the final
318     ‘\r\n’, as the user might want to add another header.
319
320   The ‘(web http)’ module also has some utility procedures to read and
321write request and response lines.
322
323 -- Scheme Procedure: parse-http-method str [start] [end]
324     Parse an HTTP method from STR.  The result is an upper-case symbol,
325     like ‘GET’.
326
327 -- Scheme Procedure: parse-http-version str [start] [end]
328     Parse an HTTP version from STR, returning it as a major–minor pair.
329     For example, ‘HTTP/1.1’ parses as the pair of integers, ‘(1 . 1)’.
330
331 -- Scheme Procedure: parse-request-uri str [start] [end]
332     Parse a URI from an HTTP request line.  Note that URIs in requests
333     do not have to have a scheme or host name.  The result is a URI
334     object.
335
336 -- Scheme Procedure: read-request-line port
337     Read the first line of an HTTP request from PORT, returning three
338     values: the method, the URI, and the version.
339
340 -- Scheme Procedure: write-request-line method uri version port
341     Write the first line of an HTTP request to PORT.
342
343 -- Scheme Procedure: read-response-line port
344     Read the first line of an HTTP response from PORT, returning three
345     values: the HTTP version, the response code, and the “reason
346     phrase”.
347
348 -- Scheme Procedure: write-response-line version code reason-phrase
349          port
350     Write the first line of an HTTP response to PORT.
351
352
353File: guile.info,  Node: HTTP Headers,  Next: Transfer Codings,  Prev: HTTP,  Up: Web
354
3557.3.4 HTTP Headers
356------------------
357
358In addition to defining the infrastructure to parse headers, the ‘(web
359http)’ module defines specific parsers and unparsers for all headers
360defined in the HTTP/1.1 standard.
361
362   For example, if you receive a header named ‘Accept-Language’ with a
363value ‘en, es;q=0.8’, Guile parses it as a quality list (defined below):
364
365     (parse-header 'accept-language "en, es;q=0.8")
366     ⇒ ((1000 . "en") (800 . "es"))
367
368   The format of the value for ‘Accept-Language’ headers is defined
369below, along with all other headers defined in the HTTP standard.  (If
370the header were unknown, the value would have been returned as a
371string.)
372
373   For brevity, the header definitions below are given in the form, TYPE
374‘NAME’, indicating that values for the header ‘NAME’ will be of the
375given TYPE.  Since Guile internally treats header names in lower case,
376in this document we give types title-cased names.  A short description
377of the each header’s purpose and an example follow.
378
379   For full details on the meanings of all of these headers, see the
380HTTP 1.1 standard, RFC 2616.
381
3827.3.4.1 HTTP Header Types
383.........................
384
385Here we define the types that are used below, when defining headers.
386
387 -- HTTP Header Type: Date
388     A SRFI-19 date.
389
390 -- HTTP Header Type: KVList
391     A list whose elements are keys or key-value pairs.  Keys are parsed
392     to symbols.  Values are strings by default.  Non-string values are
393     the exception, and are mentioned explicitly below, as appropriate.
394
395 -- HTTP Header Type: SList
396     A list of strings.
397
398 -- HTTP Header Type: Quality
399     An exact integer between 0 and 1000.  Qualities are used to express
400     preference, given multiple options.  An option with a quality of
401     870, for example, is preferred over an option with quality 500.
402
403     (Qualities are written out over the wire as numbers between 0.0 and
404     1.0, but since the standard only allows three digits after the
405     decimal, it’s equivalent to integers between 0 and 1000, so that’s
406     what Guile uses.)
407
408 -- HTTP Header Type: QList
409     A quality list: a list of pairs, the car of which is a quality, and
410     the cdr a string.  Used to express a list of options, along with
411     their qualities.
412
413 -- HTTP Header Type: ETag
414     An entity tag, represented as a pair.  The car of the pair is an
415     opaque string, and the cdr is ‘#t’ if the entity tag is a “strong”
416     entity tag, and ‘#f’ otherwise.
417
4187.3.4.2 General Headers
419.......................
420
421General HTTP headers may be present in any HTTP message.
422
423 -- HTTP Header: KVList cache-control
424     A key-value list of cache-control directives.  See RFC 2616, for
425     more details.
426
427     If present, parameters to ‘max-age’, ‘max-stale’, ‘min-fresh’, and
428     ‘s-maxage’ are all parsed as non-negative integers.
429
430     If present, parameters to ‘private’ and ‘no-cache’ are parsed as
431     lists of header names, as symbols.
432
433          (parse-header 'cache-control "no-cache,no-store"
434          ⇒ (no-cache no-store)
435          (parse-header 'cache-control "no-cache=\"Authorization,Date\",no-store"
436          ⇒ ((no-cache . (authorization date)) no-store)
437          (parse-header 'cache-control "no-cache=\"Authorization,Date\",max-age=10"
438          ⇒ ((no-cache . (authorization date)) (max-age . 10))
439
440 -- HTTP Header: List connection
441     A list of header names that apply only to this HTTP connection, as
442     symbols.  Additionally, the symbol ‘close’ may be present, to
443     indicate that the server should close the connection after
444     responding to the request.
445          (parse-header 'connection "close")
446          ⇒ (close)
447
448 -- HTTP Header: Date date
449     The date that a given HTTP message was originated.
450          (parse-header 'date "Tue, 15 Nov 1994 08:12:31 GMT")
451          ⇒ #<date ...>
452
453 -- HTTP Header: KVList pragma
454     A key-value list of implementation-specific directives.
455          (parse-header 'pragma "no-cache, broccoli=tasty")
456          ⇒ (no-cache (broccoli . "tasty"))
457
458 -- HTTP Header: List trailer
459     A list of header names which will appear after the message body,
460     instead of with the message headers.
461          (parse-header 'trailer "ETag")
462          ⇒ (etag)
463
464 -- HTTP Header: List transfer-encoding
465     A list of transfer codings, expressed as key-value lists.  The only
466     transfer coding defined by the specification is ‘chunked’.
467          (parse-header 'transfer-encoding "chunked")
468          ⇒ ((chunked))
469
470 -- HTTP Header: List upgrade
471     A list of strings, indicating additional protocols that a server
472     could use in response to a request.
473          (parse-header 'upgrade "WebSocket")
474          ⇒ ("WebSocket")
475
476   FIXME: parse out more fully?
477 -- HTTP Header: List via
478     A list of strings, indicating the protocol versions and hosts of
479     intermediate servers and proxies.  There may be multiple ‘via’
480     headers in one message.
481          (parse-header 'via "1.0 venus, 1.1 mars")
482          ⇒ ("1.0 venus" "1.1 mars")
483
484 -- HTTP Header: List warning
485     A list of warnings given by a server or intermediate proxy.  Each
486     warning is a itself a list of four elements: a code, as an exact
487     integer between 0 and 1000, a host as a string, the warning text as
488     a string, and either ‘#f’ or a SRFI-19 date.
489
490     There may be multiple ‘warning’ headers in one message.
491          (parse-header 'warning "123 foo \"core breach imminent\"")
492          ⇒ ((123 "foo" "core-breach imminent" #f))
493
4947.3.4.3 Entity Headers
495......................
496
497Entity headers may be present in any HTTP message, and refer to the
498resource referenced in the HTTP request or response.
499
500 -- HTTP Header: List allow
501     A list of allowed methods on a given resource, as symbols.
502          (parse-header 'allow "GET, HEAD")
503          ⇒ (GET HEAD)
504
505 -- HTTP Header: List content-encoding
506     A list of content codings, as symbols.
507          (parse-header 'content-encoding "gzip")
508          ⇒ (gzip)
509
510 -- HTTP Header: List content-language
511     The languages that a resource is in, as strings.
512          (parse-header 'content-language "en")
513          ⇒ ("en")
514
515 -- HTTP Header: UInt content-length
516     The number of bytes in a resource, as an exact, non-negative
517     integer.
518          (parse-header 'content-length "300")
519          ⇒ 300
520
521 -- HTTP Header: URI content-location
522     The canonical URI for a resource, in the case that it is also
523     accessible from a different URI.
524          (parse-header 'content-location "http://example.com/foo")
525          ⇒ #<<uri> ...>
526
527 -- HTTP Header: String content-md5
528     The MD5 digest of a resource.
529          (parse-header 'content-md5 "ffaea1a79810785575e29e2bd45e2fa5")
530          ⇒ "ffaea1a79810785575e29e2bd45e2fa5"
531
532 -- HTTP Header: List content-range
533     Range specification as a list of three elements: the symbol
534     ‘bytes’, either the symbol ‘*’ or a pair of integers indicating the
535     byte range, and either ‘*’ or an integer indicating the instance
536     length.  Used to indicate that a response only includes part of a
537     resource.
538          (parse-header 'content-range "bytes 10-20/*")
539          ⇒ (bytes (10 . 20) *)
540
541 -- HTTP Header: List content-type
542     The MIME type of a resource, as a symbol, along with any
543     parameters.
544          (parse-header 'content-type "text/plain")
545          ⇒ (text/plain)
546          (parse-header 'content-type "text/plain;charset=utf-8")
547          ⇒ (text/plain (charset . "utf-8"))
548     Note that the ‘charset’ parameter is something of a misnomer, and
549     the HTTP specification admits this.  It specifies the _encoding_ of
550     the characters, not the character set.
551
552 -- HTTP Header: Date expires
553     The date/time after which the resource given in a response is
554     considered stale.
555          (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
556          ⇒ #<date ...>
557
558 -- HTTP Header: Date last-modified
559     The date/time on which the resource given in a response was last
560     modified.
561          (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
562          ⇒ #<date ...>
563
5647.3.4.4 Request Headers
565.......................
566
567Request headers may only appear in an HTTP request, not in a response.
568
569 -- HTTP Header: List accept
570     A list of preferred media types for a response.  Each element of
571     the list is itself a list, in the same format as ‘content-type’.
572          (parse-header 'accept "text/html,text/plain;charset=utf-8")
573          ⇒ ((text/html) (text/plain (charset . "utf-8")))
574     Preference is expressed with quality values:
575          (parse-header 'accept "text/html;q=0.8,text/plain;q=0.6")
576          ⇒ ((text/html (q . 800)) (text/plain (q . 600)))
577
578 -- HTTP Header: QList accept-charset
579     A quality list of acceptable charsets.  Note again that what HTTP
580     calls a “charset” is what Guile calls a “character encoding”.
581          (parse-header 'accept-charset "iso-8859-5, unicode-1-1;q=0.8")
582          ⇒ ((1000 . "iso-8859-5") (800 . "unicode-1-1"))
583
584 -- HTTP Header: QList accept-encoding
585     A quality list of acceptable content codings.
586          (parse-header 'accept-encoding "gzip,identity=0.8")
587          ⇒ ((1000 . "gzip") (800 . "identity"))
588
589 -- HTTP Header: QList accept-language
590     A quality list of acceptable languages.
591          (parse-header 'accept-language "cn,en=0.75")
592          ⇒ ((1000 . "cn") (750 . "en"))
593
594 -- HTTP Header: Pair authorization
595     Authorization credentials.  The car of the pair indicates the
596     authentication scheme, like ‘basic’.  For basic authentication, the
597     cdr of the pair will be the base64-encoded ‘USER:PASS’ string.  For
598     other authentication schemes, like ‘digest’, the cdr will be a
599     key-value list of credentials.
600          (parse-header 'authorization "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
601          ⇒ (basic . "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
602
603 -- HTTP Header: List expect
604     A list of expectations that a client has of a server.  The
605     expectations are key-value lists.
606          (parse-header 'expect "100-continue")
607          ⇒ ((100-continue))
608
609 -- HTTP Header: String from
610     The email address of a user making an HTTP request.
611          (parse-header 'from "bob@example.com")
612          ⇒ "bob@example.com"
613
614 -- HTTP Header: Pair host
615     The host for the resource being requested, as a hostname-port pair.
616     If no port is given, the port is ‘#f’.
617          (parse-header 'host "gnu.org:80")
618          ⇒ ("gnu.org" . 80)
619          (parse-header 'host "gnu.org")
620          ⇒ ("gnu.org" . #f)
621
622 -- HTTP Header: *|List if-match
623     A set of etags, indicating that the request should proceed if and
624     only if the etag of the resource is in that set.  Either the symbol
625     ‘*’, indicating any etag, or a list of entity tags.
626          (parse-header 'if-match "*")
627          ⇒ *
628          (parse-header 'if-match "asdfadf")
629          ⇒ (("asdfadf" . #t))
630          (parse-header 'if-match W/"asdfadf")
631          ⇒ (("asdfadf" . #f))
632
633 -- HTTP Header: Date if-modified-since
634     Indicates that a response should proceed if and only if the
635     resource has been modified since the given date.
636          (parse-header 'if-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
637          ⇒ #<date ...>
638
639 -- HTTP Header: *|List if-none-match
640     A set of etags, indicating that the request should proceed if and
641     only if the etag of the resource is not in the set.  Either the
642     symbol ‘*’, indicating any etag, or a list of entity tags.
643          (parse-header 'if-none-match "*")
644          ⇒ *
645
646 -- HTTP Header: ETag|Date if-range
647     Indicates that the range request should proceed if and only if the
648     resource matches a modification date or an etag.  Either an entity
649     tag, or a SRFI-19 date.
650          (parse-header 'if-range "\"original-etag\"")
651          ⇒ ("original-etag" . #t)
652
653 -- HTTP Header: Date if-unmodified-since
654     Indicates that a response should proceed if and only if the
655     resource has not been modified since the given date.
656          (parse-header 'if-not-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
657          ⇒ #<date ...>
658
659 -- HTTP Header: UInt max-forwards
660     The maximum number of proxy or gateway hops that a request should
661     be subject to.
662          (parse-header 'max-forwards "10")
663          ⇒ 10
664
665 -- HTTP Header: Pair proxy-authorization
666     Authorization credentials for a proxy connection.  See the
667     documentation for ‘authorization’ above for more information on the
668     format.
669          (parse-header 'proxy-authorization "Digest foo=bar,baz=qux"
670          ⇒ (digest (foo . "bar") (baz . "qux"))
671
672 -- HTTP Header: Pair range
673     A range request, indicating that the client wants only part of a
674     resource.  The car of the pair is the symbol ‘bytes’, and the cdr
675     is a list of pairs.  Each element of the cdr indicates a range; the
676     car is the first byte position and the cdr is the last byte
677     position, as integers, or ‘#f’ if not given.
678          (parse-header 'range "bytes=10-30,50-")
679          ⇒ (bytes (10 . 30) (50 . #f))
680
681 -- HTTP Header: URI referer
682     The URI of the resource that referred the user to this resource.
683     The name of the header is a misspelling, but we are stuck with it.
684          (parse-header 'referer "http://www.gnu.org/")
685          ⇒ #<uri ...>
686
687 -- HTTP Header: List te
688     A list of transfer codings, expressed as key-value lists.  A common
689     transfer coding is ‘trailers’.
690          (parse-header 'te "trailers")
691          ⇒ ((trailers))
692
693 -- HTTP Header: String user-agent
694     A string indicating the user agent making the request.  The
695     specification defines a structured format for this header, but it
696     is widely disregarded, so Guile does not attempt to parse strictly.
697          (parse-header 'user-agent "Mozilla/5.0")
698          ⇒ "Mozilla/5.0"
699
7007.3.4.5 Response Headers
701........................
702
703 -- HTTP Header: List accept-ranges
704     A list of range units that the server supports, as symbols.
705          (parse-header 'accept-ranges "bytes")
706          ⇒ (bytes)
707
708 -- HTTP Header: UInt age
709     The age of a cached response, in seconds.
710          (parse-header 'age "3600")
711          ⇒ 3600
712
713 -- HTTP Header: ETag etag
714     The entity-tag of the resource.
715          (parse-header 'etag "\"foo\"")
716          ⇒ ("foo" . #t)
717
718 -- HTTP Header: URI-reference location
719     A URI reference on which a request may be completed.  Used in
720     combination with a redirecting status code to perform client-side
721     redirection.
722          (parse-header 'location "http://example.com/other")
723          ⇒ #<uri ...>
724
725 -- HTTP Header: List proxy-authenticate
726     A list of challenges to a proxy, indicating the need for
727     authentication.
728          (parse-header 'proxy-authenticate "Basic realm=\"foo\"")
729          ⇒ ((basic (realm . "foo")))
730
731 -- HTTP Header: UInt|Date retry-after
732     Used in combination with a server-busy status code, like 503, to
733     indicate that a client should retry later.  Either a number of
734     seconds, or a date.
735          (parse-header 'retry-after "60")
736          ⇒ 60
737
738 -- HTTP Header: String server
739     A string identifying the server.
740          (parse-header 'server "My first web server")
741          ⇒ "My first web server"
742
743 -- HTTP Header: *|List vary
744     A set of request headers that were used in computing this response.
745     Used to indicate that server-side content negotiation was
746     performed, for example in response to the ‘accept-language’ header.
747     Can also be the symbol ‘*’, indicating that all headers were
748     considered.
749          (parse-header 'vary "Accept-Language, Accept")
750          ⇒ (accept-language accept)
751
752 -- HTTP Header: List www-authenticate
753     A list of challenges to a user, indicating the need for
754     authentication.
755          (parse-header 'www-authenticate "Basic realm=\"foo\"")
756          ⇒ ((basic (realm . "foo")))
757
758
759File: guile.info,  Node: Transfer Codings,  Next: Requests,  Prev: HTTP Headers,  Up: Web
760
7617.3.5 Transfer Codings
762----------------------
763
764HTTP 1.1 allows for various transfer codings to be applied to message
765bodies.  These include various types of compression, and HTTP chunked
766encoding.  Currently, only chunked encoding is supported by guile.
767
768   Chunked coding is an optional coding that may be applied to message
769bodies, to allow messages whose length is not known beforehand to be
770returned.  Such messages can be split into chunks, terminated by a final
771zero length chunk.
772
773   In order to make dealing with encodings more simple, guile provides
774procedures to create ports that “wrap” existing ports, applying
775transformations transparently under the hood.
776
777   These procedures are in the ‘(web http)’ module.
778
779     (use-modules (web http))
780
781 -- Scheme Procedure: make-chunked-input-port port [#:keep-alive?=#f]
782     Returns a new port, that transparently reads and decodes
783     chunk-encoded data from PORT.  If no more chunk-encoded data is
784     available, it returns the end-of-file object.  When the port is
785     closed, PORT will also be closed, unless KEEP-ALIVE? is true.
786
787     (use-modules (ice-9 rdelim))
788
789     (define s "5\r\nFirst\r\nA\r\n line\n Sec\r\n8\r\nond line\r\n0\r\n")
790     (define p (make-chunked-input-port (open-input-string s)))
791     (read-line s)
792     ⇒ "First line"
793     (read-line s)
794     ⇒ "Second line"
795
796 -- Scheme Procedure: make-chunked-output-port port [#:keep-alive?=#f]
797     Returns a new port, which transparently encodes data as
798     chunk-encoded before writing it to PORT.  Whenever a write occurs
799     on this port, it buffers it, until the port is flushed, at which
800     point it writes a chunk containing all the data written so far.
801     When the port is closed, the data remaining is written to PORT, as
802     is the terminating zero chunk.  It also causes PORT to be closed,
803     unless KEEP-ALIVE? is true.
804
805     Note.  Forcing a chunked output port when there is no data is
806     buffered does not write a zero chunk, as this would cause the data
807     to be interpreted incorrectly by the client.
808
809     (call-with-output-string
810       (lambda (out)
811         (define out* (make-chunked-output-port out #:keep-alive? #t))
812         (display "first chunk" out*)
813         (force-output out*)
814         (force-output out*) ; note this does not write a zero chunk
815         (display "second chunk" out*)
816         (close-port out*)))
817     ⇒ "b\r\nfirst chunk\r\nc\r\nsecond chunk\r\n0\r\n"
818
819
820File: guile.info,  Node: Requests,  Next: Responses,  Prev: Transfer Codings,  Up: Web
821
8227.3.6 HTTP Requests
823-------------------
824
825     (use-modules (web request))
826
827   The request module contains a data type for HTTP requests.
828
8297.3.6.1 An Important Note on Character Sets
830...........................................
831
832HTTP requests consist of two parts: the request proper, consisting of a
833request line and a set of headers, and (optionally) a body.  The body
834might have a binary content-type, and even in the textual case its
835length is specified in bytes, not characters.
836
837   Therefore, HTTP is a fundamentally binary protocol.  However the
838request line and headers are specified to be in a subset of ASCII, so
839they can be treated as text, provided that the port’s encoding is set to
840an ASCII-compatible one-byte-per-character encoding.  ISO-8859-1
841(latin-1) is just such an encoding, and happens to be very efficient for
842Guile.
843
844   So what Guile does when reading requests from the wire, or writing
845them out, is to set the port’s encoding to latin-1, and treating the
846request headers as text.
847
848   The request body is another issue.  For binary data, the data is
849probably in a bytevector, so we use the R6RS binary output procedures to
850write out the binary payload.  Textual data usually has to be written
851out to some character encoding, usually UTF-8, and then the resulting
852bytevector is written out to the port.
853
854   In summary, Guile reads and writes HTTP over latin-1 sockets, without
855any loss of generality.
856
8577.3.6.2 Request API
858...................
859
860 -- Scheme Procedure: request? obj
861 -- Scheme Procedure: request-method request
862 -- Scheme Procedure: request-uri request
863 -- Scheme Procedure: request-version request
864 -- Scheme Procedure: request-headers request
865 -- Scheme Procedure: request-meta request
866 -- Scheme Procedure: request-port request
867     A predicate and field accessors for the request type.  The fields
868     are as follows:
869     ‘method’
870          The HTTP method, for example, ‘GET’.
871     ‘uri’
872          The URI as a URI record.
873     ‘version’
874          The HTTP version pair, like ‘(1 . 1)’.
875     ‘headers’
876          The request headers, as an alist of parsed values.
877     ‘meta’
878          An arbitrary alist of other data, for example information
879          returned in the ‘sockaddr’ from ‘accept’ (*note Network
880          Sockets and Communication::).
881     ‘port’
882          The port on which to read or write a request body, if any.
883
884 -- Scheme Procedure: read-request port [meta='()]
885     Read an HTTP request from PORT, optionally attaching the given
886     metadata, META.
887
888     As a side effect, sets the encoding on PORT to ISO-8859-1
889     (latin-1), so that reading one character reads one byte.  See the
890     discussion of character sets above, for more information.
891
892     Note that the body is not part of the request.  Once you have read
893     a request, you may read the body separately, and likewise for
894     writing requests.
895
896 -- Scheme Procedure: build-request uri [#:method='GET] [#:version='(1 .
897          1)] [#:headers='()] [#:port=#f] [#:meta='()]
898          [#:validate-headers?=#t]
899     Construct an HTTP request object.  If VALIDATE-HEADERS? is true,
900     the headers are each run through their respective validators.
901
902 -- Scheme Procedure: write-request r port
903     Write the given HTTP request to PORT.
904
905     Return a new request, whose ‘request-port’ will continue writing on
906     PORT, perhaps using some transfer encoding.
907
908 -- Scheme Procedure: read-request-body r
909     Reads the request body from R, as a bytevector.  Return ‘#f’ if
910     there was no request body.
911
912 -- Scheme Procedure: write-request-body r bv
913     Write BV, a bytevector, to the port corresponding to the HTTP
914     request R.
915
916   The various headers that are typically associated with HTTP requests
917may be accessed with these dedicated accessors.  *Note HTTP Headers::,
918for more information on the format of parsed headers.
919
920 -- Scheme Procedure: request-accept request [default='()]
921 -- Scheme Procedure: request-accept-charset request [default='()]
922 -- Scheme Procedure: request-accept-encoding request [default='()]
923 -- Scheme Procedure: request-accept-language request [default='()]
924 -- Scheme Procedure: request-allow request [default='()]
925 -- Scheme Procedure: request-authorization request [default=#f]
926 -- Scheme Procedure: request-cache-control request [default='()]
927 -- Scheme Procedure: request-connection request [default='()]
928 -- Scheme Procedure: request-content-encoding request [default='()]
929 -- Scheme Procedure: request-content-language request [default='()]
930 -- Scheme Procedure: request-content-length request [default=#f]
931 -- Scheme Procedure: request-content-location request [default=#f]
932 -- Scheme Procedure: request-content-md5 request [default=#f]
933 -- Scheme Procedure: request-content-range request [default=#f]
934 -- Scheme Procedure: request-content-type request [default=#f]
935 -- Scheme Procedure: request-date request [default=#f]
936 -- Scheme Procedure: request-expect request [default='()]
937 -- Scheme Procedure: request-expires request [default=#f]
938 -- Scheme Procedure: request-from request [default=#f]
939 -- Scheme Procedure: request-host request [default=#f]
940 -- Scheme Procedure: request-if-match request [default=#f]
941 -- Scheme Procedure: request-if-modified-since request [default=#f]
942 -- Scheme Procedure: request-if-none-match request [default=#f]
943 -- Scheme Procedure: request-if-range request [default=#f]
944 -- Scheme Procedure: request-if-unmodified-since request [default=#f]
945 -- Scheme Procedure: request-last-modified request [default=#f]
946 -- Scheme Procedure: request-max-forwards request [default=#f]
947 -- Scheme Procedure: request-pragma request [default='()]
948 -- Scheme Procedure: request-proxy-authorization request [default=#f]
949 -- Scheme Procedure: request-range request [default=#f]
950 -- Scheme Procedure: request-referer request [default=#f]
951 -- Scheme Procedure: request-te request [default=#f]
952 -- Scheme Procedure: request-trailer request [default='()]
953 -- Scheme Procedure: request-transfer-encoding request [default='()]
954 -- Scheme Procedure: request-upgrade request [default='()]
955 -- Scheme Procedure: request-user-agent request [default=#f]
956 -- Scheme Procedure: request-via request [default='()]
957 -- Scheme Procedure: request-warning request [default='()]
958     Return the given request header, or DEFAULT if none was present.
959
960 -- Scheme Procedure: request-absolute-uri r [default-host=#f]
961          [default-port=#f] [default-scheme=#f]
962     A helper routine to determine the absolute URI of a request, using
963     the ‘host’ header and the default scheme, host and port.  If there
964     is no default scheme and the URI is not itself absolute, an error
965     is signalled.
966
967
968File: guile.info,  Node: Responses,  Next: Web Client,  Prev: Requests,  Up: Web
969
9707.3.7 HTTP Responses
971--------------------
972
973     (use-modules (web response))
974
975   As with requests (*note Requests::), Guile offers a data type for
976HTTP responses.  Again, the body is represented separately from the
977request.
978
979 -- Scheme Procedure: response? obj
980 -- Scheme Procedure: response-version response
981 -- Scheme Procedure: response-code response
982 -- Scheme Procedure: response-reason-phrase response
983 -- Scheme Procedure: response-headers response
984 -- Scheme Procedure: response-port response
985     A predicate and field accessors for the response type.  The fields
986     are as follows:
987     ‘version’
988          The HTTP version pair, like ‘(1 . 1)’.
989     ‘code’
990          The HTTP response code, like ‘200’.
991     ‘reason-phrase’
992          The reason phrase, or the standard reason phrase for the
993          response’s code.
994     ‘headers’
995          The response headers, as an alist of parsed values.
996     ‘port’
997          The port on which to read or write a response body, if any.
998
999 -- Scheme Procedure: read-response port
1000     Read an HTTP response from PORT.
1001
1002     As a side effect, sets the encoding on PORT to ISO-8859-1
1003     (latin-1), so that reading one character reads one byte.  See the
1004     discussion of character sets in *note Responses::, for more
1005     information.
1006
1007 -- Scheme Procedure: build-response [#:version='(1 . 1)] [#:code=200]
1008          [#:reason-phrase=#f] [#:headers='()] [#:port=#f]
1009          [#:validate-headers?=#t]
1010     Construct an HTTP response object.  If VALIDATE-HEADERS? is true,
1011     the headers are each run through their respective validators.
1012
1013 -- Scheme Procedure: adapt-response-version response version
1014     Adapt the given response to a different HTTP version.  Return a new
1015     HTTP response.
1016
1017     The idea is that many applications might just build a response for
1018     the default HTTP version, and this method could handle a number of
1019     programmatic transformations to respond to older HTTP versions (0.9
1020     and 1.0).  But currently this function is a bit heavy-handed, just
1021     updating the version field.
1022
1023 -- Scheme Procedure: write-response r port
1024     Write the given HTTP response to PORT.
1025
1026     Return a new response, whose ‘response-port’ will continue writing
1027     on PORT, perhaps using some transfer encoding.
1028
1029 -- Scheme Procedure: response-must-not-include-body? r
1030     Some responses, like those with status code 304, are specified as
1031     never having bodies.  This predicate returns ‘#t’ for those
1032     responses.
1033
1034     Note also, though, that responses to ‘HEAD’ requests must also not
1035     have a body.
1036
1037 -- Scheme Procedure: response-body-port r [#:decode?=#t]
1038          [#:keep-alive?=#t]
1039     Return an input port from which the body of R can be read.  The
1040     encoding of the returned port is set according to R’s
1041     ‘content-type’ header, when it’s textual, except if DECODE? is
1042     ‘#f’.  Return ‘#f’ when no body is available.
1043
1044     When KEEP-ALIVE? is ‘#f’, closing the returned port also closes R’s
1045     response port.
1046
1047 -- Scheme Procedure: read-response-body r
1048     Read the response body from R, as a bytevector.  Returns ‘#f’ if
1049     there was no response body.
1050
1051 -- Scheme Procedure: write-response-body r bv
1052     Write BV, a bytevector, to the port corresponding to the HTTP
1053     response R.
1054
1055   As with requests, the various headers that are typically associated
1056with HTTP responses may be accessed with these dedicated accessors.
1057*Note HTTP Headers::, for more information on the format of parsed
1058headers.
1059
1060 -- Scheme Procedure: response-accept-ranges response [default=#f]
1061 -- Scheme Procedure: response-age response [default='()]
1062 -- Scheme Procedure: response-allow response [default='()]
1063 -- Scheme Procedure: response-cache-control response [default='()]
1064 -- Scheme Procedure: response-connection response [default='()]
1065 -- Scheme Procedure: response-content-encoding response [default='()]
1066 -- Scheme Procedure: response-content-language response [default='()]
1067 -- Scheme Procedure: response-content-length response [default=#f]
1068 -- Scheme Procedure: response-content-location response [default=#f]
1069 -- Scheme Procedure: response-content-md5 response [default=#f]
1070 -- Scheme Procedure: response-content-range response [default=#f]
1071 -- Scheme Procedure: response-content-type response [default=#f]
1072 -- Scheme Procedure: response-date response [default=#f]
1073 -- Scheme Procedure: response-etag response [default=#f]
1074 -- Scheme Procedure: response-expires response [default=#f]
1075 -- Scheme Procedure: response-last-modified response [default=#f]
1076 -- Scheme Procedure: response-location response [default=#f]
1077 -- Scheme Procedure: response-pragma response [default='()]
1078 -- Scheme Procedure: response-proxy-authenticate response [default=#f]
1079 -- Scheme Procedure: response-retry-after response [default=#f]
1080 -- Scheme Procedure: response-server response [default=#f]
1081 -- Scheme Procedure: response-trailer response [default='()]
1082 -- Scheme Procedure: response-transfer-encoding response [default='()]
1083 -- Scheme Procedure: response-upgrade response [default='()]
1084 -- Scheme Procedure: response-vary response [default='()]
1085 -- Scheme Procedure: response-via response [default='()]
1086 -- Scheme Procedure: response-warning response [default='()]
1087 -- Scheme Procedure: response-www-authenticate response [default=#f]
1088     Return the given response header, or DEFAULT if none was present.
1089
1090 -- Scheme Procedure: text-content-type? TYPE
1091     Return ‘#t’ if TYPE, a symbol as returned by
1092     ‘response-content-type’, represents a textual type such as
1093text/plain’.
1094
1095
1096File: guile.info,  Node: Web Client,  Next: Web Server,  Prev: Responses,  Up: Web
1097
10987.3.8 Web Client
1099----------------
1100
1101‘(web client)’ provides a simple, synchronous HTTP client, built on the
1102lower-level HTTP, request, and response modules.
1103
1104     (use-modules (web client))
1105
1106 -- Scheme Procedure: open-socket-for-uri uri [#:verify-certificate? #t]
1107     Return an open input/output port for a connection to URI. Guile
1108     dynamically loads GnuTLS for HTTPS support.  *Note how to install
1109     the GnuTLS bindings for Guile: (gnutls-guile)Guile Preparations,
1110     for more information.
1111
1112     When VERIFY-CERTIFICATE? is true, verify the server’s X.509
1113     certificates against those read from ‘x509-certificate-directory’.
1114     When an error occurs—e.g., the server’s certificate has expired, or
1115     its host name does not match—raise a ‘tls-certificate-error’
1116     exception.  The arguments to the ‘tls-certificate-error’ exception
1117     are:
1118
1119       1. a symbol indicating the failure cause, ‘host-mismatch’ if the
1120          certificate’s host name does not match the server’s host name,
1121          and ‘invalid-certificate’ for other causes;
1122
1123       2. the server’s X.509 certificate (*note GnuTLS Guile reference:
1124          (gnutls-guile)Guile Reference.);
1125
1126       3. the server’s host name (a string);
1127
1128       4. in the case of ‘invalid-certificate’ errors, a list of GnuTLS
1129          certificate status values—one of the ‘certificate-status/’
1130          constants, such as ‘certificate-status/signer-not-found’ or
1131certificate-status/revoked’.
1132
1133 -- Scheme Procedure: http-request URI ARG...
1134
1135     Connect to the server corresponding to URI and make a request over
1136     HTTP, using METHOD (‘GET’, ‘HEAD’, ‘POST’, etc.).
1137
1138     The following keyword arguments allow you to modify the requests in
1139     various ways, for example attaching a body to the request, or
1140     setting specific headers.  The following table lists the keyword
1141     arguments and their default values.
1142
1143     ‘#:method 'GET’
1144     ‘#:body #f’
1145     ‘#:verify-certificate? #t’
1146     ‘#:port (open-socket-for-uri URI #:verify-certificate? VERIFY-CERTIFICATE?)’
1147     ‘#:version '(1 . 1)’
1148     ‘#:keep-alive? #f’
1149     ‘#:headers '()’
1150     ‘#:decode-body? #t’
1151     ‘#:streaming? #f’
1152
1153     If you already have a port open, pass it as PORT.  Otherwise, a
1154     connection will be opened to the server corresponding to URI.  Any
1155     extra headers in the alist HEADERS will be added to the request.
1156
1157     If BODY is not ‘#f’, a message body will also be sent with the HTTP
1158     request.  If BODY is a string, it is encoded according to the
1159     content-type in HEADERS, defaulting to UTF-8.  Otherwise BODY
1160     should be a bytevector, or ‘#f’ for no body.  Although a message
1161     body may be sent with any request, usually only ‘POST’ and ‘PUT’
1162     requests have bodies.
1163
1164     If DECODE-BODY? is true, as is the default, the body of the
1165     response will be decoded to string, if it is a textual
1166     content-type.  Otherwise it will be returned as a bytevector.
1167
1168     However, if STREAMING? is true, instead of eagerly reading the
1169     response body from the server, this function only reads off the
1170     headers.  The response body will be returned as a port on which the
1171     data may be read.
1172
1173     Unless KEEP-ALIVE? is true, the port will be closed after the full
1174     response body has been read.
1175
1176     If PORT is false, URI denotes an HTTPS URL, and VERIFY-CERTIFICATE?
1177     is true, verify X.509 certificates against those available in
1178     ‘x509-certificate-directory’.
1179
1180     Returns two values: the response read from the server, and the
1181     response body as a string, bytevector, #f value, or as a port (if
1182     STREAMING? is true).
1183
1184 -- Scheme Procedure: http-get URI ARG...
1185 -- Scheme Procedure: http-head URI ARG...
1186 -- Scheme Procedure: http-post URI ARG...
1187 -- Scheme Procedure: http-put URI ARG...
1188 -- Scheme Procedure: http-delete URI ARG...
1189 -- Scheme Procedure: http-trace URI ARG...
1190 -- Scheme Procedure: http-options URI ARG...
1191     Connect to the server corresponding to URI and make a request over
1192     HTTP, using the appropriate method (‘GET’, ‘HEAD’, ‘POST’, etc.).
1193
1194     These procedures are variants of ‘http-request’ specialized with a
1195     specific METHOD argument, and have the same prototype: a URI
1196     followed by an optional sequence of keyword arguments.  *Note
1197     http-request::, for full documentation on the various keyword
1198     arguments.
1199
1200 -- Scheme Parameter: x509-certificate-directory
1201     This parameter gives the name of the directory where X.509
1202     certificates for HTTPS connections should be looked for.
1203
1204     Its default value is one of:
1205
1206        • the value of the ‘GUILE_TLS_CERTIFICATE_DIRECTORY’ environment
1207          variable;
1208
1209        • or the value of the ‘SSL_CERT_DIR’ environment variable (also
1210          honored by the OpenSSL library);
1211
1212        • or, as a last resort, ‘"/etc/ssl/certs"’.
1213
1214     X.509 certificates are used when authenticating the identity of a
1215     remote site, when the ‘#:verify-certificate?’ argument to
1216     ‘open-socket-for-uri’, to ‘http-request’, or to related procedures
1217     is true.
1218
1219   ‘http-get’ is useful for making one-off requests to web sites.  If
1220you are writing a web spider or some other client that needs to handle a
1221number of requests in parallel, it’s better to build an event-driven URL
1222fetcher, similar in structure to the web server (*note Web Server::).
1223
1224   Another option, good but not as performant, would be to use threads,
1225possibly via par-map or futures.
1226
1227 -- Scheme Parameter: current-http-proxy
1228 -- Scheme Parameter: current-https-proxy
1229     Either ‘#f’ or a non-empty string containing the URL of the HTTP or
1230     HTTPS proxy server to be used by the procedures in the ‘(web
1231     client)’ module, including ‘open-socket-for-uri’.  Its initial
1232     value is based on the ‘http_proxy’ and ‘https_proxy’ environment
1233     variables.
1234
1235          (current-http-proxy) ⇒ "http://localhost:8123/"
1236          (parameterize ((current-http-proxy #f))
1237            (http-get "http://example.com/"))  ; temporarily bypass proxy
1238          (current-http-proxy) ⇒ "http://localhost:8123/"
1239
1240
1241File: guile.info,  Node: Web Server,  Next: Web Examples,  Prev: Web Client,  Up: Web
1242
12437.3.9 Web Server
1244----------------
1245
1246‘(web server)’ is a generic web server interface, along with a main loop
1247implementation for web servers controlled by Guile.
1248
1249     (use-modules (web server))
1250
1251   The lowest layer is the ‘<server-impl>’ object, which defines a set
1252of hooks to open a server, read a request from a client, write a
1253response to a client, and close a server.  These hooks – ‘open’, ‘read’,
1254‘write’, and ‘close’, respectively – are bound together in a
1255‘<server-impl>’ object.  Procedures in this module take a
1256‘<server-impl>’ object, if needed.
1257
1258   A ‘<server-impl>’ may also be looked up by name.  If you pass the
1259‘http’ symbol to ‘run-server’, Guile looks for a variable named ‘http’
1260in the ‘(web server http)’ module, which should be bound to a
1261‘<server-impl>’ object.  Such a binding is made by instantiation of the
1262‘define-server-impl’ syntax.  In this way the run-server loop can
1263automatically load other backends if available.
1264
1265   The life cycle of a server goes as follows:
1266
1267  1. The ‘open’ hook is called, to open the server.  ‘open’ takes zero
1268     or more arguments, depending on the backend, and returns an opaque
1269     server socket object, or signals an error.
1270
1271  2. The ‘read’ hook is called, to read a request from a new client.
1272     The ‘read’ hook takes one argument, the server socket.  It should
1273     return three values: an opaque client socket, the request, and the
1274     request body.  The request should be a ‘<request>’ object, from
1275     ‘(web request)’.  The body should be a string or a bytevector, or
1276     ‘#f’ if there is no body.
1277
1278     If the read failed, the ‘read’ hook may return #f for the client
1279     socket, request, and body.
1280
1281  3. A user-provided handler procedure is called, with the request and
1282     body as its arguments.  The handler should return two values: the
1283     response, as a ‘<response>’ record from ‘(web response)’, and the
1284     response body as bytevector, or ‘#f’ if not present.
1285
1286     The respose and response body are run through ‘sanitize-response’,
1287     documented below.  This allows the handler writer to take some
1288     convenient shortcuts: for example, instead of a ‘<response>’, the
1289     handler can simply return an alist of headers, in which case a
1290     default response object is constructed with those headers.  Instead
1291     of a bytevector for the body, the handler can return a string,
1292     which will be serialized into an appropriate encoding; or it can
1293     return a procedure, which will be called on a port to write out the
1294     data.  See the ‘sanitize-response’ documentation, for more.
1295
1296  4. The ‘write’ hook is called with three arguments: the client socket,
1297     the response, and the body.  The ‘write’ hook returns no values.
1298
1299  5. At this point the request handling is complete.  For a loop, we
1300     loop back and try to read a new request.
1301
1302  6. If the user interrupts the loop, the ‘close’ hook is called on the
1303     server socket.
1304
1305   A user may define a server implementation with the following form:
1306
1307 -- Scheme Syntax: define-server-impl name open read write close
1308     Make a ‘<server-impl>’ object with the hooks OPEN, READ, WRITE, and
1309     CLOSE, and bind it to the symbol NAME in the current module.
1310
1311 -- Scheme Procedure: lookup-server-impl impl
1312     Look up a server implementation.  If IMPL is a server
1313     implementation already, it is returned directly.  If it is a
1314     symbol, the binding named IMPL in the ‘(web server IMPL)’ module is
1315     looked up.  Otherwise an error is signaled.
1316
1317     Currently a server implementation is a somewhat opaque type, useful
1318     only for passing to other procedures in this module, like
1319     ‘read-client’.
1320
1321   The ‘(web server)’ module defines a number of routines that use
1322‘<server-impl>’ objects to implement parts of a web server.  Given that
1323we don’t expose the accessors for the various fields of a
1324‘<server-impl>’, indeed these routines are the only procedures with any
1325access to the impl objects.
1326
1327 -- Scheme Procedure: open-server impl open-params
1328     Open a server for the given implementation.  Return one value, the
1329     new server object.  The implementation’s ‘open’ procedure is
1330     applied to OPEN-PARAMS, which should be a list.
1331
1332 -- Scheme Procedure: read-client impl server
1333     Read a new client from SERVER, by applying the implementation’s
1334     ‘read’ procedure to the server.  If successful, return three
1335     values: an object corresponding to the client, a request object,
1336     and the request body.  If any exception occurs, return ‘#f’ for all
1337     three values.
1338
1339 -- Scheme Procedure: handle-request handler request body state
1340     Handle a given request, returning the response and body.
1341
1342     The response and response body are produced by calling the given
1343     HANDLER with REQUEST and BODY as arguments.
1344
1345     The elements of STATE are also passed to HANDLER as arguments, and
1346     may be returned as additional values.  The new STATE, collected
1347     from the HANDLER’s return values, is then returned as a list.  The
1348     idea is that a server loop receives a handler from the user, along
1349     with whatever state values the user is interested in, allowing the
1350     user’s handler to explicitly manage its state.
1351
1352 -- Scheme Procedure: sanitize-response request response body
1353     “Sanitize” the given response and body, making them appropriate for
1354     the given request.
1355
1356     As a convenience to web handler authors, RESPONSE may be given as
1357     an alist of headers, in which case it is used to construct a
1358     default response.  Ensures that the response version corresponds to
1359     the request version.  If BODY is a string, encodes the string to a
1360     bytevector, in an encoding appropriate for RESPONSE.  Adds a
1361     ‘content-length’ and ‘content-type’ header, as necessary.
1362
1363     If BODY is a procedure, it is called with a port as an argument,
1364     and the output collected as a bytevector.  In the future we might
1365     try to instead use a compressing, chunk-encoded port, and call this
1366     procedure later, in the write-client procedure.  Authors are
1367     advised not to rely on the procedure being called at any particular
1368     time.
1369
1370 -- Scheme Procedure: write-client impl server client response body
1371     Write an HTTP response and body to CLIENT.  If the server and
1372     client support persistent connections, it is the implementation’s
1373     responsibility to keep track of the client thereafter, presumably
1374     by attaching it to the SERVER argument somehow.
1375
1376 -- Scheme Procedure: close-server impl server
1377     Release resources allocated by a previous invocation of
1378     ‘open-server’.
1379
1380   Given the procedures above, it is a small matter to make a web
1381server:
1382
1383 -- Scheme Procedure: serve-one-client handler impl server state
1384     Read one request from SERVER, call HANDLER on the request and body,
1385     and write the response to the client.  Return the new state
1386     produced by the handler procedure.
1387
1388 -- Scheme Procedure: run-server handler [impl='http] [open-params='()]
1389          arg ...
1390     Run Guile’s built-in web server.
1391
1392     HANDLER should be a procedure that takes two or more arguments, the
1393     HTTP request and request body, and returns two or more values, the
1394     response and response body.
1395
1396     For examples, skip ahead to the next section, *note Web Examples::.
1397
1398     The response and body will be run through ‘sanitize-response’
1399     before sending back to the client.
1400
1401     Additional arguments to HANDLER are taken from ARG ....  These
1402     arguments comprise a “state”.  Additional return values are
1403     accumulated into a new state, which will be used for subsequent
1404     requests.  In this way a handler can explicitly manage its state.
1405
1406   The default web server implementation is ‘http’, which binds to a
1407socket, listening for request on that port.
1408
1409 -- HTTP Implementation: http [#:host=#f] [#:family=AF_INET]
1410          [#:addr=INADDR_LOOPBACK] [#:port 8080] [#:socket]
1411     The default HTTP implementation.  We document it as a function with
1412     keyword arguments, because that is precisely the way that it is –
1413     all of the OPEN-PARAMS to ‘run-server’ get passed to the
1414     implementation’s open function.
1415
1416          ;; The defaults: localhost:8080
1417          (run-server handler)
1418          ;; Same thing
1419          (run-server handler 'http '())
1420          ;; On a different port
1421          (run-server handler 'http '(#:port 8081))
1422          ;; IPv6
1423          (run-server handler 'http '(#:family AF_INET6 #:port 8081))
1424          ;; Custom socket
1425          (run-server handler 'http `(#:socket ,(sudo-make-me-a-socket)))
1426
1427
1428File: guile.info,  Node: Web Examples,  Prev: Web Server,  Up: Web
1429
14307.3.10 Web Examples
1431-------------------
1432
1433Well, enough about the tedious internals.  Let’s make a web application!
1434
14357.3.10.1 Hello, World!
1436......................
1437
1438The first program we have to write, of course, is “Hello, World!”.  This
1439means that we have to implement a web handler that does what we want.
1440
1441   Now we define a handler, a function of two arguments and two return
1442values:
1443
1444     (define (handler request request-body)
1445       (values RESPONSE RESPONSE-BODY))
1446
1447   In this first example, we take advantage of a short-cut, returning an
1448alist of headers instead of a proper response object.  The response body
1449is our payload:
1450
1451     (define (hello-world-handler request request-body)
1452       (values '((content-type . (text/plain)))
1453               "Hello World!"))
1454
1455   Now let’s test it, by running a server with this handler.  Load up
1456the web server module if you haven’t yet done so, and run a server with
1457this handler:
1458
1459     (use-modules (web server))
1460     (run-server hello-world-handler)
1461
1462   By default, the web server listens for requests on ‘localhost:8080’.
1463Visit that address in your web browser to test.  If you see the string,
1464‘Hello World!’, sweet!
1465
14667.3.10.2 Inspecting the Request
1467...............................
1468
1469The Hello World program above is a general greeter, responding to all
1470URIs.  To make a more exclusive greeter, we need to inspect the request
1471object, and conditionally produce different results.  So let’s load up
1472the request, response, and URI modules, and do just that.
1473
1474     (use-modules (web server)) ; you probably did this already
1475     (use-modules (web request)
1476                  (web response)
1477                  (web uri))
1478
1479     (define (request-path-components request)
1480       (split-and-decode-uri-path (uri-path (request-uri request))))
1481
1482     (define (hello-hacker-handler request body)
1483       (if (equal? (request-path-components request)
1484                   '("hacker"))
1485           (values '((content-type . (text/plain)))
1486                   "Hello hacker!")
1487           (not-found request)))
1488
1489     (run-server hello-hacker-handler)
1490
1491   Here we see that we have defined a helper to return the components of
1492the URI path as a list of strings, and used that to check for a request
1493to ‘/hacker/’.  Then the success case is just as before – visit
1494http://localhost:8080/hacker/’ in your browser to check.
1495
1496   You should always match against URI path components as decoded by
1497‘split-and-decode-uri-path’.  The above example will work for
1498‘/hacker/’, ‘//hacker///’, and ‘/h%61ck%65r’.
1499
1500   But we forgot to define ‘not-found’!  If you are pasting these
1501examples into a REPL, accessing any other URI in your web browser will
1502drop your Guile console into the debugger:
1503
1504     <unnamed port>:38:7: In procedure module-lookup:
1505     <unnamed port>:38:7: Unbound variable: not-found
1506
1507     Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.
1508     scheme@(guile-user) [1]>
1509
1510   So let’s define the function, right there in the debugger.  As you
1511probably know, we’ll want to return a 404 response.
1512
1513     ;; Paste this in your REPL
1514     (define (not-found request)
1515       (values (build-response #:code 404)
1516               (string-append "Resource not found: "
1517                              (uri->string (request-uri request)))))
1518
1519     ;; Now paste this to let the web server keep going:
1520     ,continue
1521
1522   Now if you access ‘http://localhost/foo/’, you get this error
1523message.  (Note that some popular web browsers won’t show
1524server-generated 404 messages, showing their own instead, unless the 404
1525message body is long enough.)
1526
15277.3.10.3 Higher-Level Interfaces
1528................................
1529
1530The web handler interface is a common baseline that all kinds of Guile
1531web applications can use.  You will usually want to build something on
1532top of it, however, especially when producing HTML. Here is a simple
1533example that builds up HTML output using SXML (*note SXML::).
1534
1535   First, load up the modules:
1536
1537     (use-modules (web server)
1538                  (web request)
1539                  (web response)
1540                  (sxml simple))
1541
1542   Now we define a simple templating function that takes a list of HTML
1543body elements, as SXML, and puts them in our super template:
1544
1545     (define (templatize title body)
1546       `(html (head (title ,title))
1547              (body ,@body)))
1548
1549   For example, the simplest Hello HTML can be produced like this:
1550
1551     (sxml->xml (templatize "Hello!" '((b "Hi!"))))
15521553     <html><head><title>Hello!</title></head><body><b>Hi!</b></body></html>
1554
1555   Much better to work with Scheme data types than to work with HTML as
1556strings.  Now we define a little response helper:
1557
1558     (define* (respond #:optional body #:key
1559                       (status 200)
1560                       (title "Hello hello!")
1561                       (doctype "<!DOCTYPE html>\n")
1562                       (content-type-params '((charset . "utf-8")))
1563                       (content-type 'text/html)
1564                       (extra-headers '())
1565                       (sxml (and body (templatize title body))))
1566       (values (build-response
1567                #:code status
1568                #:headers `((content-type
1569                             . (,content-type ,@content-type-params))
1570                            ,@extra-headers))
1571               (lambda (port)
1572                 (if sxml
1573                     (begin
1574                       (if doctype (display doctype port))
1575                       (sxml->xml sxml port))))))
1576
1577   Here we see the power of keyword arguments with default initializers.
1578By the time the arguments are fully parsed, the ‘sxml’ local variable
1579will hold the templated SXML, ready for sending out to the client.
1580
1581   Also, instead of returning the body as a string, ‘respond’ gives a
1582procedure, which will be called by the web server to write out the
1583response to the client.
1584
1585   Now, a simple example using this responder, which lays out the
1586incoming headers in an HTML table.
1587
1588     (define (debug-page request body)
1589       (respond
1590        `((h1 "hello world!")
1591          (table
1592           (tr (th "header") (th "value"))
1593           ,@(map (lambda (pair)
1594                    `(tr (td (tt ,(with-output-to-string
1595                                    (lambda () (display (car pair))))))
1596                         (td (tt ,(with-output-to-string
1597                                    (lambda ()
1598                                      (write (cdr pair))))))))
1599                  (request-headers request))))))
1600
1601     (run-server debug-page)
1602
1603   Now if you visit any local address in your web browser, we actually
1604see some HTML, finally.
1605
16067.3.10.4 Conclusion
1607...................
1608
1609Well, this is about as far as Guile’s built-in web support goes, for
1610now.  There are many ways to make a web application, but hopefully by
1611standardizing the most fundamental data types, users will be able to
1612choose the approach that suits them best, while also being able to
1613switch between implementations of the server.  This is a relatively new
1614part of Guile, so if you have feedback, let us know, and we can take it
1615into account.  Happy hacking on the web!
1616
1617
1618File: guile.info,  Node: getopt-long,  Next: SRFI Support,  Prev: Web,  Up: Guile Modules
1619
16207.4 The (ice-9 getopt-long) Module
1621==================================
1622
1623The ‘(ice-9 getopt-long)’ facility is designed to help parse arguments
1624that are passed to Guile programs on the command line, and is modelled
1625after the C library’s facility of the same name (*note (libc)Getopt::).
1626For a more low-level interface to command-line argument parsing, *Note
1627SRFI-37::.
1628
1629   The ‘(ice-9 getopt-long)’ module exports two procedures:
1630‘getopt-long’ and ‘option-ref’.
1631
1632   • ‘getopt-long’ takes a list of strings — the command line arguments
1633     — an “option specification”, and some optional keyword parameters.
1634     It parses the command line arguments according to the option
1635     specification and keyword parameters, and returns a data structure
1636     that encapsulates the results of the parsing.
1637
1638   • ‘option-ref’ then takes the parsed data structure and a specific
1639     option’s name, and returns information about that option in
1640     particular.
1641
1642   To make these procedures available to your Guile script, include the
1643expression ‘(use-modules (ice-9 getopt-long))’ somewhere near the top,
1644before the first usage of ‘getopt-long’ or ‘option-ref’.
1645
1646* Menu:
1647
1648* getopt-long Example::         A short getopt-long example.
1649* Option Specification::        How to write an option specification.
1650* Command Line Format::         The expected command line format.
1651* getopt-long Reference::       Full documentation for ‘getopt-long’.
1652* option-ref Reference::        Full documentation for ‘option-ref’.
1653
1654
1655File: guile.info,  Node: getopt-long Example,  Next: Option Specification,  Up: getopt-long
1656
16577.4.1 A Short getopt-long Example
1658---------------------------------
1659
1660This section illustrates how ‘getopt-long’ is used by presenting and
1661dissecting a simple example.  The first thing that we need is an “option
1662specification” that tells ‘getopt-long’ how to parse the command line.
1663This specification is an association list with the long option name as
1664the key.  Here is how such a specification might look:
1665
1666     (define option-spec
1667       '((version (single-char #\v) (value #f))
1668         (help    (single-char #\h) (value #f))))
1669
1670   This alist tells ‘getopt-long’ that it should accept two long
1671options, called _version_ and _help_, and that these options can also be
1672selected by the single-letter abbreviations _v_ and _h_, respectively.
1673The ‘(value #f)’ clauses indicate that neither of the options accepts a
1674value.
1675
1676   With this specification we can use ‘getopt-long’ to parse a given
1677command line:
1678
1679     (define options (getopt-long (command-line) option-spec))
1680
1681   After this call, ‘options’ contains the parsed command line and is
1682ready to be examined by ‘option-ref’.  ‘option-ref’ is called like this:
1683
1684     (option-ref options 'help #f)
1685
1686It expects the parsed command line, a symbol indicating the option to
1687examine, and a default value.  The default value is returned if the
1688option was not present in the command line, or if the option was present
1689but without a value; otherwise the value from the command line is
1690returned.  Usually ‘option-ref’ is called once for each possible option
1691that a script supports.
1692
1693   The following example shows a main program which puts all this
1694together to parse its command line and figure out what the user wanted.
1695
1696     (define (main args)
1697       (let* ((option-spec '((version (single-char #\v) (value #f))
1698                             (help    (single-char #\h) (value #f))))
1699              (options (getopt-long args option-spec))
1700              (help-wanted (option-ref options 'help #f))
1701              (version-wanted (option-ref options 'version #f)))
1702         (if (or version-wanted help-wanted)
1703             (begin
1704               (if version-wanted
1705                   (display "getopt-long-example version 0.3\n"))
1706               (if help-wanted
1707                   (display "\
1708     getopt-long-example [options]
1709       -v, --version    Display version
1710       -h, --help       Display this help
1711     ")))
1712             (begin
1713               (display "Hello, World!") (newline)))))
1714
1715
1716File: guile.info,  Node: Option Specification,  Next: Command Line Format,  Prev: getopt-long Example,  Up: getopt-long
1717
17187.4.2 How to Write an Option Specification
1719------------------------------------------
1720
1721An option specification is an association list (*note Association
1722Lists::) with one list element for each supported option.  The key of
1723each list element is a symbol that names the option, while the value is
1724a list of option properties:
1725
1726     OPTION-SPEC ::=  '( (OPT-NAME1 (PROP-NAME PROP-VALUE) ...)
1727                         (OPT-NAME2 (PROP-NAME PROP-VALUE) ...)
1728                         (OPT-NAME3 (PROP-NAME PROP-VALUE) ...)
1729                         ...
1730                       )
1731
1732   Each OPT-NAME specifies the long option name for that option.  For
1733example, a list element with OPT-NAME ‘background’ specifies an option
1734that can be specified on the command line using the long option
1735‘--background’.  Further information about the option — whether it takes
1736a value, whether it is required to be present in the command line, and
1737so on — is specified by the option properties.
1738
1739   In the example of the preceding section, we already saw that a long
1740option name can have a equivalent “short option” character.  The
1741equivalent short option character can be set for an option by specifying
1742a ‘single-char’ property in that option’s property list.  For example, a
1743list element like ‘'(output (single-char #\o) ...)’ specifies an option
1744with long name ‘--output’ that can also be specified by the equivalent
1745short name ‘-o’.
1746
1747   The ‘value’ property specifies whether an option requires or accepts
1748a value.  If the ‘value’ property is set to ‘#t’, the option requires a
1749value: ‘getopt-long’ will signal an error if the option name is present
1750without a corresponding value.  If set to ‘#f’, the option does not take
1751a value; in this case, a non-option word that follows the option name in
1752the command line will be treated as a non-option argument.  If set to
1753the symbol ‘optional’, the option accepts a value but does not require
1754one: a non-option word that follows the option name in the command line
1755will be interpreted as that option’s value.  If the option name for an
1756option with ‘'(value optional)’ is immediately followed in the command
1757line by _another_ option name, the value for the first option is
1758implicitly ‘#t’.
1759
1760   The ‘required?’ property indicates whether an option is required to
1761be present in the command line.  If the ‘required?’ property is set to
1762‘#t’, ‘getopt-long’ will signal an error if the option is not specified.
1763
1764   Finally, the ‘predicate’ property can be used to constrain the
1765possible values of an option.  If used, the ‘predicate’ property should
1766be set to a procedure that takes one argument — the proposed option
1767value as a string — and returns either ‘#t’ or ‘#f’ according as the
1768proposed value is or is not acceptable.  If the predicate procedure
1769returns ‘#f’, ‘getopt-long’ will signal an error.
1770
1771   By default, options do not have single-character equivalents, are not
1772required, and do not take values.  Where the list element for an option
1773includes a ‘value’ property but no ‘predicate’ property, the option
1774values are unconstrained.
1775
1776
1777File: guile.info,  Node: Command Line Format,  Next: getopt-long Reference,  Prev: Option Specification,  Up: getopt-long
1778
17797.4.3 Expected Command Line Format
1780----------------------------------
1781
1782In order for ‘getopt-long’ to correctly parse a command line, that
1783command line must conform to a standard set of rules for how command
1784line options are specified.  This section explains what those rules are.
1785
1786   ‘getopt-long’ splits a given command line into several pieces.  All
1787elements of the argument list are classified to be either options or
1788normal arguments.  Options consist of two dashes and an option name
1789(so-called “long” options), or of one dash followed by a single letter
1790(“short” options).
1791
1792   Options can behave as switches, when they are given without a value,
1793or they can be used to pass a value to the program.  The value for an
1794option may be specified using an equals sign, or else is simply the next
1795word in the command line, so the following two invocations are
1796equivalent:
1797
1798     $ ./foo.scm --output=bar.txt
1799     $ ./foo.scm --output bar.txt
1800
1801   Short options can be used instead of their long equivalents and can
1802be grouped together after a single dash.  For example, the following
1803commands are equivalent.
1804
1805     $ ./foo.scm --version --help
1806     $ ./foo.scm -v --help
1807     $ ./foo.scm -vh
1808
1809   If an option requires a value, it can only be grouped together with
1810other short options if it is the last option in the group; the value is
1811the next argument.  So, for example, with the following option
1812specification —
1813
1814     ((apples    (single-char #\a))
1815      (blimps    (single-char #\b) (value #t))
1816      (catalexis (single-char #\c) (value #t)))
1817
1818— the following command lines would all be acceptable:
1819
1820     $ ./foo.scm -a -b bang -c couth
1821     $ ./foo.scm -ab bang -c couth
1822     $ ./foo.scm -ac couth -b bang
1823
1824   But the next command line is an error, because ‘-b’ is not the last
1825option in its combination, and because a group of short options cannot
1826include two options that both require values:
1827
1828     $ ./foo.scm -abc couth bang
1829
1830   If an option’s value is optional, ‘getopt-long’ decides whether the
1831option has a value by looking at what follows it in the argument list.
1832If the next element is a string, and it does not appear to be an option
1833itself, then that string is the option’s value.
1834
1835   If the option ‘--’ appears in the argument list, argument parsing
1836stops there and subsequent arguments are returned as ordinary arguments,
1837even if they resemble options.  So, with the command line
1838
1839     $ ./foo.scm --apples "Granny Smith" -- --blimp Goodyear
1840
1841‘getopt-long’ will recognize the ‘--apples’ option as having the value
1842"Granny Smith", but will not treat ‘--blimp’ as an option.  The strings
1843‘--blimp’ and ‘Goodyear’ will be returned as ordinary argument strings.
1844
1845
1846File: guile.info,  Node: getopt-long Reference,  Next: option-ref Reference,  Prev: Command Line Format,  Up: getopt-long
1847
18487.4.4 Reference Documentation for ‘getopt-long’
1849-----------------------------------------------
1850
1851 -- Scheme Procedure: getopt-long args grammar
1852          [#:stop-at-first-non-option #t]
1853     Parse the command line given in ARGS (which must be a list of
1854     strings) according to the option specification GRAMMAR.
1855
1856     The GRAMMAR argument is expected to be a list of this form:
1857
1858     ‘((OPTION (PROPERTY VALUE) ...) ...)’
1859
1860     where each OPTION is a symbol denoting the long option, but without
1861     the two leading dashes (e.g. ‘version’ if the option is called
1862     ‘--version’).
1863
1864     For each option, there may be list of arbitrarily many
1865     property/value pairs.  The order of the pairs is not important, but
1866     every property may only appear once in the property list.  The
1867     following table lists the possible properties:
1868
1869     ‘(single-char CHAR)’
1870          Accept ‘-CHAR’ as a single-character equivalent to ‘--OPTION’.
1871          This is how to specify traditional Unix-style flags.
1872     ‘(required? BOOL)’
1873          If BOOL is true, the option is required.  ‘getopt-long’ will
1874          raise an error if it is not found in ARGS.
1875     ‘(value BOOL)’
1876          If BOOL is ‘#t’, the option accepts a value; if it is ‘#f’, it
1877          does not; and if it is the symbol ‘optional’, the option may
1878          appear in ARGS with or without a value.
1879     ‘(predicate FUNC)’
1880          If the option accepts a value (i.e. you specified ‘(value #t)’
1881          for this option), then ‘getopt-long’ will apply FUNC to the
1882          value, and throw an exception if it returns ‘#f’.  FUNC should
1883          be a procedure which accepts a string and returns a boolean
1884          value; you may need to use quasiquotes to get it into GRAMMAR.
1885
1886     The ‘#:stop-at-first-non-option’ keyword, if specified with any
1887     true value, tells ‘getopt-long’ to stop when it gets to the first
1888     non-option in the command line.  That is, at the first word which
1889     is neither an option itself, nor the value of an option.
1890     Everything in the command line from that word onwards will be
1891     returned as non-option arguments.
1892
1893   ‘getopt-long’’s ARGS parameter is expected to be a list of strings
1894like the one returned by ‘command-line’, with the first element being
1895the name of the command.  Therefore ‘getopt-long’ ignores the first
1896element in ARGS and starts argument interpretation with the second
1897element.
1898
1899   ‘getopt-long’ signals an error if any of the following conditions
1900hold.
1901
1902   • The option grammar has an invalid syntax.
1903
1904   • One of the options in the argument list was not specified by the
1905     grammar.
1906
1907   • A required option is omitted.
1908
1909   • An option which requires an argument did not get one.
1910
1911   • An option that doesn’t accept an argument does get one (this can
1912     only happen using the long option ‘--opt=VALUE’ syntax).
1913
1914   • An option predicate fails.
1915
1916   ‘#:stop-at-first-non-option’ is useful for command line invocations
1917like ‘guild [--help | --version] [script [script-options]]’ and ‘cvs
1918[general-options] command [command-options]’, where there are options at
1919two levels: some generic and understood by the outer command, and some
1920that are specific to the particular script or command being invoked.  To
1921use ‘getopt-long’ in such cases, you would call it twice: firstly with
1922‘#:stop-at-first-non-option #t’, so as to parse any generic options and
1923identify the wanted script or sub-command; secondly, and after trimming
1924off the initial generic command words, with a script- or
1925sub-command-specific option grammar, so as to process those specific
1926options.
1927
1928
1929File: guile.info,  Node: option-ref Reference,  Prev: getopt-long Reference,  Up: getopt-long
1930
19317.4.5 Reference Documentation for ‘option-ref’
1932----------------------------------------------
1933
1934 -- Scheme Procedure: option-ref options key default
1935     Search OPTIONS for a command line option named KEY and return its
1936     value, if found.  If the option has no value, but was given, return
1937     ‘#t’.  If the option was not given, return DEFAULT.  OPTIONS must
1938     be the result of a call to ‘getopt-long’.
1939
1940   ‘option-ref’ always succeeds, either by returning the requested
1941option value from the command line, or the default value.
1942
1943   The special key ‘'()’ can be used to get a list of all non-option
1944arguments.
1945
1946
1947File: guile.info,  Node: SRFI Support,  Next: R6RS Support,  Prev: getopt-long,  Up: Guile Modules
1948
19497.5 SRFI Support Modules
1950========================
1951
1952SRFI is an acronym for Scheme Request For Implementation.  The SRFI
1953documents define a lot of syntactic and procedure extensions to standard
1954Scheme as defined in R5RS.
1955
1956   Guile has support for a number of SRFIs.  This chapter gives an
1957overview over the available SRFIs and some usage hints.  For complete
1958documentation, design rationales and further examples, we advise you to
1959get the relevant SRFI documents from the SRFI home page
1960<http://srfi.schemers.org/>.
1961
1962* Menu:
1963
1964* About SRFI Usage::            What to know about Guile’s SRFI support.
1965* SRFI-0::                      cond-expand
1966* SRFI-1::                      List library.
1967* SRFI-2::                      and-let*.
1968* SRFI-4::                      Homogeneous numeric vector datatypes.
1969* SRFI-6::                      Basic String Ports.
1970* SRFI-8::                      receive.
1971* SRFI-9::                      define-record-type.
1972* SRFI-10::                     Hash-Comma Reader Extension.
1973* SRFI-11::                     let-values and let*-values.
1974* SRFI-13::                     String library.
1975* SRFI-14::                     Character-set library.
1976* SRFI-16::                     case-lambda
1977* SRFI-17::                     Generalized set!
1978* SRFI-18::                     Multithreading support
1979* SRFI-19::                     Time/Date library.
1980* SRFI-23::                     Error reporting
1981* SRFI-26::                     Specializing parameters
1982* SRFI-27::                     Sources of Random Bits
1983* SRFI-28::                     Basic format strings.
1984* SRFI-30::                     Nested multi-line block comments
1985* SRFI-31::                     A special form ‘rec’ for recursive evaluation
1986* SRFI-34::                     Exception handling.
1987* SRFI-35::                     Conditions.
1988* SRFI-37::                     args-fold program argument processor
1989* SRFI-38::                     External Representation for Data With Shared Structure
1990* SRFI-39::                     Parameter objects
1991* SRFI-41::                     Streams.
1992* SRFI-42::                     Eager comprehensions
1993* SRFI-43::                     Vector Library.
1994* SRFI-45::                     Primitives for expressing iterative lazy algorithms
1995* SRFI-46::                     Basic syntax-rules Extensions.
1996* SRFI-55::                     Requiring Features.
1997* SRFI-60::                     Integers as bits.
1998* SRFI-61::                     A more general ‘cond’ clause
1999* SRFI-62::                     S-expression comments.
2000* SRFI-64::                     A Scheme API for test suites.
2001* SRFI-67::                     Compare procedures
2002* SRFI-69::                     Basic hash tables.
2003* SRFI-71::                     Extended let-syntax for multiple values.
2004* SRFI-87::                     => in case clauses.
2005* SRFI-88::                     Keyword objects.
2006* SRFI-98::                     Accessing environment variables.
2007* SRFI-105::                    Curly-infix expressions.
2008* SRFI-111::                    Boxes.
2009* SRFI-171::                    Transducers
2010
2011
2012File: guile.info,  Node: About SRFI Usage,  Next: SRFI-0,  Up: SRFI Support
2013
20147.5.1 About SRFI Usage
2015----------------------
2016
2017SRFI support in Guile is currently implemented partly in the core
2018library, and partly as add-on modules.  That means that some SRFIs are
2019automatically available when the interpreter is started, whereas the
2020other SRFIs require you to use the appropriate support module
2021explicitly.
2022
2023   There are several reasons for this inconsistency.  First, the feature
2024checking syntactic form ‘cond-expand’ (*note SRFI-0::) must be available
2025immediately, because it must be there when the user wants to check for
2026the Scheme implementation, that is, before she can know that it is safe
2027to use ‘use-modules’ to load SRFI support modules.  The second reason is
2028that some features defined in SRFIs had been implemented in Guile before
2029the developers started to add SRFI implementations as modules (for
2030example SRFI-13 (*note SRFI-13::)).  In the future, it is possible that
2031SRFIs in the core library might be factored out into separate modules,
2032requiring explicit module loading when they are needed.  So you should
2033be prepared to have to use ‘use-modules’ someday in the future to access
2034SRFI-13 bindings.  If you want, you can do that already.  We have
2035included the module ‘(srfi srfi-13)’ in the distribution, which
2036currently does nothing, but ensures that you can write future-safe code.
2037
2038   Generally, support for a specific SRFI is made available by using
2039modules named ‘(srfi srfi-NUMBER)’, where NUMBER is the number of the
2040SRFI needed.  Another possibility is to use the command line option
2041‘--use-srfi’, which will load the necessary modules automatically (*note
2042Invoking Guile::).
2043
2044
2045File: guile.info,  Node: SRFI-0,  Next: SRFI-1,  Prev: About SRFI Usage,  Up: SRFI Support
2046
20477.5.2 SRFI-0 - cond-expand
2048--------------------------
2049
2050This SRFI lets a portable Scheme program test for the presence of
2051certain features, and adapt itself by using different blocks of code, or
2052fail if the necessary features are not available.  There’s no module to
2053load, this is in the Guile core.
2054
2055   A program designed only for Guile will generally not need this
2056mechanism, such a program can of course directly use the various
2057documented parts of Guile.
2058
2059 -- syntax: cond-expand (feature body...) ...
2060     Expand to the BODY of the first clause whose FEATURE specification
2061     is satisfied.  It is an error if no FEATURE is satisfied.
2062
2063     Features are symbols such as ‘srfi-1’, and a feature specification
2064     can use ‘and’, ‘or’ and ‘not’ forms to test combinations.  The last
2065     clause can be an ‘else’, to be used if no other passes.
2066
2067     For example, define a private version of ‘alist-cons’ if SRFI-1 is
2068     not available.
2069
2070          (cond-expand (srfi-1
2071                        )
2072                       (else
2073                        (define (alist-cons key val alist)
2074                          (cons (cons key val) alist))))
2075
2076     Or demand a certain set of SRFIs (list operations, string ports,
2077     ‘receive’ and string operations), failing if they’re not available.
2078
2079          (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
2080                        ))
2081
2082The Guile core has the following features,
2083
2084     guile
2085     guile-2   ;; starting from Guile 2.x
2086     guile-2.2 ;; starting from Guile 2.2
2087     guile-3   ;; starting from Guile 3.x
2088     guile-3.0 ;; starting from Guile 3.0
2089     r5rs
2090     r6rs
2091     r7rs
2092     exact-closed ieee-float full-unicode ratios ;; R7RS features
2093     srfi-0
2094     srfi-4
2095     srfi-6
2096     srfi-13
2097     srfi-14
2098     srfi-16
2099     srfi-23
2100     srfi-30
2101     srfi-39
2102     srfi-46
2103     srfi-55
2104     srfi-61
2105     srfi-62
2106     srfi-87
2107     srfi-105
2108
2109   Other SRFI feature symbols are defined once their code has been
2110loaded with ‘use-modules’, since only then are their bindings available.
2111
2112   The ‘--use-srfi’ command line option (*note Invoking Guile::) is a
2113good way to load SRFIs to satisfy ‘cond-expand’ when running a portable
2114program.
2115
2116   Testing the ‘guile’ feature allows a program to adapt itself to the
2117Guile module system, but still run on other Scheme systems.  For example
2118the following demands SRFI-8 (‘receive’), but also knows how to load it
2119with the Guile mechanism.
2120
2121     (cond-expand (srfi-8
2122                   )
2123                  (guile
2124                   (use-modules (srfi srfi-8))))
2125
2126   Likewise, testing the ‘guile-2’ feature allows code to be portable
2127between Guile 2.X and previous versions of Guile.  For instance, it
2128makes it possible to write code that accounts for Guile 2.X’s compiler,
2129yet be correctly interpreted on 1.8 and earlier versions:
2130
2131     (cond-expand (guile-2 (eval-when (compile)
2132                             ;; This must be evaluated at compile time.
2133                             (fluid-set! current-reader my-reader)))
2134                  (guile
2135                           ;; Earlier versions of Guile do not have a
2136                           ;; separate compilation phase.
2137                           (fluid-set! current-reader my-reader)))
2138
2139   It should be noted that ‘cond-expand’ is separate from the
2140‘*features*’ mechanism (*note Feature Tracking::), feature symbols in
2141one are unrelated to those in the other.
2142
2143
2144File: guile.info,  Node: SRFI-1,  Next: SRFI-2,  Prev: SRFI-0,  Up: SRFI Support
2145
21467.5.3 SRFI-1 - List library
2147---------------------------
2148
2149The list library defined in SRFI-1 contains a lot of useful list
2150processing procedures for construction, examining, destructuring and
2151manipulating lists and pairs.
2152
2153   Since SRFI-1 also defines some procedures which are already contained
2154in R5RS and thus are supported by the Guile core library, some list and
2155pair procedures which appear in the SRFI-1 document may not appear in
2156this section.  So when looking for a particular list/pair processing
2157procedure, you should also have a look at the sections *note Lists:: and
2158*note Pairs::.
2159
2160* Menu:
2161
2162* SRFI-1 Constructors::         Constructing new lists.
2163* SRFI-1 Predicates::           Testing list for specific properties.
2164* SRFI-1 Selectors::            Selecting elements from lists.
2165* SRFI-1 Length Append etc::    Length calculation and list appending.
2166* SRFI-1 Fold and Map::         Higher-order list processing.
2167* SRFI-1 Filtering and Partitioning::  Filter lists based on predicates.
2168* SRFI-1 Searching::            Search for elements.
2169* SRFI-1 Deleting::             Delete elements from lists.
2170* SRFI-1 Association Lists::    Handle association lists.
2171* SRFI-1 Set Operations::       Use lists for representing sets.
2172
2173
2174File: guile.info,  Node: SRFI-1 Constructors,  Next: SRFI-1 Predicates,  Up: SRFI-1
2175
21767.5.3.1 Constructors
2177....................
2178
2179New lists can be constructed by calling one of the following procedures.
2180
2181 -- Scheme Procedure: xcons d a
2182     Like ‘cons’, but with interchanged arguments.  Useful mostly when
2183     passed to higher-order procedures.
2184
2185 -- Scheme Procedure: list-tabulate n init-proc
2186     Return an N-element list, where each list element is produced by
2187     applying the procedure INIT-PROC to the corresponding list index.
2188     The order in which INIT-PROC is applied to the indices is not
2189     specified.
2190
2191 -- Scheme Procedure: list-copy lst
2192     Return a new list containing the elements of the list LST.
2193
2194     This function differs from the core ‘list-copy’ (*note List
2195     Constructors::) in accepting improper lists too.  And if LST is not
2196     a pair at all then it’s treated as the final tail of an improper
2197     list and simply returned.
2198
2199 -- Scheme Procedure: circular-list elt1 elt2 ...
2200     Return a circular list containing the given arguments ELT1 ELT2
2201     ....
2202
2203 -- Scheme Procedure: iota count [start step]
2204     Return a list containing COUNT numbers, starting from START and
2205     adding STEP each time.  The default START is 0, the default STEP is
2206     1.  For example,
2207
2208          (iota 6)        ⇒ (0 1 2 3 4 5)
2209          (iota 4 2.5 -2) ⇒ (2.5 0.5 -1.5 -3.5)
2210
2211     This function takes its name from the corresponding primitive in
2212     the APL language.
2213
2214
2215File: guile.info,  Node: SRFI-1 Predicates,  Next: SRFI-1 Selectors,  Prev: SRFI-1 Constructors,  Up: SRFI-1
2216
22177.5.3.2 Predicates
2218..................
2219
2220The procedures in this section test specific properties of lists.
2221
2222 -- Scheme Procedure: proper-list? obj
2223     Return ‘#t’ if OBJ is a proper list, or ‘#f’ otherwise.  This is
2224     the same as the core ‘list?’ (*note List Predicates::).
2225
2226     A proper list is a list which ends with the empty list ‘()’ in the
2227     usual way.  The empty list ‘()’ itself is a proper list too.
2228
2229          (proper-list? '(1 2 3))  ⇒ #t
2230          (proper-list? '())       ⇒ #t
2231
2232 -- Scheme Procedure: circular-list? obj
2233     Return ‘#t’ if OBJ is a circular list, or ‘#f’ otherwise.
2234
2235     A circular list is a list where at some point the ‘cdr’ refers back
2236     to a previous pair in the list (either the start or some later
2237     point), so that following the ‘cdr’s takes you around in a circle,
2238     with no end.
2239
2240          (define x (list 1 2 3 4))
2241          (set-cdr! (last-pair x) (cddr x))
2242          x ⇒ (1 2 3 4 3 4 3 4 ...)
2243          (circular-list? x)  ⇒ #t
2244
2245 -- Scheme Procedure: dotted-list? obj
2246     Return ‘#t’ if OBJ is a dotted list, or ‘#f’ otherwise.
2247
2248     A dotted list is a list where the ‘cdr’ of the last pair is not the
2249     empty list ‘()’.  Any non-pair OBJ is also considered a dotted
2250     list, with length zero.
2251
2252          (dotted-list? '(1 2 . 3))  ⇒ #t
2253          (dotted-list? 99)          ⇒ #t
2254
2255   It will be noted that any Scheme object passes exactly one of the
2256above three tests ‘proper-list?’, ‘circular-list?’ and ‘dotted-list?’.
2257Non-lists are ‘dotted-list?’, finite lists are either ‘proper-list?’ or
2258‘dotted-list?’, and infinite lists are ‘circular-list?’.
2259
2260
2261 -- Scheme Procedure: null-list? lst
2262     Return ‘#t’ if LST is the empty list ‘()’, ‘#f’ otherwise.  If
2263     something else than a proper or circular list is passed as LST, an
2264     error is signalled.  This procedure is recommended for checking for
2265     the end of a list in contexts where dotted lists are not allowed.
2266
2267 -- Scheme Procedure: not-pair? obj
2268     Return ‘#t’ is OBJ is not a pair, ‘#f’ otherwise.  This is
2269     shorthand notation ‘(not (pair? OBJ))’ and is supposed to be used
2270     for end-of-list checking in contexts where dotted lists are
2271     allowed.
2272
2273 -- Scheme Procedure: list= elt= list1 ...
2274     Return ‘#t’ if all argument lists are equal, ‘#f’ otherwise.  List
2275     equality is determined by testing whether all lists have the same
2276     length and the corresponding elements are equal in the sense of the
2277     equality predicate ELT=.  If no or only one list is given, ‘#t’ is
2278     returned.
2279
2280
2281File: guile.info,  Node: SRFI-1 Selectors,  Next: SRFI-1 Length Append etc,  Prev: SRFI-1 Predicates,  Up: SRFI-1
2282
22837.5.3.3 Selectors
2284.................
2285
2286 -- Scheme Procedure: first pair
2287 -- Scheme Procedure: second pair
2288 -- Scheme Procedure: third pair
2289 -- Scheme Procedure: fourth pair
2290 -- Scheme Procedure: fifth pair
2291 -- Scheme Procedure: sixth pair
2292 -- Scheme Procedure: seventh pair
2293 -- Scheme Procedure: eighth pair
2294 -- Scheme Procedure: ninth pair
2295 -- Scheme Procedure: tenth pair
2296     These are synonyms for ‘car’, ‘cadr’, ‘caddr’, ....
2297
2298 -- Scheme Procedure: car+cdr pair
2299     Return two values, the CAR and the CDR of PAIR.
2300
2301 -- Scheme Procedure: take lst i
2302 -- Scheme Procedure: take! lst i
2303     Return a list containing the first I elements of LST.
2304
2305     ‘take!’ may modify the structure of the argument list LST in order
2306     to produce the result.
2307
2308 -- Scheme Procedure: drop lst i
2309     Return a list containing all but the first I elements of LST.
2310
2311 -- Scheme Procedure: take-right lst i
2312     Return a list containing the I last elements of LST.  The return
2313     shares a common tail with LST.
2314
2315 -- Scheme Procedure: drop-right lst i
2316 -- Scheme Procedure: drop-right! lst i
2317     Return a list containing all but the I last elements of LST.
2318
2319     ‘drop-right’ always returns a new list, even when I is zero.
2320     ‘drop-right!’ may modify the structure of the argument list LST in
2321     order to produce the result.
2322
2323 -- Scheme Procedure: split-at lst i
2324 -- Scheme Procedure: split-at! lst i
2325     Return two values, a list containing the first I elements of the
2326     list LST and a list containing the remaining elements.
2327
2328     ‘split-at!’ may modify the structure of the argument list LST in
2329     order to produce the result.
2330
2331 -- Scheme Procedure: last lst
2332     Return the last element of the non-empty, finite list LST.
2333
2334
2335File: guile.info,  Node: SRFI-1 Length Append etc,  Next: SRFI-1 Fold and Map,  Prev: SRFI-1 Selectors,  Up: SRFI-1
2336
23377.5.3.4 Length, Append, Concatenate, etc.
2338.........................................
2339
2340 -- Scheme Procedure: length+ lst
2341     Return the length of the argument list LST.  When LST is a circular
2342     list, ‘#f’ is returned.
2343
2344 -- Scheme Procedure: concatenate list-of-lists
2345 -- Scheme Procedure: concatenate! list-of-lists
2346     Construct a list by appending all lists in LIST-OF-LISTS.
2347
2348     ‘concatenate!’ may modify the structure of the given lists in order
2349     to produce the result.
2350
2351     ‘concatenate’ is the same as ‘(apply append LIST-OF-LISTS)’.  It
2352     exists because some Scheme implementations have a limit on the
2353     number of arguments a function takes, which the ‘apply’ might
2354     exceed.  In Guile there is no such limit.
2355
2356 -- Scheme Procedure: append-reverse rev-head tail
2357 -- Scheme Procedure: append-reverse! rev-head tail
2358     Reverse REV-HEAD, append TAIL to it, and return the result.  This
2359     is equivalent to ‘(append (reverse REV-HEAD) TAIL)’, but its
2360     implementation is more efficient.
2361
2362          (append-reverse '(1 2 3) '(4 5 6)) ⇒ (3 2 1 4 5 6)
2363
2364     ‘append-reverse!’ may modify REV-HEAD in order to produce the
2365     result.
2366
2367 -- Scheme Procedure: zip lst1 lst2 ...
2368     Return a list as long as the shortest of the argument lists, where
2369     each element is a list.  The first list contains the first elements
2370     of the argument lists, the second list contains the second
2371     elements, and so on.
2372
2373 -- Scheme Procedure: unzip1 lst
2374 -- Scheme Procedure: unzip2 lst
2375 -- Scheme Procedure: unzip3 lst
2376 -- Scheme Procedure: unzip4 lst
2377 -- Scheme Procedure: unzip5 lst
2378     ‘unzip1’ takes a list of lists, and returns a list containing the
2379     first elements of each list, ‘unzip2’ returns two lists, the first
2380     containing the first elements of each lists and the second
2381     containing the second elements of each lists, and so on.
2382
2383 -- Scheme Procedure: count pred lst1 lst2 ...
2384     Return a count of the number of times PRED returns true when called
2385     on elements from the given lists.
2386
2387     PRED is called with N parameters ‘(PRED ELEM1 ... ELEMN )’, each
2388     element being from the corresponding list.  The first call is with
2389     the first element of each list, the second with the second element
2390     from each, and so on.
2391
2392     Counting stops when the end of the shortest list is reached.  At
2393     least one list must be non-circular.
2394
2395
2396File: guile.info,  Node: SRFI-1 Fold and Map,  Next: SRFI-1 Filtering and Partitioning,  Prev: SRFI-1 Length Append etc,  Up: SRFI-1
2397
23987.5.3.5 Fold, Unfold & Map
2399..........................
2400
2401 -- Scheme Procedure: fold proc init lst1 lst2 ...
2402 -- Scheme Procedure: fold-right proc init lst1 lst2 ...
2403     Apply PROC to the elements of LST1 LST2 ... to build a result, and
2404     return that result.
2405
2406     Each PROC call is ‘(PROC ELEM1 ELEM2 ... PREVIOUS)’, where ELEM1 is
2407     from LST1, ELEM2 is from LST2, and so on.  PREVIOUS is the return
2408     from the previous call to PROC, or the given INIT for the first
2409     call.  If any list is empty, just INIT is returned.
2410
2411     ‘fold’ works through the list elements from first to last.  The
2412     following shows a list reversal and the calls it makes,
2413
2414          (fold cons '() '(1 2 3))
2415
2416          (cons 1 '())
2417          (cons 2 '(1))
2418          (cons 3 '(2 1)
2419          ⇒ (3 2 1)
2420
2421     ‘fold-right’ works through the list elements from last to first,
2422     ie. from the right.  So for example the following finds the longest
2423     string, and the last among equal longest,
2424
2425          (fold-right (lambda (str prev)
2426                        (if (> (string-length str) (string-length prev))
2427                            str
2428                            prev))
2429                      ""
2430                      '("x" "abc" "xyz" "jk"))
2431          ⇒ "xyz"
2432
2433     If LST1 LST2 ... have different lengths, ‘fold’ stops when the end
2434     of the shortest is reached; ‘fold-right’ commences at the last
2435     element of the shortest.  Ie. elements past the length of the
2436     shortest are ignored in the other LSTs.  At least one LST must be
2437     non-circular.
2438
2439     ‘fold’ should be preferred over ‘fold-right’ if the order of
2440     processing doesn’t matter, or can be arranged either way, since
2441     ‘fold’ is a little more efficient.
2442
2443     The way ‘fold’ builds a result from iterating is quite general, it
2444     can do more than other iterations like say ‘map’ or ‘filter’.  The
2445     following for example removes adjacent duplicate elements from a
2446     list,
2447
2448          (define (delete-adjacent-duplicates lst)
2449            (fold-right (lambda (elem ret)
2450                          (if (equal? elem (first ret))
2451                              ret
2452                              (cons elem ret)))
2453                        (list (last lst))
2454                        lst))
2455          (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
2456          ⇒ (1 2 3 4 5)
2457
2458     Clearly the same sort of thing can be done with a ‘for-each’ and a
2459     variable in which to build the result, but a self-contained PROC
2460     can be re-used in multiple contexts, where a ‘for-each’ would have
2461     to be written out each time.
2462
2463 -- Scheme Procedure: pair-fold proc init lst1 lst2 ...
2464 -- Scheme Procedure: pair-fold-right proc init lst1 lst2 ...
2465     The same as ‘fold’ and ‘fold-right’, but apply PROC to the pairs of
2466     the lists instead of the list elements.
2467
2468 -- Scheme Procedure: reduce proc default lst
2469 -- Scheme Procedure: reduce-right proc default lst
2470     ‘reduce’ is a variant of ‘fold’, where the first call to PROC is on
2471     two elements from LST, rather than one element and a given initial
2472     value.
2473
2474     If LST is empty, ‘reduce’ returns DEFAULT (this is the only use for
2475     DEFAULT).  If LST has just one element then that’s the return
2476     value.  Otherwise PROC is called on the elements of LST.
2477
2478     Each PROC call is ‘(PROC ELEM PREVIOUS)’, where ELEM is from LST
2479     (the second and subsequent elements of LST), and PREVIOUS is the
2480     return from the previous call to PROC.  The first element of LST is
2481     the PREVIOUS for the first call to PROC.
2482
2483     For example, the following adds a list of numbers, the calls made
2484     to ‘+’ are shown.  (Of course ‘+’ accepts multiple arguments and
2485     can add a list directly, with ‘apply’.)
2486
2487          (reduce + 0 '(5 6 7)) ⇒ 18
2488
2489          (+ 6 5)  ⇒ 11
2490          (+ 7 11) ⇒ 18
2491
2492     ‘reduce’ can be used instead of ‘fold’ where the INIT value is an
2493     “identity”, meaning a value which under PROC doesn’t change the
2494     result, in this case 0 is an identity since ‘(+ 5 0)’ is just 5.
2495     ‘reduce’ avoids that unnecessary call.
2496
2497     ‘reduce-right’ is a similar variation on ‘fold-right’, working from
2498     the end (ie. the right) of LST.  The last element of LST is the
2499     PREVIOUS for the first call to PROC, and the ELEM values go from
2500     the second last.
2501
2502     ‘reduce’ should be preferred over ‘reduce-right’ if the order of
2503     processing doesn’t matter, or can be arranged either way, since
2504     ‘reduce’ is a little more efficient.
2505
2506 -- Scheme Procedure: unfold p f g seed [tail-gen]
2507     ‘unfold’ is defined as follows:
2508
2509          (unfold p f g seed) =
2510             (if (p seed) (tail-gen seed)
2511                 (cons (f seed)
2512                       (unfold p f g (g seed))))
2513
2514     P
2515          Determines when to stop unfolding.
2516
2517     F
2518          Maps each seed value to the corresponding list element.
2519
2520     G
2521          Maps each seed value to next seed value.
2522
2523     SEED
2524          The state value for the unfold.
2525
2526     TAIL-GEN
2527          Creates the tail of the list; defaults to ‘(lambda (x) '())’.
2528
2529     G produces a series of seed values, which are mapped to list
2530     elements by F.  These elements are put into a list in left-to-right
2531     order, and P tells when to stop unfolding.
2532
2533 -- Scheme Procedure: unfold-right p f g seed [tail]
2534     Construct a list with the following loop.
2535
2536          (let lp ((seed seed) (lis tail))
2537             (if (p seed) lis
2538                 (lp (g seed)
2539                     (cons (f seed) lis))))
2540
2541     P
2542          Determines when to stop unfolding.
2543
2544     F
2545          Maps each seed value to the corresponding list element.
2546
2547     G
2548          Maps each seed value to next seed value.
2549
2550     SEED
2551          The state value for the unfold.
2552
2553     TAIL
2554          The tail of the list; defaults to ‘'()’.
2555
2556 -- Scheme Procedure: map f lst1 lst2 ...
2557     Map the procedure over the list(s) LST1, LST2, ... and return a
2558     list containing the results of the procedure applications.  This
2559     procedure is extended with respect to R5RS, because the argument
2560     lists may have different lengths.  The result list will have the
2561     same length as the shortest argument lists.  The order in which F
2562     will be applied to the list element(s) is not specified.
2563
2564 -- Scheme Procedure: for-each f lst1 lst2 ...
2565     Apply the procedure F to each pair of corresponding elements of the
2566     list(s) LST1, LST2, ....  The return value is not specified.  This
2567     procedure is extended with respect to R5RS, because the argument
2568     lists may have different lengths.  The shortest argument list
2569     determines the number of times F is called.  F will be applied to
2570     the list elements in left-to-right order.
2571
2572 -- Scheme Procedure: append-map f lst1 lst2 ...
2573 -- Scheme Procedure: append-map! f lst1 lst2 ...
2574     Equivalent to
2575
2576          (apply append (map f clist1 clist2 ...))
2577
2578     and
2579
2580          (apply append! (map f clist1 clist2 ...))
2581
2582     Map F over the elements of the lists, just as in the ‘map’
2583     function.  However, the results of the applications are appended
2584     together to make the final result.  ‘append-map’ uses ‘append’ to
2585     append the results together; ‘append-map!’ uses ‘append!’.
2586
2587     The dynamic order in which the various applications of F are made
2588     is not specified.
2589
2590 -- Scheme Procedure: map! f lst1 lst2 ...
2591     Linear-update variant of ‘map’ – ‘map!’ is allowed, but not
2592     required, to alter the cons cells of LST1 to construct the result
2593     list.
2594
2595     The dynamic order in which the various applications of F are made
2596     is not specified.  In the n-ary case, LST2, LST3, ... must have at
2597     least as many elements as LST1.
2598
2599 -- Scheme Procedure: pair-for-each f lst1 lst2 ...
2600     Like ‘for-each’, but applies the procedure F to the pairs from
2601     which the argument lists are constructed, instead of the list
2602     elements.  The return value is not specified.
2603
2604 -- Scheme Procedure: filter-map f lst1 lst2 ...
2605     Like ‘map’, but only results from the applications of F which are
2606     true are saved in the result list.
2607
2608
2609File: guile.info,  Node: SRFI-1 Filtering and Partitioning,  Next: SRFI-1 Searching,  Prev: SRFI-1 Fold and Map,  Up: SRFI-1
2610
26117.5.3.6 Filtering and Partitioning
2612..................................
2613
2614Filtering means to collect all elements from a list which satisfy a
2615specific condition.  Partitioning a list means to make two groups of
2616list elements, one which contains the elements satisfying a condition,
2617and the other for the elements which don’t.
2618
2619   The ‘filter’ and ‘filter!’ functions are implemented in the Guile
2620core, *Note List Modification::.
2621
2622 -- Scheme Procedure: partition pred lst
2623 -- Scheme Procedure: partition! pred lst
2624     Split LST into those elements which do and don’t satisfy the
2625     predicate PRED.
2626
2627     The return is two values (*note Multiple Values::), the first being
2628     a list of all elements from LST which satisfy PRED, the second a
2629     list of those which do not.
2630
2631     The elements in the result lists are in the same order as in LST
2632     but the order in which the calls ‘(PRED elem)’ are made on the list
2633     elements is unspecified.
2634
2635     ‘partition’ does not change LST, but one of the returned lists may
2636     share a tail with it.  ‘partition!’ may modify LST to construct its
2637     return.
2638
2639 -- Scheme Procedure: remove pred lst
2640 -- Scheme Procedure: remove! pred lst
2641     Return a list containing all elements from LST which do not satisfy
2642     the predicate PRED.  The elements in the result list have the same
2643     order as in LST.  The order in which PRED is applied to the list
2644     elements is not specified.
2645
2646     ‘remove!’ is allowed, but not required to modify the structure of
2647     the input list.
2648
2649
2650File: guile.info,  Node: SRFI-1 Searching,  Next: SRFI-1 Deleting,  Prev: SRFI-1 Filtering and Partitioning,  Up: SRFI-1
2651
26527.5.3.7 Searching
2653.................
2654
2655The procedures for searching elements in lists either accept a predicate
2656or a comparison object for determining which elements are to be
2657searched.
2658
2659 -- Scheme Procedure: find pred lst
2660     Return the first element of LST that satisfies the predicate PRED
2661     and ‘#f’ if no such element is found.
2662
2663 -- Scheme Procedure: find-tail pred lst
2664     Return the first pair of LST whose CAR satisfies the predicate PRED
2665     and ‘#f’ if no such element is found.
2666
2667 -- Scheme Procedure: take-while pred lst
2668 -- Scheme Procedure: take-while! pred lst
2669     Return the longest initial prefix of LST whose elements all satisfy
2670     the predicate PRED.
2671
2672     ‘take-while!’ is allowed, but not required to modify the input list
2673     while producing the result.
2674
2675 -- Scheme Procedure: drop-while pred lst
2676     Drop the longest initial prefix of LST whose elements all satisfy
2677     the predicate PRED.
2678
2679 -- Scheme Procedure: span pred lst
2680 -- Scheme Procedure: span! pred lst
2681 -- Scheme Procedure: break pred lst
2682 -- Scheme Procedure: break! pred lst
2683     ‘span’ splits the list LST into the longest initial prefix whose
2684     elements all satisfy the predicate PRED, and the remaining tail.
2685     ‘break’ inverts the sense of the predicate.
2686
2687     ‘span!’ and ‘break!’ are allowed, but not required to modify the
2688     structure of the input list LST in order to produce the result.
2689
2690     Note that the name ‘break’ conflicts with the ‘break’ binding
2691     established by ‘while’ (*note while do::).  Applications wanting to
2692     use ‘break’ from within a ‘while’ loop will need to make a new
2693     define under a different name.
2694
2695 -- Scheme Procedure: any pred lst1 lst2 ...
2696     Test whether any set of elements from LST1 LST2 ... satisfies PRED.
2697     If so, the return value is the return value from the successful
2698     PRED call, or if not, the return value is ‘#f’.
2699
2700     If there are n list arguments, then PRED must be a predicate taking
2701     n arguments.  Each PRED call is ‘(PRED ELEM1 ELEM2 ... )’ taking an
2702     element from each LST.  The calls are made successively for the
2703     first, second, etc.  elements of the lists, stopping when PRED
2704     returns non-‘#f’, or when the end of the shortest list is reached.
2705
2706     The PRED call on the last set of elements (i.e., when the end of
2707     the shortest list has been reached), if that point is reached, is a
2708     tail call.
2709
2710 -- Scheme Procedure: every pred lst1 lst2 ...
2711     Test whether every set of elements from LST1 LST2 ... satisfies
2712     PRED.  If so, the return value is the return from the final PRED
2713     call, or if not, the return value is ‘#f’.
2714
2715     If there are n list arguments, then PRED must be a predicate taking
2716     n arguments.  Each PRED call is ‘(PRED ELEM1 ELEM2 ...)’ taking an
2717     element from each LST.  The calls are made successively for the
2718     first, second, etc.  elements of the lists, stopping if PRED
2719     returns ‘#f’, or when the end of any of the lists is reached.
2720
2721     The PRED call on the last set of elements (i.e., when the end of
2722     the shortest list has been reached) is a tail call.
2723
2724     If one of LST1 LST2 ...is empty then no calls to PRED are made, and
2725     the return value is ‘#t’.
2726
2727 -- Scheme Procedure: list-index pred lst1 lst2 ...
2728     Return the index of the first set of elements, one from each of
2729     LST1 LST2 ..., which satisfies PRED.
2730
2731     PRED is called as ‘(ELEM1 ELEM2 ...)’.  Searching stops when the
2732     end of the shortest LST is reached.  The return index starts from 0
2733     for the first set of elements.  If no set of elements pass, then
2734     the return value is ‘#f’.
2735
2736          (list-index odd? '(2 4 6 9))      ⇒ 3
2737          (list-index = '(1 2 3) '(3 1 2))  ⇒ #f
2738
2739 -- Scheme Procedure: member x lst [=]
2740     Return the first sublist of LST whose CAR is equal to X.  If X does
2741     not appear in LST, return ‘#f’.
2742
2743     Equality is determined by ‘equal?’, or by the equality predicate =
2744     if given.  = is called ‘(= X elem)’, ie. with the given X first, so
2745     for example to find the first element greater than 5,
2746
2747          (member 5 '(3 5 1 7 2 9) <) ⇒ (7 2 9)
2748
2749     This version of ‘member’ extends the core ‘member’ (*note List
2750     Searching::) by accepting an equality predicate.
2751
2752
2753File: guile.info,  Node: SRFI-1 Deleting,  Next: SRFI-1 Association Lists,  Prev: SRFI-1 Searching,  Up: SRFI-1
2754
27557.5.3.8 Deleting
2756................
2757
2758 -- Scheme Procedure: delete x lst [=]
2759 -- Scheme Procedure: delete! x lst [=]
2760     Return a list containing the elements of LST but with those equal
2761     to X deleted.  The returned elements will be in the same order as
2762     they were in LST.
2763
2764     Equality is determined by the = predicate, or ‘equal?’ if not
2765     given.  An equality call is made just once for each element, but
2766     the order in which the calls are made on the elements is
2767     unspecified.
2768
2769     The equality calls are always ‘(= x elem)’, ie. the given X is
2770     first.  This means for instance elements greater than 5 can be
2771     deleted with ‘(delete 5 lst <)’.
2772
2773     ‘delete’ does not modify LST, but the return might share a common
2774     tail with LST.  ‘delete!’ may modify the structure of LST to
2775     construct its return.
2776
2777     These functions extend the core ‘delete’ and ‘delete!’ (*note List
2778     Modification::) in accepting an equality predicate.  See also
2779     ‘lset-difference’ (*note SRFI-1 Set Operations::) for deleting
2780     multiple elements from a list.
2781
2782 -- Scheme Procedure: delete-duplicates lst [=]
2783 -- Scheme Procedure: delete-duplicates! lst [=]
2784     Return a list containing the elements of LST but without
2785     duplicates.
2786
2787     When elements are equal, only the first in LST is retained.  Equal
2788     elements can be anywhere in LST, they don’t have to be adjacent.
2789     The returned list will have the retained elements in the same order
2790     as they were in LST.
2791
2792     Equality is determined by the = predicate, or ‘equal?’ if not
2793     given.  Calls ‘(= x y)’ are made with element X being before Y in
2794     LST.  A call is made at most once for each combination, but the
2795     sequence of the calls across the elements is unspecified.
2796
2797     ‘delete-duplicates’ does not modify LST, but the return might share
2798     a common tail with LST.  ‘delete-duplicates!’ may modify the
2799     structure of LST to construct its return.
2800
2801     In the worst case, this is an O(N^2) algorithm because it must
2802     check each element against all those preceding it.  For long lists
2803     it is more efficient to sort and then compare only adjacent
2804     elements.
2805
2806
2807File: guile.info,  Node: SRFI-1 Association Lists,  Next: SRFI-1 Set Operations,  Prev: SRFI-1 Deleting,  Up: SRFI-1
2808
28097.5.3.9 Association Lists
2810.........................
2811
2812Association lists are described in detail in section *note Association
2813Lists::.  The present section only documents the additional procedures
2814for dealing with association lists defined by SRFI-1.
2815
2816 -- Scheme Procedure: assoc key alist [=]
2817     Return the pair from ALIST which matches KEY.  This extends the
2818     core ‘assoc’ (*note Retrieving Alist Entries::) by taking an
2819     optional = comparison procedure.
2820
2821     The default comparison is ‘equal?’.  If an = parameter is given
2822     it’s called ‘(= KEY ALISTCAR)’, i.e. the given target KEY is the
2823     first argument, and a ‘car’ from ALIST is second.
2824
2825     For example a case-insensitive string lookup,
2826
2827          (assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
2828          ⇒ ("YY" . 2)
2829
2830 -- Scheme Procedure: alist-cons key datum alist
2831     Cons a new association KEY and DATUM onto ALIST and return the
2832     result.  This is equivalent to
2833
2834          (cons (cons KEY DATUM) ALIST)
2835
2836     ‘acons’ (*note Adding or Setting Alist Entries::) in the Guile core
2837     does the same thing.
2838
2839 -- Scheme Procedure: alist-copy alist
2840     Return a newly allocated copy of ALIST, that means that the spine
2841     of the list as well as the pairs are copied.
2842
2843 -- Scheme Procedure: alist-delete key alist [=]
2844 -- Scheme Procedure: alist-delete! key alist [=]
2845     Return a list containing the elements of ALIST but with those
2846     elements whose keys are equal to KEY deleted.  The returned
2847     elements will be in the same order as they were in ALIST.
2848
2849     Equality is determined by the = predicate, or ‘equal?’ if not
2850     given.  The order in which elements are tested is unspecified, but
2851     each equality call is made ‘(= key alistkey)’, i.e. the given KEY
2852     parameter is first and the key from ALIST second.  This means for
2853     instance all associations with a key greater than 5 can be removed
2854     with ‘(alist-delete 5 alist <)’.
2855
2856     ‘alist-delete’ does not modify ALIST, but the return might share a
2857     common tail with ALIST.  ‘alist-delete!’ may modify the list
2858     structure of ALIST to construct its return.
2859
2860
2861File: guile.info,  Node: SRFI-1 Set Operations,  Prev: SRFI-1 Association Lists,  Up: SRFI-1
2862
28637.5.3.10 Set Operations on Lists
2864................................
2865
2866Lists can be used to represent sets of objects.  The procedures in this
2867section operate on such lists as sets.
2868
2869   Note that lists are not an efficient way to implement large sets.
2870The procedures here typically take time MxN when operating on M and N
2871element lists.  Other data structures like trees, bitsets (*note Bit
2872Vectors::) or hash tables (*note Hash Tables::) are faster.
2873
2874   All these procedures take an equality predicate as the first
2875argument.  This predicate is used for testing the objects in the list
2876sets for sameness.  This predicate must be consistent with ‘eq?’ (*note
2877Equality::) in the sense that if two list elements are ‘eq?’ then they
2878must also be equal under the predicate.  This simply means a given
2879object must be equal to itself.
2880
2881 -- Scheme Procedure: lset<= = list ...
2882     Return ‘#t’ if each list is a subset of the one following it.
2883     I.e., LIST1 is a subset of LIST2, LIST2 is a subset of LIST3, etc.,
2884     for as many lists as given.  If only one list or no lists are
2885     given, the return value is ‘#t’.
2886
2887     A list X is a subset of Y if each element of X is equal to some
2888     element in Y.  Elements are compared using the given = procedure,
2889     called as ‘(= xelem yelem)’.
2890
2891          (lset<= eq?)                      ⇒ #t
2892          (lset<= eqv? '(1 2 3) '(1))       ⇒ #f
2893          (lset<= eqv? '(1 3 2) '(4 3 1 2)) ⇒ #t
2894
2895 -- Scheme Procedure: lset= = list ...
2896     Return ‘#t’ if all argument lists are set-equal.  LIST1 is compared
2897     to LIST2, LIST2 to LIST3, etc., for as many lists as given.  If
2898     only one list or no lists are given, the return value is ‘#t’.
2899
2900     Two lists X and Y are set-equal if each element of X is equal to
2901     some element of Y and conversely each element of Y is equal to some
2902     element of X.  The order of the elements in the lists doesn’t
2903     matter.  Element equality is determined with the given = procedure,
2904     called as ‘(= xelem yelem)’, but exactly which calls are made is
2905     unspecified.
2906
2907          (lset= eq?)                      ⇒ #t
2908          (lset= eqv? '(1 2 3) '(3 2 1))   ⇒ #t
2909          (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) ⇒ #t
2910
2911 -- Scheme Procedure: lset-adjoin = list elem ...
2912     Add to LIST any of the given ELEMs not already in the list.  ELEMs
2913     are ‘cons’ed onto the start of LIST (so the return value shares a
2914     common tail with LIST), but the order that the ELEMs are added is
2915     unspecified.
2916
2917     The given = procedure is used for comparing elements, called as ‘(=
2918     listelem elem)’, i.e., the second argument is one of the given ELEM
2919     parameters.
2920
2921          (lset-adjoin eqv? '(1 2 3) 4 1 5) ⇒ (5 4 1 2 3)
2922
2923 -- Scheme Procedure: lset-union = list ...
2924 -- Scheme Procedure: lset-union! = list ...
2925     Return the union of the argument list sets.  The result is built by
2926     taking the union of LIST1 and LIST2, then the union of that with
2927     LIST3, etc., for as many lists as given.  For one list argument
2928     that list itself is the result, for no list arguments the result is
2929     the empty list.
2930
2931     The union of two lists X and Y is formed as follows.  If X is empty
2932     then the result is Y.  Otherwise start with X as the result and
2933     consider each Y element (from first to last).  A Y element not
2934     equal to something already in the result is ‘cons’ed onto the
2935     result.
2936
2937     The given = procedure is used for comparing elements, called as ‘(=
2938     relem yelem)’.  The first argument is from the result accumulated
2939     so far, and the second is from the list being union-ed in.  But
2940     exactly which calls are made is otherwise unspecified.
2941
2942     Notice that duplicate elements in LIST1 (or the first non-empty
2943     list) are preserved, but that repeated elements in subsequent lists
2944     are only added once.
2945
2946          (lset-union eqv?)                          ⇒ ()
2947          (lset-union eqv? '(1 2 3))                 ⇒ (1 2 3)
2948          (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) ⇒ (5 4 1 2 1 3)
2949
2950     ‘lset-union’ doesn’t change the given lists but the result may
2951     share a tail with the first non-empty list.  ‘lset-union!’ can
2952     modify all of the given lists to form the result.
2953
2954 -- Scheme Procedure: lset-intersection = list1 list2 ...
2955 -- Scheme Procedure: lset-intersection! = list1 list2 ...
2956     Return the intersection of LIST1 with the other argument lists,
2957     meaning those elements of LIST1 which are also in all of LIST2 etc.
2958     For one list argument, just that list is returned.
2959
2960     The test for an element of LIST1 to be in the return is simply that
2961     it’s equal to some element in each of LIST2 etc.  Notice this means
2962     an element appearing twice in LIST1 but only once in each of LIST2
2963     etc will go into the return twice.  The return has its elements in
2964     the same order as they were in LIST1.
2965
2966     The given = procedure is used for comparing elements, called as ‘(=
2967     elem1 elemN)’.  The first argument is from LIST1 and the second is
2968     from one of the subsequent lists.  But exactly which calls are made
2969     and in what order is unspecified.
2970
2971          (lset-intersection eqv? '(x y))                        ⇒ (x y)
2972          (lset-intersection eqv? '(1 2 3) '(4 3 2))             ⇒ (2 3)
2973          (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) ⇒ (2 2)
2974
2975     The return from ‘lset-intersection’ may share a tail with LIST1.
2976     ‘lset-intersection!’ may modify LIST1 to form its result.
2977
2978 -- Scheme Procedure: lset-difference = list1 list2 ...
2979 -- Scheme Procedure: lset-difference! = list1 list2 ...
2980     Return LIST1 with any elements in LIST2, LIST3 etc removed (ie.
2981     subtracted).  For one list argument, just that list is returned.
2982
2983     The given = procedure is used for comparing elements, called as ‘(=
2984     elem1 elemN)’.  The first argument is from LIST1 and the second
2985     from one of the subsequent lists.  But exactly which calls are made
2986     and in what order is unspecified.
2987
2988          (lset-difference eqv? '(x y))             ⇒ (x y)
2989          (lset-difference eqv? '(1 2 3) '(3 1))    ⇒ (2)
2990          (lset-difference eqv? '(1 2 3) '(3) '(2)) ⇒ (1)
2991
2992     The return from ‘lset-difference’ may share a tail with LIST1.
2993     ‘lset-difference!’ may modify LIST1 to form its result.
2994
2995 -- Scheme Procedure: lset-diff+intersection = list1 list2 ...
2996 -- Scheme Procedure: lset-diff+intersection! = list1 list2 ...
2997     Return two values (*note Multiple Values::), the difference and
2998     intersection of the argument lists as per ‘lset-difference’ and
2999     ‘lset-intersection’ above.
3000
3001     For two list arguments this partitions LIST1 into those elements of
3002     LIST1 which are in LIST2 and not in LIST2.  (But for more than two
3003     arguments there can be elements of LIST1 which are neither part of
3004     the difference nor the intersection.)
3005
3006     One of the return values from ‘lset-diff+intersection’ may share a
3007     tail with LIST1.  ‘lset-diff+intersection!’ may modify LIST1 to
3008     form its results.
3009
3010 -- Scheme Procedure: lset-xor = list ...
3011 -- Scheme Procedure: lset-xor! = list ...
3012     Return an XOR of the argument lists.  For two lists this means
3013     those elements which are in exactly one of the lists.  For more
3014     than two lists it means those elements which appear in an odd
3015     number of the lists.
3016
3017     To be precise, the XOR of two lists X and Y is formed by taking
3018     those elements of X not equal to any element of Y, plus those
3019     elements of Y not equal to any element of X.  Equality is
3020     determined with the given = procedure, called as ‘(= e1 e2)’.  One
3021     argument is from X and the other from Y, but which way around is
3022     unspecified.  Exactly which calls are made is also unspecified, as
3023     is the order of the elements in the result.
3024
3025          (lset-xor eqv? '(x y))             ⇒ (x y)
3026          (lset-xor eqv? '(1 2 3) '(4 3 2))  ⇒ (4 1)
3027
3028     The return from ‘lset-xor’ may share a tail with one of the list
3029     arguments.  ‘lset-xor!’ may modify LIST1 to form its result.
3030
3031
3032File: guile.info,  Node: SRFI-2,  Next: SRFI-4,  Prev: SRFI-1,  Up: SRFI Support
3033
30347.5.4 SRFI-2 - and-let*
3035-----------------------
3036
3037The following syntax can be obtained with
3038
3039     (use-modules (srfi srfi-2))
3040
3041   or alternatively
3042
3043     (use-modules (ice-9 and-let-star))
3044
3045 -- library syntax: and-let* (clause ...) body ...
3046     A combination of ‘and’ and ‘let*’.
3047
3048     Each CLAUSE is evaluated in turn, and if ‘#f’ is obtained then
3049     evaluation stops and ‘#f’ is returned.  If all are non-‘#f’ then
3050     BODY is evaluated and the last form gives the return value, or if
3051     BODY is empty then the result is ‘#t’.  Each CLAUSE should be one
3052     of the following,
3053
3054     ‘(symbol expr)’
3055          Evaluate EXPR, check for ‘#f’, and bind it to SYMBOL.  Like
3056          ‘let*’, that binding is available to subsequent clauses.
3057     ‘(expr)’
3058          Evaluate EXPR and check for ‘#f’.
3059     ‘symbol’
3060          Get the value bound to SYMBOL and check for ‘#f’.
3061
3062     Notice that ‘(expr)’ has an “extra” pair of parentheses, for
3063     instance ‘((eq? x y))’.  One way to remember this is to imagine the
3064     ‘symbol’ in ‘(symbol expr)’ is omitted.
3065
3066     ‘and-let*’ is good for calculations where a ‘#f’ value means
3067     termination, but where a non-‘#f’ value is going to be needed in
3068     subsequent expressions.
3069
3070     The following illustrates this, it returns text between brackets
3071     ‘[...]’ in a string, or ‘#f’ if there are no such brackets (ie.
3072     either ‘string-index’ gives ‘#f’).
3073
3074          (define (extract-brackets str)
3075            (and-let* ((start (string-index str #\[))
3076                       (end   (string-index str #\] start)))
3077              (substring str (1+ start) end)))
3078
3079     The following shows plain variables and expressions tested too.
3080     ‘diagnostic-levels’ is taken to be an alist associating a
3081     diagnostic type with a level.  ‘str’ is printed only if the type is
3082     known and its level is high enough.
3083
3084          (define (show-diagnostic type str)
3085            (and-let* (want-diagnostics
3086                       (level (assq-ref diagnostic-levels type))
3087                       ((>= level current-diagnostic-level)))
3088              (display str)))
3089
3090     The advantage of ‘and-let*’ is that an extended sequence of
3091     expressions and tests doesn’t require lots of nesting as would
3092     arise from separate ‘and’ and ‘let*’, or from ‘cond’ with ‘=>’.
3093
3094
3095File: guile.info,  Node: SRFI-4,  Next: SRFI-6,  Prev: SRFI-2,  Up: SRFI Support
3096
30977.5.5 SRFI-4 - Homogeneous numeric vector datatypes
3098---------------------------------------------------
3099
3100SRFI-4 provides an interface to uniform numeric vectors: vectors whose
3101elements are all of a single numeric type.  Guile offers uniform numeric
3102vectors for signed and unsigned 8-bit, 16-bit, 32-bit, and 64-bit
3103integers, two sizes of floating point values, and, as an extension to
3104SRFI-4, complex floating-point numbers of these two sizes.
3105
3106   The standard SRFI-4 procedures and data types may be included via
3107loading the appropriate module:
3108
3109     (use-modules (srfi srfi-4))
3110
3111   This module is currently a part of the default Guile environment, but
3112it is a good practice to explicitly import the module.  In the future,
3113using SRFI-4 procedures without importing the SRFI-4 module will cause a
3114deprecation message to be printed.  (Of course, one may call the C
3115functions at any time.  Would that C had modules!)
3116
3117* Menu:
3118
3119* SRFI-4 Overview::             The warp and weft of uniform numeric vectors.
3120* SRFI-4 API::                  Uniform vectors, from Scheme and from C.
3121* SRFI-4 and Bytevectors::      SRFI-4 vectors are backed by bytevectors.
3122* SRFI-4 Extensions::           Guile-specific extensions to the standard.
3123
3124
3125File: guile.info,  Node: SRFI-4 Overview,  Next: SRFI-4 API,  Up: SRFI-4
3126
31277.5.5.1 SRFI-4 - Overview
3128.........................
3129
3130Uniform numeric vectors can be useful since they consume less memory
3131than the non-uniform, general vectors.  Also, since the types they can
3132store correspond directly to C types, it is easier to work with them
3133efficiently on a low level.  Consider image processing as an example,
3134where you want to apply a filter to some image.  While you could store
3135the pixels of an image in a general vector and write a general
3136convolution function, things are much more efficient with uniform
3137vectors: the convolution function knows that all pixels are unsigned
31388-bit values (say), and can use a very tight inner loop.
3139
3140   This is implemented in Scheme by having the compiler notice calls to
3141the SRFI-4 accessors, and inline them to appropriate compiled code.
3142From C you have access to the raw array; functions for efficiently
3143working with uniform numeric vectors from C are listed at the end of
3144this section.
3145
3146   Uniform numeric vectors are the special case of one dimensional
3147uniform numeric arrays.
3148
3149   There are 12 standard kinds of uniform numeric vectors, and they all
3150have their own complement of constructors, accessors, and so on.
3151Procedures that operate on a specific kind of uniform numeric vector
3152have a “tag” in their name, indicating the element type.
3153
3154u8
3155     unsigned 8-bit integers
3156
3157s8
3158     signed 8-bit integers
3159
3160u16
3161     unsigned 16-bit integers
3162
3163s16
3164     signed 16-bit integers
3165
3166u32
3167     unsigned 32-bit integers
3168
3169s32
3170     signed 32-bit integers
3171
3172u64
3173     unsigned 64-bit integers
3174
3175s64
3176     signed 64-bit integers
3177
3178f32
3179     the C type ‘float’
3180
3181f64
3182     the C type ‘double’
3183
3184   In addition, Guile supports uniform arrays of complex numbers, with
3185the nonstandard tags:
3186
3187c32
3188     complex numbers in rectangular form with the real and imaginary
3189     part being a ‘float’
3190
3191c64
3192     complex numbers in rectangular form with the real and imaginary
3193     part being a ‘double’
3194
3195   The external representation (ie. read syntax) for these vectors is
3196similar to normal Scheme vectors, but with an additional tag from the
3197tables above indicating the vector’s type.  For example,
3198
3199     #u16(1 2 3)
3200     #f64(3.1415 2.71)
3201
3202   Note that the read syntax for floating-point here conflicts with ‘#f’
3203for false.  In Standard Scheme one can write ‘(1 #f3)’ for a three
3204element list ‘(1 #f 3)’, but for Guile ‘(1 #f3)’ is invalid.  ‘(1 #f 3)’
3205is almost certainly what one should write anyway to make the intention
3206clear, so this is rarely a problem.
3207
3208
3209File: guile.info,  Node: SRFI-4 API,  Next: SRFI-4 and Bytevectors,  Prev: SRFI-4 Overview,  Up: SRFI-4
3210
32117.5.5.2 SRFI-4 - API
3212....................
3213
3214Note that the c32 and c64 functions are only available from (srfi srfi-4
3215gnu).
3216
3217 -- Scheme Procedure: u8vector? obj
3218 -- Scheme Procedure: s8vector? obj
3219 -- Scheme Procedure: u16vector? obj
3220 -- Scheme Procedure: s16vector? obj
3221 -- Scheme Procedure: u32vector? obj
3222 -- Scheme Procedure: s32vector? obj
3223 -- Scheme Procedure: u64vector? obj
3224 -- Scheme Procedure: s64vector? obj
3225 -- Scheme Procedure: f32vector? obj
3226 -- Scheme Procedure: f64vector? obj
3227 -- Scheme Procedure: c32vector? obj
3228 -- Scheme Procedure: c64vector? obj
3229 -- C Function: scm_u8vector_p (obj)
3230 -- C Function: scm_s8vector_p (obj)
3231 -- C Function: scm_u16vector_p (obj)
3232 -- C Function: scm_s16vector_p (obj)
3233 -- C Function: scm_u32vector_p (obj)
3234 -- C Function: scm_s32vector_p (obj)
3235 -- C Function: scm_u64vector_p (obj)
3236 -- C Function: scm_s64vector_p (obj)
3237 -- C Function: scm_f32vector_p (obj)
3238 -- C Function: scm_f64vector_p (obj)
3239 -- C Function: scm_c32vector_p (obj)
3240 -- C Function: scm_c64vector_p (obj)
3241     Return ‘#t’ if OBJ is a homogeneous numeric vector of the indicated
3242     type.
3243
3244 -- Scheme Procedure: make-u8vector n [value]
3245 -- Scheme Procedure: make-s8vector n [value]
3246 -- Scheme Procedure: make-u16vector n [value]
3247 -- Scheme Procedure: make-s16vector n [value]
3248 -- Scheme Procedure: make-u32vector n [value]
3249 -- Scheme Procedure: make-s32vector n [value]
3250 -- Scheme Procedure: make-u64vector n [value]
3251 -- Scheme Procedure: make-s64vector n [value]
3252 -- Scheme Procedure: make-f32vector n [value]
3253 -- Scheme Procedure: make-f64vector n [value]
3254 -- Scheme Procedure: make-c32vector n [value]
3255 -- Scheme Procedure: make-c64vector n [value]
3256 -- C Function: scm_make_u8vector (n, value)
3257 -- C Function: scm_make_s8vector (n, value)
3258 -- C Function: scm_make_u16vector (n, value)
3259 -- C Function: scm_make_s16vector (n, value)
3260 -- C Function: scm_make_u32vector (n, value)
3261 -- C Function: scm_make_s32vector (n, value)
3262 -- C Function: scm_make_u64vector (n, value)
3263 -- C Function: scm_make_s64vector (n, value)
3264 -- C Function: scm_make_f32vector (n, value)
3265 -- C Function: scm_make_f64vector (n, value)
3266 -- C Function: scm_make_c32vector (n, value)
3267 -- C Function: scm_make_c64vector (n, value)
3268     Return a newly allocated homogeneous numeric vector holding N
3269     elements of the indicated type.  If VALUE is given, the vector is
3270     initialized with that value, otherwise the contents are
3271     unspecified.
3272
3273 -- Scheme Procedure: u8vector value ...
3274 -- Scheme Procedure: s8vector value ...
3275 -- Scheme Procedure: u16vector value ...
3276 -- Scheme Procedure: s16vector value ...
3277 -- Scheme Procedure: u32vector value ...
3278 -- Scheme Procedure: s32vector value ...
3279 -- Scheme Procedure: u64vector value ...
3280 -- Scheme Procedure: s64vector value ...
3281 -- Scheme Procedure: f32vector value ...
3282 -- Scheme Procedure: f64vector value ...
3283 -- Scheme Procedure: c32vector value ...
3284 -- Scheme Procedure: c64vector value ...
3285 -- C Function: scm_u8vector (values)
3286 -- C Function: scm_s8vector (values)
3287 -- C Function: scm_u16vector (values)
3288 -- C Function: scm_s16vector (values)
3289 -- C Function: scm_u32vector (values)
3290 -- C Function: scm_s32vector (values)
3291 -- C Function: scm_u64vector (values)
3292 -- C Function: scm_s64vector (values)
3293 -- C Function: scm_f32vector (values)
3294 -- C Function: scm_f64vector (values)
3295 -- C Function: scm_c32vector (values)
3296 -- C Function: scm_c64vector (values)
3297     Return a newly allocated homogeneous numeric vector of the
3298     indicated type, holding the given parameter VALUEs.  The vector
3299     length is the number of parameters given.
3300
3301 -- Scheme Procedure: u8vector-length vec
3302 -- Scheme Procedure: s8vector-length vec
3303 -- Scheme Procedure: u16vector-length vec
3304 -- Scheme Procedure: s16vector-length vec
3305 -- Scheme Procedure: u32vector-length vec
3306 -- Scheme Procedure: s32vector-length vec
3307 -- Scheme Procedure: u64vector-length vec
3308 -- Scheme Procedure: s64vector-length vec
3309 -- Scheme Procedure: f32vector-length vec
3310 -- Scheme Procedure: f64vector-length vec
3311 -- Scheme Procedure: c32vector-length vec
3312 -- Scheme Procedure: c64vector-length vec
3313 -- C Function: scm_u8vector_length (vec)
3314 -- C Function: scm_s8vector_length (vec)
3315 -- C Function: scm_u16vector_length (vec)
3316 -- C Function: scm_s16vector_length (vec)
3317 -- C Function: scm_u32vector_length (vec)
3318 -- C Function: scm_s32vector_length (vec)
3319 -- C Function: scm_u64vector_length (vec)
3320 -- C Function: scm_s64vector_length (vec)
3321 -- C Function: scm_f32vector_length (vec)
3322 -- C Function: scm_f64vector_length (vec)
3323 -- C Function: scm_c32vector_length (vec)
3324 -- C Function: scm_c64vector_length (vec)
3325     Return the number of elements in VEC.
3326
3327 -- Scheme Procedure: u8vector-ref vec i
3328 -- Scheme Procedure: s8vector-ref vec i
3329 -- Scheme Procedure: u16vector-ref vec i
3330 -- Scheme Procedure: s16vector-ref vec i
3331 -- Scheme Procedure: u32vector-ref vec i
3332 -- Scheme Procedure: s32vector-ref vec i
3333 -- Scheme Procedure: u64vector-ref vec i
3334 -- Scheme Procedure: s64vector-ref vec i
3335 -- Scheme Procedure: f32vector-ref vec i
3336 -- Scheme Procedure: f64vector-ref vec i
3337 -- Scheme Procedure: c32vector-ref vec i
3338 -- Scheme Procedure: c64vector-ref vec i
3339 -- C Function: scm_u8vector_ref (vec, i)
3340 -- C Function: scm_s8vector_ref (vec, i)
3341 -- C Function: scm_u16vector_ref (vec, i)
3342 -- C Function: scm_s16vector_ref (vec, i)
3343 -- C Function: scm_u32vector_ref (vec, i)
3344 -- C Function: scm_s32vector_ref (vec, i)
3345 -- C Function: scm_u64vector_ref (vec, i)
3346 -- C Function: scm_s64vector_ref (vec, i)
3347 -- C Function: scm_f32vector_ref (vec, i)
3348 -- C Function: scm_f64vector_ref (vec, i)
3349 -- C Function: scm_c32vector_ref (vec, i)
3350 -- C Function: scm_c64vector_ref (vec, i)
3351     Return the element at index I in VEC.  The first element in VEC is
3352     index 0.
3353
3354 -- Scheme Procedure: u8vector-set! vec i value
3355 -- Scheme Procedure: s8vector-set! vec i value
3356 -- Scheme Procedure: u16vector-set! vec i value
3357 -- Scheme Procedure: s16vector-set! vec i value
3358 -- Scheme Procedure: u32vector-set! vec i value
3359 -- Scheme Procedure: s32vector-set! vec i value
3360 -- Scheme Procedure: u64vector-set! vec i value
3361 -- Scheme Procedure: s64vector-set! vec i value
3362 -- Scheme Procedure: f32vector-set! vec i value
3363 -- Scheme Procedure: f64vector-set! vec i value
3364 -- Scheme Procedure: c32vector-set! vec i value
3365 -- Scheme Procedure: c64vector-set! vec i value
3366 -- C Function: scm_u8vector_set_x (vec, i, value)
3367 -- C Function: scm_s8vector_set_x (vec, i, value)
3368 -- C Function: scm_u16vector_set_x (vec, i, value)
3369 -- C Function: scm_s16vector_set_x (vec, i, value)
3370 -- C Function: scm_u32vector_set_x (vec, i, value)
3371 -- C Function: scm_s32vector_set_x (vec, i, value)
3372 -- C Function: scm_u64vector_set_x (vec, i, value)
3373 -- C Function: scm_s64vector_set_x (vec, i, value)
3374 -- C Function: scm_f32vector_set_x (vec, i, value)
3375 -- C Function: scm_f64vector_set_x (vec, i, value)
3376 -- C Function: scm_c32vector_set_x (vec, i, value)
3377 -- C Function: scm_c64vector_set_x (vec, i, value)
3378     Set the element at index I in VEC to VALUE.  The first element in
3379     VEC is index 0.  The return value is unspecified.
3380
3381 -- Scheme Procedure: u8vector->list vec
3382 -- Scheme Procedure: s8vector->list vec
3383 -- Scheme Procedure: u16vector->list vec
3384 -- Scheme Procedure: s16vector->list vec
3385 -- Scheme Procedure: u32vector->list vec
3386 -- Scheme Procedure: s32vector->list vec
3387 -- Scheme Procedure: u64vector->list vec
3388 -- Scheme Procedure: s64vector->list vec
3389 -- Scheme Procedure: f32vector->list vec
3390 -- Scheme Procedure: f64vector->list vec
3391 -- Scheme Procedure: c32vector->list vec
3392 -- Scheme Procedure: c64vector->list vec
3393 -- C Function: scm_u8vector_to_list (vec)
3394 -- C Function: scm_s8vector_to_list (vec)
3395 -- C Function: scm_u16vector_to_list (vec)
3396 -- C Function: scm_s16vector_to_list (vec)
3397 -- C Function: scm_u32vector_to_list (vec)
3398 -- C Function: scm_s32vector_to_list (vec)
3399 -- C Function: scm_u64vector_to_list (vec)
3400 -- C Function: scm_s64vector_to_list (vec)
3401 -- C Function: scm_f32vector_to_list (vec)
3402 -- C Function: scm_f64vector_to_list (vec)
3403 -- C Function: scm_c32vector_to_list (vec)
3404 -- C Function: scm_c64vector_to_list (vec)
3405     Return a newly allocated list holding all elements of VEC.
3406
3407 -- Scheme Procedure: list->u8vector lst
3408 -- Scheme Procedure: list->s8vector lst
3409 -- Scheme Procedure: list->u16vector lst
3410 -- Scheme Procedure: list->s16vector lst
3411 -- Scheme Procedure: list->u32vector lst
3412 -- Scheme Procedure: list->s32vector lst
3413 -- Scheme Procedure: list->u64vector lst
3414 -- Scheme Procedure: list->s64vector lst
3415 -- Scheme Procedure: list->f32vector lst
3416 -- Scheme Procedure: list->f64vector lst
3417 -- Scheme Procedure: list->c32vector lst
3418 -- Scheme Procedure: list->c64vector lst
3419 -- C Function: scm_list_to_u8vector (lst)
3420 -- C Function: scm_list_to_s8vector (lst)
3421 -- C Function: scm_list_to_u16vector (lst)
3422 -- C Function: scm_list_to_s16vector (lst)
3423 -- C Function: scm_list_to_u32vector (lst)
3424 -- C Function: scm_list_to_s32vector (lst)
3425 -- C Function: scm_list_to_u64vector (lst)
3426 -- C Function: scm_list_to_s64vector (lst)
3427 -- C Function: scm_list_to_f32vector (lst)
3428 -- C Function: scm_list_to_f64vector (lst)
3429 -- C Function: scm_list_to_c32vector (lst)
3430 -- C Function: scm_list_to_c64vector (lst)
3431     Return a newly allocated homogeneous numeric vector of the
3432     indicated type, initialized with the elements of the list LST.
3433
3434 -- C Function: SCM scm_take_u8vector (const scm_t_uint8 *data, size_t
3435          len)
3436 -- C Function: SCM scm_take_s8vector (const scm_t_int8 *data, size_t
3437          len)
3438 -- C Function: SCM scm_take_u16vector (const scm_t_uint16 *data, size_t
3439          len)
3440 -- C Function: SCM scm_take_s16vector (const scm_t_int16 *data, size_t
3441          len)
3442 -- C Function: SCM scm_take_u32vector (const scm_t_uint32 *data, size_t
3443          len)
3444 -- C Function: SCM scm_take_s32vector (const scm_t_int32 *data, size_t
3445          len)
3446 -- C Function: SCM scm_take_u64vector (const scm_t_uint64 *data, size_t
3447          len)
3448 -- C Function: SCM scm_take_s64vector (const scm_t_int64 *data, size_t
3449          len)
3450 -- C Function: SCM scm_take_f32vector (const float *data, size_t len)
3451 -- C Function: SCM scm_take_f64vector (const double *data, size_t len)
3452 -- C Function: SCM scm_take_c32vector (const float *data, size_t len)
3453 -- C Function: SCM scm_take_c64vector (const double *data, size_t len)
3454     Return a new uniform numeric vector of the indicated type and
3455     length that uses the memory pointed to by DATA to store its
3456     elements.  This memory will eventually be freed with ‘free’.  The
3457     argument LEN specifies the number of elements in DATA, not its size
3458     in bytes.
3459
3460     The ‘c32’ and ‘c64’ variants take a pointer to a C array of
3461     ‘float’s or ‘double’s.  The real parts of the complex numbers are
3462     at even indices in that array, the corresponding imaginary parts
3463     are at the following odd index.
3464
3465 -- C Function: const scm_t_uint8 * scm_u8vector_elements (SCM vec,
3466          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3467 -- C Function: const scm_t_int8 * scm_s8vector_elements (SCM vec,
3468          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3469 -- C Function: const scm_t_uint16 * scm_u16vector_elements (SCM vec,
3470          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3471 -- C Function: const scm_t_int16 * scm_s16vector_elements (SCM vec,
3472          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3473 -- C Function: const scm_t_uint32 * scm_u32vector_elements (SCM vec,
3474          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3475 -- C Function: const scm_t_int32 * scm_s32vector_elements (SCM vec,
3476          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3477 -- C Function: const scm_t_uint64 * scm_u64vector_elements (SCM vec,
3478          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3479 -- C Function: const scm_t_int64 * scm_s64vector_elements (SCM vec,
3480          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3481 -- C Function: const float * scm_f32vector_elements (SCM vec,
3482          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3483 -- C Function: const double * scm_f64vector_elements (SCM vec,
3484          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3485 -- C Function: const float * scm_c32vector_elements (SCM vec,
3486          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3487 -- C Function: const double * scm_c64vector_elements (SCM vec,
3488          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3489     Like ‘scm_vector_elements’ (*note Vector Accessing from C::), but
3490     returns a pointer to the elements of a uniform numeric vector of
3491     the indicated kind.
3492
3493 -- C Function: scm_t_uint8 * scm_u8vector_writable_elements (SCM vec,
3494          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3495 -- C Function: scm_t_int8 * scm_s8vector_writable_elements (SCM vec,
3496          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3497 -- C Function: scm_t_uint16 * scm_u16vector_writable_elements (SCM vec,
3498          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3499 -- C Function: scm_t_int16 * scm_s16vector_writable_elements (SCM vec,
3500          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3501 -- C Function: scm_t_uint32 * scm_u32vector_writable_elements (SCM vec,
3502          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3503 -- C Function: scm_t_int32 * scm_s32vector_writable_elements (SCM vec,
3504          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3505 -- C Function: scm_t_uint64 * scm_u64vector_writable_elements (SCM vec,
3506          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3507 -- C Function: scm_t_int64 * scm_s64vector_writable_elements (SCM vec,
3508          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3509 -- C Function: float * scm_f32vector_writable_elements (SCM vec,
3510          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3511 -- C Function: double * scm_f64vector_writable_elements (SCM vec,
3512          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3513 -- C Function: float * scm_c32vector_writable_elements (SCM vec,
3514          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3515 -- C Function: double * scm_c64vector_writable_elements (SCM vec,
3516          scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
3517     Like ‘scm_vector_writable_elements’ (*note Vector Accessing from
3518     C::), but returns a pointer to the elements of a uniform numeric
3519     vector of the indicated kind.
3520
3521
3522File: guile.info,  Node: SRFI-4 and Bytevectors,  Next: SRFI-4 Extensions,  Prev: SRFI-4 API,  Up: SRFI-4
3523
35247.5.5.3 SRFI-4 - Relation to bytevectors
3525........................................
3526
3527Guile implements SRFI-4 vectors using bytevectors (*note Bytevectors::).
3528Often when you have a numeric vector, you end up wanting to write its
3529bytes somewhere, or have access to the underlying bytes, or read in
3530bytes from somewhere else.  Bytevectors are very good at this sort of
3531thing.  But the SRFI-4 APIs are nicer to use when doing
3532number-crunching, because they are addressed by element and not by byte.
3533
3534   So as a compromise, Guile allows all bytevector functions to operate
3535on numeric vectors.  They address the underlying bytes in the native
3536endianness, as one would expect.
3537
3538   Following the same reasoning, that it’s just bytes underneath, Guile
3539also allows uniform vectors of a given type to be accessed as if they
3540were of any type.  One can fill a u32vector, and access its elements
3541with u8vector-ref.  One can use f64vector-ref on bytevectors.  It’s all
3542the same to Guile.
3543
3544   In this way, uniform numeric vectors may be written to and read from
3545input/output ports using the procedures that operate on bytevectors.
3546
3547   *Note Bytevectors::, for more information.
3548
3549
3550File: guile.info,  Node: SRFI-4 Extensions,  Prev: SRFI-4 and Bytevectors,  Up: SRFI-4
3551
35527.5.5.4 SRFI-4 - Guile extensions
3553.................................
3554
3555Guile defines some useful extensions to SRFI-4, which are not available
3556in the default Guile environment.  They may be imported by loading the
3557extensions module:
3558
3559     (use-modules (srfi srfi-4 gnu))
3560
3561 -- Scheme Procedure: any->u8vector obj
3562 -- Scheme Procedure: any->s8vector obj
3563 -- Scheme Procedure: any->u16vector obj
3564 -- Scheme Procedure: any->s16vector obj
3565 -- Scheme Procedure: any->u32vector obj
3566 -- Scheme Procedure: any->s32vector obj
3567 -- Scheme Procedure: any->u64vector obj
3568 -- Scheme Procedure: any->s64vector obj
3569 -- Scheme Procedure: any->f32vector obj
3570 -- Scheme Procedure: any->f64vector obj
3571 -- Scheme Procedure: any->c32vector obj
3572 -- Scheme Procedure: any->c64vector obj
3573 -- C Function: scm_any_to_u8vector (obj)
3574 -- C Function: scm_any_to_s8vector (obj)
3575 -- C Function: scm_any_to_u16vector (obj)
3576 -- C Function: scm_any_to_s16vector (obj)
3577 -- C Function: scm_any_to_u32vector (obj)
3578 -- C Function: scm_any_to_s32vector (obj)
3579 -- C Function: scm_any_to_u64vector (obj)
3580 -- C Function: scm_any_to_s64vector (obj)
3581 -- C Function: scm_any_to_f32vector (obj)
3582 -- C Function: scm_any_to_f64vector (obj)
3583 -- C Function: scm_any_to_c32vector (obj)
3584 -- C Function: scm_any_to_c64vector (obj)
3585     Return a (maybe newly allocated) uniform numeric vector of the
3586     indicated type, initialized with the elements of OBJ, which must be
3587     a list, a vector, or a uniform vector.  When OBJ is already a
3588     suitable uniform numeric vector, it is returned unchanged.
3589
3590
3591File: guile.info,  Node: SRFI-6,  Next: SRFI-8,  Prev: SRFI-4,  Up: SRFI Support
3592
35937.5.6 SRFI-6 - Basic String Ports
3594---------------------------------
3595
3596SRFI-6 defines the procedures ‘open-input-string’, ‘open-output-string’
3597and ‘get-output-string’.  These procedures are included in the Guile
3598core, so using this module does not make any difference at the moment.
3599But it is possible that support for SRFI-6 will be factored out of the
3600core library in the future, so using this module does not hurt, after
3601all.
3602
3603
3604File: guile.info,  Node: SRFI-8,  Next: SRFI-9,  Prev: SRFI-6,  Up: SRFI Support
3605
36067.5.7 SRFI-8 - receive
3607----------------------
3608
3609‘receive’ is a syntax for making the handling of multiple-value
3610procedures easier.  It is documented in *Note Multiple Values::.
3611
3612
3613File: guile.info,  Node: SRFI-9,  Next: SRFI-10,  Prev: SRFI-8,  Up: SRFI Support
3614
36157.5.8 SRFI-9 - define-record-type
3616---------------------------------
3617
3618This SRFI is a syntax for defining new record types and creating
3619predicate, constructor, and field getter and setter functions.  It is
3620documented in the “Data Types” section of the manual (*note SRFI-9
3621Records::).
3622
3623
3624File: guile.info,  Node: SRFI-10,  Next: SRFI-11,  Prev: SRFI-9,  Up: SRFI Support
3625
36267.5.9 SRFI-10 - Hash-Comma Reader Extension
3627-------------------------------------------
3628
3629This SRFI implements a reader extension ‘#,()’ called hash-comma.  It
3630allows the reader to give new kinds of objects, for use both in data and
3631as constants or literals in source code.  This feature is available with
3632
3633     (use-modules (srfi srfi-10))
3634
3635The new read syntax is of the form
3636
3637     #,(TAG ARG...)
3638
3639where TAG is a symbol and the ARGs are objects taken as parameters.
3640TAGs are registered with the following procedure.
3641
3642 -- Scheme Procedure: define-reader-ctor tag proc
3643     Register PROC as the constructor for a hash-comma read syntax
3644     starting with symbol TAG, i.e. #,(TAG arg...).  PROC is called with
3645     the given arguments ‘(PROC arg...)’ and the object it returns is
3646     the result of the read.
3647
3648For example, a syntax giving a list of N copies of an object.
3649
3650     (define-reader-ctor 'repeat
3651       (lambda (obj reps)
3652         (make-list reps obj)))
3653
3654     (display '#,(repeat 99 3))
3655     ⊣ (99 99 99)
3656
3657   Notice the quote ’ when the #,( ) is used.  The ‘repeat’ handler
3658returns a list and the program must quote to use it literally, the same
3659as any other list.  Ie.
3660
3661     (display '#,(repeat 99 3))
36623663     (display '(99 99 99))
3664
3665   When a handler returns an object which is self-evaluating, like a
3666number or a string, then there’s no need for quoting, just as there’s no
3667need when giving those directly as literals.  For example an addition,
3668
3669     (define-reader-ctor 'sum
3670       (lambda (x y)
3671         (+ x y)))
3672     (display #,(sum 123 456)) ⊣ 579
3673
3674   Once ‘(srfi srfi-10)’ has loaded, #,() is available globally, there’s
3675no need to use ‘(srfi srfi-10)’ in later modules.  Similarly the tags
3676registered are global and can be used anywhere once registered.
3677
3678   We do not recommend #,() reader extensions, however, and for three
3679reasons.
3680
3681   First of all, this SRFI is not modular: the tag is matched by name,
3682not as an identifier within a scope.  Defining a reader extension in one
3683part of a program can thus affect unrelated parts of a program because
3684the tag is not scoped.
3685
3686   Secondly, reader extensions can be hard to manage from a time
3687perspective: when does the reader extension take effect?  *Note Eval
3688When::, for more discussion.
3689
3690   Finally, reader extensions can easily produce objects that can’t be
3691reified to an object file by the compiler.  For example if you define a
3692reader extension that makes a hash table (*note Hash Tables::), then it
3693will work fine when run with the interpreter, and you think you have a
3694neat hack.  But then if you try to compile your program, after wrangling
3695with the ‘eval-when’ concerns mentioned above, the compiler will carp
3696that it doesn’t know how to serialize a hash table to disk.
3697
3698   In the specific case of hash tables, it would be possible for Guile
3699to know how to pack hash tables into compiled files, but this doesn’t
3700work in general.  What if the object you produce is an instance of a
3701record type?  Guile would then have to serialize the record type to disk
3702too, and then what happens if the program independently loads the code
3703that defines the record type?  Does it define the same type or a
3704different type?  Guile’s record types are nominal, not structural, so
3705the answer is not clear at all.
3706
3707   For all of these reasons we recommend macros over reader extensions.
3708Macros fulfill many of the same needs while preserving modular
3709composition, and their interaction with ‘eval-when’ is well-known.  If
3710you need brevity, instead use ‘read-hash-extend’ and make your reader
3711extension expand to a macro invocation.  In that way we preserve scoping
3712as much as possible.  *Note Reader Extensions::.
3713
3714
3715File: guile.info,  Node: SRFI-11,  Next: SRFI-13,  Prev: SRFI-10,  Up: SRFI Support
3716
37177.5.10 SRFI-11 - let-values
3718---------------------------
3719
3720This module implements the binding forms for multiple values
3721‘let-values’ and ‘let*-values’.  These forms are similar to ‘let’ and
3722‘let*’ (*note Local Bindings::), but they support binding of the values
3723returned by multiple-valued expressions.
3724
3725   Write ‘(use-modules (srfi srfi-11))’ to make the bindings available.
3726
3727     (let-values (((x y) (values 1 2))
3728                  ((z f) (values 3 4)))
3729        (+ x y z f))
37303731     10
3732
3733   ‘let-values’ performs all bindings simultaneously, which means that
3734no expression in the binding clauses may refer to variables bound in the
3735same clause list.  ‘let*-values’, on the other hand, performs the
3736bindings sequentially, just like ‘let*’ does for single-valued
3737expressions.
3738
3739
3740File: guile.info,  Node: SRFI-13,  Next: SRFI-14,  Prev: SRFI-11,  Up: SRFI Support
3741
37427.5.11 SRFI-13 - String Library
3743-------------------------------
3744
3745The SRFI-13 procedures are always available, *Note Strings::.
3746
3747
3748File: guile.info,  Node: SRFI-14,  Next: SRFI-16,  Prev: SRFI-13,  Up: SRFI Support
3749
37507.5.12 SRFI-14 - Character-set Library
3751--------------------------------------
3752
3753The SRFI-14 data type and procedures are always available, *Note
3754Character Sets::.
3755
3756
3757File: guile.info,  Node: SRFI-16,  Next: SRFI-17,  Prev: SRFI-14,  Up: SRFI Support
3758
37597.5.13 SRFI-16 - case-lambda
3760----------------------------
3761
3762SRFI-16 defines a variable-arity ‘lambda’ form, ‘case-lambda’.  This
3763form is available in the default Guile environment.  *Note
3764Case-lambda::, for more information.
3765
3766
3767File: guile.info,  Node: SRFI-17,  Next: SRFI-18,  Prev: SRFI-16,  Up: SRFI Support
3768
37697.5.14 SRFI-17 - Generalized set!
3770---------------------------------
3771
3772This SRFI implements a generalized ‘set!’, allowing some “referencing”
3773functions to be used as the target location of a ‘set!’.  This feature
3774is available from
3775
3776     (use-modules (srfi srfi-17))
3777
3778For example ‘vector-ref’ is extended so that
3779
3780     (set! (vector-ref vec idx) new-value)
3781
3782is equivalent to
3783
3784     (vector-set! vec idx new-value)
3785
3786   The idea is that a ‘vector-ref’ expression identifies a location,
3787which may be either fetched or stored.  The same form is used for the
3788location in both cases, encouraging visual clarity.  This is similar to
3789the idea of an “lvalue” in C.
3790
3791   The mechanism for this kind of ‘set!’ is in the Guile core (*note
3792Procedures with Setters::).  This module adds definitions of the
3793following functions as procedures with setters, allowing them to be
3794targets of a ‘set!’,
3795
3796     car, cdr, caar, cadr, cdar, cddr, caaar, caadr, cadar, caddr,
3797     cdaar, cdadr, cddar, cdddr, caaaar, caaadr, caadar, caaddr, cadaar,
3798     cadadr, caddar, cadddr, cdaaar, cdaadr, cdadar, cdaddr, cddaar,
3799     cddadr, cdddar, cddddr
3800
3801     string-ref, vector-ref
3802
3803   The SRFI specifies ‘setter’ (*note Procedures with Setters::) as a
3804procedure with setter, allowing the setter for a procedure to be
3805changed, eg. ‘(set! (setter foo) my-new-setter-handler)’.  Currently
3806Guile does not implement this, a setter can only be specified on
3807creation (‘getter-with-setter’ below).
3808
3809 -- Function: getter-with-setter
3810     The same as the Guile core ‘make-procedure-with-setter’ (*note
3811     Procedures with Setters::).
3812
3813
3814File: guile.info,  Node: SRFI-18,  Next: SRFI-19,  Prev: SRFI-17,  Up: SRFI Support
3815
38167.5.15 SRFI-18 - Multithreading support
3817---------------------------------------
3818
3819This is an implementation of the SRFI-18 threading and synchronization
3820library.  The functions and variables described here are provided by
3821
3822     (use-modules (srfi srfi-18))
3823
3824   SRFI-18 defines facilities for threads, mutexes, condition variables,
3825time, and exception handling.  Because these facilities are at a higher
3826level than Guile’s primitives, they are implemented as a layer on top of
3827what Guile provides.  In particular this means that a Guile mutex is not
3828a SRFI-18 mutex, and a Guile thread is not a SRFI-18 thread, and so on.
3829Guile provides a set of primitives and SRFI-18 is one of the systems
3830built in terms of those primitives.
3831
3832* Menu:
3833
3834* SRFI-18 Threads::             Executing code
3835* SRFI-18 Mutexes::             Mutual exclusion devices
3836* SRFI-18 Condition variables:: Synchronizing of groups of threads
3837* SRFI-18 Time::                Representation of times and durations
3838* SRFI-18 Exceptions::          Signalling and handling errors
3839
3840
3841File: guile.info,  Node: SRFI-18 Threads,  Next: SRFI-18 Mutexes,  Up: SRFI-18
3842
38437.5.15.1 SRFI-18 Threads
3844........................
3845
3846Threads created by SRFI-18 differ in two ways from threads created by
3847Guile’s built-in thread functions.  First, a thread created by SRFI-18
3848‘make-thread’ begins in a blocked state and will not start execution
3849until ‘thread-start!’ is called on it.  Second, SRFI-18 threads are
3850constructed with a top-level exception handler that captures any
3851exceptions that are thrown on thread exit.
3852
3853   SRFI-18 threads are disjoint from Guile’s primitive threads.  *Note
3854Threads::, for more on Guile’s primitive facility.
3855
3856 -- Function: current-thread
3857     Returns the thread that called this function.  This is the same
3858     procedure as the same-named built-in procedure ‘current-thread’
3859     (*note Threads::).
3860
3861 -- Function: thread? obj
3862     Returns ‘#t’ if OBJ is a thread, ‘#f’ otherwise.  This is the same
3863     procedure as the same-named built-in procedure ‘thread?’ (*note
3864     Threads::).
3865
3866 -- Function: make-thread thunk [name]
3867     Call ‘thunk’ in a new thread and with a new dynamic state,
3868     returning the new thread and optionally assigning it the object
3869     name NAME, which may be any Scheme object.
3870
3871     Note that the name ‘make-thread’ conflicts with the ‘(ice-9
3872     threads)’ function ‘make-thread’.  Applications wanting to use both
3873     of these functions will need to refer to them by different names.
3874
3875 -- Function: thread-name thread
3876     Returns the name assigned to THREAD at the time of its creation, or
3877     ‘#f’ if it was not given a name.
3878
3879 -- Function: thread-specific thread
3880 -- Function: thread-specific-set! thread obj
3881     Get or set the “object-specific” property of THREAD.  In Guile’s
3882     implementation of SRFI-18, this value is stored as an object
3883     property, and will be ‘#f’ if not set.
3884
3885 -- Function: thread-start! thread
3886     Unblocks THREAD and allows it to begin execution if it has not done
3887     so already.
3888
3889 -- Function: thread-yield!
3890     If one or more threads are waiting to execute, calling
3891     ‘thread-yield!’ forces an immediate context switch to one of them.
3892     Otherwise, ‘thread-yield!’ has no effect.  ‘thread-yield!’ behaves
3893     identically to the Guile built-in function ‘yield’.
3894
3895 -- Function: thread-sleep! timeout
3896     The current thread waits until the point specified by the time
3897     object TIMEOUT is reached (*note SRFI-18 Time::).  This blocks the
3898     thread only if TIMEOUT represents a point in the future.  it is an
3899     error for TIMEOUT to be ‘#f’.
3900
3901 -- Function: thread-terminate! thread
3902     Causes an abnormal termination of THREAD.  If THREAD is not already
3903     terminated, all mutexes owned by THREAD become unlocked/abandoned.
3904     If THREAD is the current thread, ‘thread-terminate!’ does not
3905     return.  Otherwise ‘thread-terminate!’ returns an unspecified
3906     value; the termination of THREAD will occur before
3907     ‘thread-terminate!’ returns.  Subsequent attempts to join on THREAD
3908     will cause a “terminated thread exception” to be raised.
3909
3910     ‘thread-terminate!’ is compatible with the thread cancellation
3911     procedures in the core threads API (*note Threads::) in that if a
3912     cleanup handler has been installed for the target thread, it will
3913     be called before the thread exits and its return value (or
3914     exception, if any) will be stored for later retrieval via a call to
3915     ‘thread-join!’.
3916
3917 -- Function: thread-join! thread [timeout [timeout-val]]
3918     Wait for THREAD to terminate and return its exit value.  When a
3919     time value TIMEOUT is given, it specifies a point in time where the
3920     waiting should be aborted.  When the waiting is aborted,
3921     TIMEOUT-VAL is returned if it is specified; otherwise, a
3922     ‘join-timeout-exception’ exception is raised (*note SRFI-18
3923     Exceptions::).  Exceptions may also be raised if the thread was
3924     terminated by a call to ‘thread-terminate!’
3925     (‘terminated-thread-exception’ will be raised) or if the thread
3926     exited by raising an exception that was handled by the top-level
3927     exception handler (‘uncaught-exception’ will be raised; the
3928     original exception can be retrieved using
3929     ‘uncaught-exception-reason’).
3930
3931
3932File: guile.info,  Node: SRFI-18 Mutexes,  Next: SRFI-18 Condition variables,  Prev: SRFI-18 Threads,  Up: SRFI-18
3933
39347.5.15.2 SRFI-18 Mutexes
3935........................
3936
3937SRFI-18 mutexes are disjoint from Guile’s primitive mutexes.  *Note
3938Mutexes and Condition Variables::, for more on Guile’s primitive
3939facility.
3940
3941 -- Function: make-mutex [name]
3942     Returns a new mutex, optionally assigning it the object name NAME,
3943     which may be any Scheme object.  The returned mutex will be created
3944     with the configuration described above.
3945
3946 -- Function: mutex-name mutex
3947     Returns the name assigned to MUTEX at the time of its creation, or
3948     ‘#f’ if it was not given a name.
3949
3950 -- Function: mutex-specific mutex
3951     Return the “object-specific” property of MUTEX, or ‘#f’ if none is
3952     set.
3953
3954 -- Function: mutex-specific-set! mutex obj
3955     Set the “object-specific” property of MUTEX.
3956
3957 -- Function: mutex-state mutex
3958     Returns information about the state of MUTEX.  Possible values are:
3959        • thread T: the mutex is in the locked/owned state and thread T
3960          is the owner of the mutex
3961        • symbol ‘not-owned’: the mutex is in the locked/not-owned state
3962        • symbol ‘abandoned’: the mutex is in the unlocked/abandoned
3963          state
3964        • symbol ‘not-abandoned’: the mutex is in the
3965          unlocked/not-abandoned state
3966
3967 -- Function: mutex-lock! mutex [timeout [thread]]
3968     Lock MUTEX, optionally specifying a time object TIMEOUT after which
3969     to abort the lock attempt and a thread THREAD giving a new owner
3970     for MUTEX different than the current thread.
3971
3972 -- Function: mutex-unlock! mutex [condition-variable [timeout]]
3973     Unlock MUTEX, optionally specifying a condition variable
3974     CONDITION-VARIABLE on which to wait, either indefinitely or,
3975     optionally, until the time object TIMEOUT has passed, to be
3976     signalled.
3977
3978
3979File: guile.info,  Node: SRFI-18 Condition variables,  Next: SRFI-18 Time,  Prev: SRFI-18 Mutexes,  Up: SRFI-18
3980
39817.5.15.3 SRFI-18 Condition variables
3982....................................
3983
3984SRFI-18 does not specify a “wait” function for condition variables.
3985Waiting on a condition variable can be simulated using the SRFI-18
3986‘mutex-unlock!’ function described in the previous section.
3987
3988   SRFI-18 condition variables are disjoint from Guile’s primitive
3989condition variables.  *Note Mutexes and Condition Variables::, for more
3990on Guile’s primitive facility.
3991
3992 -- Function: condition-variable? obj
3993     Returns ‘#t’ if OBJ is a condition variable, ‘#f’ otherwise.
3994
3995 -- Function: make-condition-variable [name]
3996     Returns a new condition variable, optionally assigning it the
3997     object name NAME, which may be any Scheme object.
3998
3999 -- Function: condition-variable-name condition-variable
4000     Returns the name assigned to CONDITION-VARIABLE at the time of its
4001     creation, or ‘#f’ if it was not given a name.
4002
4003 -- Function: condition-variable-specific condition-variable
4004     Return the “object-specific” property of CONDITION-VARIABLE, or
4005     ‘#f’ if none is set.
4006
4007 -- Function: condition-variable-specific-set! condition-variable obj
4008     Set the “object-specific” property of CONDITION-VARIABLE.
4009
4010 -- Function: condition-variable-signal! condition-variable
4011 -- Function: condition-variable-broadcast! condition-variable
4012     Wake up one thread that is waiting for CONDITION-VARIABLE, in the
4013     case of ‘condition-variable-signal!’, or all threads waiting for
4014     it, in the case of ‘condition-variable-broadcast!’.
4015
4016
4017File: guile.info,  Node: SRFI-18 Time,  Next: SRFI-18 Exceptions,  Prev: SRFI-18 Condition variables,  Up: SRFI-18
4018
40197.5.15.4 SRFI-18 Time
4020.....................
4021
4022The SRFI-18 time functions manipulate time in two formats: a “time
4023object” type that represents an absolute point in time in some
4024implementation-specific way; and the number of seconds since some
4025unspecified “epoch”.  In Guile’s implementation, the epoch is the Unix
4026epoch, 00:00:00 UTC, January 1, 1970.
4027
4028 -- Function: current-time
4029     Return the current time as a time object.  This procedure replaces
4030     the procedure of the same name in the core library, which returns
4031     the current time in seconds since the epoch.
4032
4033 -- Function: time? obj
4034     Returns ‘#t’ if OBJ is a time object, ‘#f’ otherwise.
4035
4036 -- Function: time->seconds time
4037 -- Function: seconds->time seconds
4038     Convert between time objects and numerical values representing the
4039     number of seconds since the epoch.  When converting from a time
4040     object to seconds, the return value is the number of seconds
4041     between TIME and the epoch.  When converting from seconds to a time
4042     object, the return value is a time object that represents a time
4043     SECONDS seconds after the epoch.
4044
4045
4046File: guile.info,  Node: SRFI-18 Exceptions,  Prev: SRFI-18 Time,  Up: SRFI-18
4047
40487.5.15.5 SRFI-18 Exceptions
4049...........................
4050
4051SRFI-18 exceptions are identical to the exceptions provided by Guile’s
4052implementation of SRFI-34.  The behavior of exception handlers invoked
4053to handle exceptions thrown from SRFI-18 functions, however, differs
4054from the conventional behavior of SRFI-34 in that the continuation of
4055the handler is the same as that of the call to the function.  Handlers
4056are called in a tail-recursive manner; the exceptions do not “bubble
4057up”.
4058
4059 -- Function: current-exception-handler
4060     Returns the current exception handler.
4061
4062 -- Function: with-exception-handler handler thunk
4063     Installs HANDLER as the current exception handler and calls the
4064     procedure THUNK with no arguments, returning its value as the value
4065     of the exception.  HANDLER must be a procedure that accepts a
4066     single argument.  The current exception handler at the time this
4067     procedure is called will be restored after the call returns.
4068
4069 -- Function: raise obj
4070     Raise OBJ as an exception.  This is the same procedure as the
4071     same-named procedure defined in SRFI 34.
4072
4073 -- Function: join-timeout-exception? obj
4074     Returns ‘#t’ if OBJ is an exception raised as the result of
4075     performing a timed join on a thread that does not exit within the
4076     specified timeout, ‘#f’ otherwise.
4077
4078 -- Function: abandoned-mutex-exception? obj
4079     Returns ‘#t’ if OBJ is an exception raised as the result of
4080     attempting to lock a mutex that has been abandoned by its owner
4081     thread, ‘#f’ otherwise.
4082
4083 -- Function: terminated-thread-exception? obj
4084     Returns ‘#t’ if OBJ is an exception raised as the result of joining
4085     on a thread that exited as the result of a call to
4086     ‘thread-terminate!’.
4087
4088 -- Function: uncaught-exception? obj
4089 -- Function: uncaught-exception-reason exc
4090     ‘uncaught-exception?’ returns ‘#t’ if OBJ is an exception thrown as
4091     the result of joining a thread that exited by raising an exception
4092     that was handled by the top-level exception handler installed by
4093     ‘make-thread’.  When this occurs, the original exception is
4094     preserved as part of the exception thrown by ‘thread-join!’ and can
4095     be accessed by calling ‘uncaught-exception-reason’ on that
4096     exception.  Note that because this exception-preservation mechanism
4097     is a side-effect of ‘make-thread’, joining on threads that exited
4098     as described above but were created by other means will not raise
4099     this ‘uncaught-exception’ error.
4100
4101
4102File: guile.info,  Node: SRFI-19,  Next: SRFI-23,  Prev: SRFI-18,  Up: SRFI Support
4103
41047.5.16 SRFI-19 - Time/Date Library
4105----------------------------------
4106
4107This is an implementation of the SRFI-19 time/date library.  The
4108functions and variables described here are provided by
4109
4110     (use-modules (srfi srfi-19))
4111
4112* Menu:
4113
4114* SRFI-19 Introduction::
4115* SRFI-19 Time::
4116* SRFI-19 Date::
4117* SRFI-19 Time/Date conversions::
4118* SRFI-19 Date to string::
4119* SRFI-19 String to date::
4120
4121
4122File: guile.info,  Node: SRFI-19 Introduction,  Next: SRFI-19 Time,  Up: SRFI-19
4123
41247.5.16.1 SRFI-19 Introduction
4125.............................
4126
4127This module implements time and date representations and calculations,
4128in various time systems, including Coordinated Universal Time (UTC) and
4129International Atomic Time (TAI).
4130
4131   For those not familiar with these time systems, TAI is based on a
4132fixed length second derived from oscillations of certain atoms.  UTC
4133differs from TAI by an integral number of seconds, which is increased or
4134decreased at announced times to keep UTC aligned to a mean solar day
4135(the orbit and rotation of the earth are not quite constant).
4136
4137   So far, only increases in the TAI <-> UTC difference have been
4138needed.  Such an increase is a “leap second”, an extra second of TAI
4139introduced at the end of a UTC day.  When working entirely within UTC
4140this is never seen, every day simply has 86400 seconds.  But when
4141converting from TAI to a UTC date, an extra 23:59:60 is present, where
4142normally a day would end at 23:59:59.  Effectively the UTC second from
414323:59:59 to 00:00:00 has taken two TAI seconds.
4144
4145   In the current implementation, the system clock is assumed to be UTC,
4146and a table of leap seconds in the code converts to TAI. See comments in
4147srfi-19.scm’ for how to update this table.
4148
4149   Also, for those not familiar with the terminology, a “Julian Day”
4150represents a point in time as a real number of days since
4151-4713-11-24T12:00:00Z, i.e. midday UT on 24 November 4714 BC in the
4152proleptic Gregorian calendar (1 January 4713 BC in the proleptic Julian
4153calendar).
4154
4155   A “Modified Julian Day” represents a point in time as a real number
4156of days since 1858-11-17T00:00:00Z, i.e. midnight UT on Wednesday 17
4157November AD 1858.  That time is julian day 2400000.5.
4158
4159
4160File: guile.info,  Node: SRFI-19 Time,  Next: SRFI-19 Date,  Prev: SRFI-19 Introduction,  Up: SRFI-19
4161
41627.5.16.2 SRFI-19 Time
4163.....................
4164
4165A “time” object has type, seconds and nanoseconds fields representing a
4166point in time starting from some epoch.  This is an arbitrary point in
4167time, not just a time of day.  Although times are represented in
4168nanoseconds, the actual resolution may be lower.
4169
4170   The following variables hold the possible time types.  For instance
4171‘(current-time time-process)’ would give the current CPU process time.
4172
4173 -- Variable: time-utc
4174     Universal Coordinated Time (UTC).
4175
4176 -- Variable: time-tai
4177     International Atomic Time (TAI).
4178
4179 -- Variable: time-monotonic
4180     Monotonic time, meaning a monotonically increasing time starting
4181     from an unspecified epoch.
4182
4183     Note that in the current implementation ‘time-monotonic’ is the
4184     same as ‘time-tai’, and unfortunately is therefore affected by
4185     adjustments to the system clock.  Perhaps this will change in the
4186     future.
4187
4188 -- Variable: time-duration
4189     A duration, meaning simply a difference between two times.
4190
4191 -- Variable: time-process
4192     CPU time spent in the current process, starting from when the
4193     process began.
4194
4195 -- Variable: time-thread
4196     CPU time spent in the current thread.  Not currently implemented.
4197
4198
4199 -- Function: time? obj
4200     Return ‘#t’ if OBJ is a time object, or ‘#f’ if not.
4201
4202 -- Function: make-time type nanoseconds seconds
4203     Create a time object with the given TYPE, SECONDS and NANOSECONDS.
4204
4205 -- Function: time-type time
4206 -- Function: time-nanosecond time
4207 -- Function: time-second time
4208 -- Function: set-time-type! time type
4209 -- Function: set-time-nanosecond! time nsec
4210 -- Function: set-time-second! time sec
4211     Get or set the type, seconds or nanoseconds fields of a time
4212     object.
4213
4214     ‘set-time-type!’ merely changes the field, it doesn’t convert the
4215     time value.  For conversions, see *note SRFI-19 Time/Date
4216     conversions::.
4217
4218 -- Function: copy-time time
4219     Return a new time object, which is a copy of the given TIME.
4220
4221 -- Function: current-time [type]
4222     Return the current time of the given TYPE.  The default TYPE is
4223     ‘time-utc’.
4224
4225     Note that the name ‘current-time’ conflicts with the Guile core
4226     ‘current-time’ function (*note Time::) as well as the SRFI-18
4227     ‘current-time’ function (*note SRFI-18 Time::).  Applications
4228     wanting to use more than one of these functions will need to refer
4229     to them by different names.
4230
4231 -- Function: time-resolution [type]
4232     Return the resolution, in nanoseconds, of the given time TYPE.  The
4233     default TYPE is ‘time-utc’.
4234
4235 -- Function: time<=? t1 t2
4236 -- Function: time<? t1 t2
4237 -- Function: time=? t1 t2
4238 -- Function: time>=? t1 t2
4239 -- Function: time>? t1 t2
4240     Return ‘#t’ or ‘#f’ according to the respective relation between
4241     time objects T1 and T2.  T1 and T2 must be the same time type.
4242
4243 -- Function: time-difference t1 t2
4244 -- Function: time-difference! t1 t2
4245     Return a time object of type ‘time-duration’ representing the
4246     period between T1 and T2.  T1 and T2 must be the same time type.
4247
4248     ‘time-difference’ returns a new time object, ‘time-difference!’ may
4249     modify T1 to form its return.
4250
4251 -- Function: add-duration time duration
4252 -- Function: add-duration! time duration
4253 -- Function: subtract-duration time duration
4254 -- Function: subtract-duration! time duration
4255     Return a time object which is TIME with the given DURATION added or
4256     subtracted.  DURATION must be a time object of type
4257     ‘time-duration’.
4258
4259     ‘add-duration’ and ‘subtract-duration’ return a new time object.
4260     ‘add-duration!’ and ‘subtract-duration!’ may modify the given TIME
4261     to form their return.
4262
4263
4264File: guile.info,  Node: SRFI-19 Date,  Next: SRFI-19 Time/Date conversions,  Prev: SRFI-19 Time,  Up: SRFI-19
4265
42667.5.16.3 SRFI-19 Date
4267.....................
4268
4269A “date” object represents a date in the Gregorian calendar and a time
4270of day on that date in some timezone.
4271
4272   The fields are year, month, day, hour, minute, second, nanoseconds
4273and timezone.  A date object is immutable, its fields can be read but
4274they cannot be modified once the object is created.
4275
4276   Historically, the Gregorian calendar was only used from the latter
4277part of the year 1582 onwards, and not until even later in many
4278countries.  Prior to that most countries used the Julian calendar.
4279SRFI-19 does not deal with the Julian calendar at all, and so does not
4280reflect this historical calendar reform.  Instead it projects the
4281Gregorian calendar back proleptically as far as necessary.  When dealing
4282with historical data, especially prior to the British Empire’s adoption
4283of the Gregorian calendar in 1752, one should be mindful of which
4284calendar is used in each context, and apply non-SRFI-19 facilities to
4285convert where necessary.
4286
4287 -- Function: date? obj
4288     Return ‘#t’ if OBJ is a date object, or ‘#f’ if not.
4289
4290 -- Function: make-date nsecs seconds minutes hours date month year
4291          zone-offset
4292     Create a new date object.
4293
4294 -- Function: date-nanosecond date
4295     Nanoseconds, 0 to 999999999.
4296
4297 -- Function: date-second date
4298     Seconds, 0 to 59, or 60 for a leap second.  60 is never seen when
4299     working entirely within UTC, it’s only when converting to or from
4300     TAI.
4301
4302 -- Function: date-minute date
4303     Minutes, 0 to 59.
4304
4305 -- Function: date-hour date
4306     Hour, 0 to 23.
4307
4308 -- Function: date-day date
4309     Day of the month, 1 to 31 (or less, according to the month).
4310
4311 -- Function: date-month date
4312     Month, 1 to 12.
4313
4314 -- Function: date-year date
4315     Year, eg. 2003.  Dates B.C. are negative, eg. -46 is 46 B.C. There
4316     is no year 0, year -1 is followed by year 1.
4317
4318 -- Function: date-zone-offset date
4319     Time zone, an integer number of seconds east of Greenwich.
4320
4321 -- Function: date-year-day date
4322     Day of the year, starting from 1 for 1st January.
4323
4324 -- Function: date-week-day date
4325     Day of the week, starting from 0 for Sunday.
4326
4327 -- Function: date-week-number date dstartw
4328     Week of the year, ignoring a first partial week.  DSTARTW is the
4329     day of the week which is taken to start a week, 0 for Sunday, 1 for
4330     Monday, etc.
4331
4332 -- Function: current-date [tz-offset]
4333     Return a date object representing the current date/time, in UTC
4334     offset by TZ-OFFSET.  TZ-OFFSET is seconds east of Greenwich and
4335     defaults to the local timezone.
4336
4337 -- Function: current-julian-day
4338     Return the current Julian Day.
4339
4340 -- Function: current-modified-julian-day
4341     Return the current Modified Julian Day.
4342
4343
4344File: guile.info,  Node: SRFI-19 Time/Date conversions,  Next: SRFI-19 Date to string,  Prev: SRFI-19 Date,  Up: SRFI-19
4345
43467.5.16.4 SRFI-19 Time/Date conversions
4347......................................
4348
4349 -- Function: date->julian-day date
4350 -- Function: date->modified-julian-day date
4351 -- Function: date->time-monotonic date
4352 -- Function: date->time-tai date
4353 -- Function: date->time-utc date
4354 -- Function: julian-day->date jdn [tz-offset]
4355 -- Function: julian-day->time-monotonic jdn
4356 -- Function: julian-day->time-tai jdn
4357 -- Function: julian-day->time-utc jdn
4358 -- Function: modified-julian-day->date jdn [tz-offset]
4359 -- Function: modified-julian-day->time-monotonic jdn
4360 -- Function: modified-julian-day->time-tai jdn
4361 -- Function: modified-julian-day->time-utc jdn
4362 -- Function: time-monotonic->date time [tz-offset]
4363 -- Function: time-monotonic->time-tai time
4364 -- Function: time-monotonic->time-tai! time
4365 -- Function: time-monotonic->time-utc time
4366 -- Function: time-monotonic->time-utc! time
4367 -- Function: time-tai->date time [tz-offset]
4368 -- Function: time-tai->julian-day time
4369 -- Function: time-tai->modified-julian-day time
4370 -- Function: time-tai->time-monotonic time
4371 -- Function: time-tai->time-monotonic! time
4372 -- Function: time-tai->time-utc time
4373 -- Function: time-tai->time-utc! time
4374 -- Function: time-utc->date time [tz-offset]
4375 -- Function: time-utc->julian-day time
4376 -- Function: time-utc->modified-julian-day time
4377 -- Function: time-utc->time-monotonic time
4378 -- Function: time-utc->time-monotonic! time
4379 -- Function: time-utc->time-tai time
4380 -- Function: time-utc->time-tai! time
4381
4382     Convert between dates, times and days of the respective types.  For
4383     instance ‘time-tai->time-utc’ accepts a TIME object of type
4384     ‘time-tai’ and returns an object of type ‘time-utc’.
4385
4386     The ‘!’ variants may modify their TIME argument to form their
4387     return.  The plain functions create a new object.
4388
4389     For conversions to dates, TZ-OFFSET is seconds east of Greenwich.
4390     The default is the local timezone, at the given time, as provided
4391     by the system, using ‘localtime’ (*note Time::).
4392
4393     On 32-bit systems, ‘localtime’ is limited to a 32-bit ‘time_t’, so
4394     a default TZ-OFFSET is only available for times between Dec 1901
4395     and Jan 2038.  For prior dates an application might like to use the
4396     value in 1902, though some locations have zone changes prior to
4397     that.  For future dates an application might like to assume today’s
4398     rules extend indefinitely.  But for correct daylight savings
4399     transitions it will be necessary to take an offset for the same day
4400     and time but a year in range and which has the same starting
4401     weekday and same leap/non-leap (to support rules like last Sunday
4402     in October).
4403
4404
4405File: guile.info,  Node: SRFI-19 Date to string,  Next: SRFI-19 String to date,  Prev: SRFI-19 Time/Date conversions,  Up: SRFI-19
4406
44077.5.16.5 SRFI-19 Date to string
4408...............................
4409
4410 -- Function: date->string date [format]
4411     Convert a date to a string under the control of a format.  FORMAT
4412     should be a string containing ‘~’ escapes, which will be expanded
4413     as per the following conversion table.  The default FORMAT is ‘~c’,
4414     a locale-dependent date and time.
4415
4416     Many of these conversion characters are the same as POSIX
4417     ‘strftime’ (*note Time::), but there are some extras and some
4418     variations.
4419
4420     ~~     literal ~
4421     ~a     locale abbreviated weekday, eg. ‘Sun’
4422     ~A     locale full weekday, eg. ‘Sunday’
4423     ~b     locale abbreviated month, eg. ‘Jan’
4424     ~B     locale full month, eg. ‘January’
4425     ~c     locale date and time, eg.
4426            ‘Fri Jul 14 20:28:42-0400 2000’
4427     ~d     day of month, zero padded, ‘01’ to ‘31’
4428
4429     ~e     day of month, blank padded, ‘ 1’ to ‘31’
4430     ~f     seconds and fractional seconds, with locale
4431            decimal point, eg. ‘5.2’
4432     ~h     same as ~b
4433     ~H     hour, 24-hour clock, zero padded, ‘00’ to ‘23’
4434     ~I     hour, 12-hour clock, zero padded, ‘01’ to ‘12’
4435     ~j     day of year, zero padded, ‘001’ to ‘366’
4436     ~k     hour, 24-hour clock, blank padded, ‘ 0’ to ‘23’
4437     ~l     hour, 12-hour clock, blank padded, ‘ 1’ to ‘12’
4438     ~m     month, zero padded, ‘01’ to ‘12’
4439     ~M     minute, zero padded, ‘00’ to ‘59’
4440     ~n     newline
4441     ~N     nanosecond, zero padded, ‘000000000’ to
4442            ‘999999999’
4443     ~p     locale AM or PM
4444     ~r     time, 12 hour clock, ‘~I:~M:~S ~p’
4445     ~s     number of full seconds since “the epoch” in UTC
4446     ~S     second, zero padded ‘00’ to ‘60’
4447            (usual limit is 59, 60 is a leap second)
4448     ~t     horizontal tab character
4449     ~T     time, 24 hour clock, ‘~H:~M:~S’
4450     ~U     week of year, Sunday first day of week, ‘00’ to
4451            ‘52’
4452     ~V     week of year, Monday first day of week, ‘01’ to
4453            ‘53’
4454     ~w     day of week, 0 for Sunday, ‘0’ to ‘6’
4455     ~W     week of year, Monday first day of week, ‘00’ to
4456            ‘52’
4457
4458     ~y     year, two digits, ‘00’ to ‘99’
4459     ~Y     year, full, eg. ‘2003’
4460     ~z     time zone, RFC-822 style
4461     ~Z     time zone symbol (not currently implemented)
4462     ~1     ISO-8601 date, ‘~Y-~m-~d’
4463     ~2     ISO-8601 time+zone, ‘~H:~M:~S~z’
4464     ~3     ISO-8601 time, ‘~H:~M:~S’
4465     ~4     ISO-8601 date/time+zone, ‘~Y-~m-~dT~H:~M:~S~z’
4466     ~5     ISO-8601 date/time, ‘~Y-~m-~dT~H:~M:~S’
4467
4468   Conversions ‘~D’, ‘~x’ and ‘~X’ are not currently described here,
4469since the specification and reference implementation differ.
4470
4471   Conversion is locale-dependent on systems that support it (*note
4472Accessing Locale Information::).  *Note ‘setlocale’: Locales, for
4473information on how to change the current locale.
4474
4475
4476File: guile.info,  Node: SRFI-19 String to date,  Prev: SRFI-19 Date to string,  Up: SRFI-19
4477
44787.5.16.6 SRFI-19 String to date
4479...............................
4480
4481 -- Function: string->date input template
4482     Convert an INPUT string to a date under the control of a TEMPLATE
4483     string.  Return a newly created date object.
4484
4485     Literal characters in TEMPLATE must match characters in INPUT and
4486     ‘~’ escapes must match the input forms described in the table
4487     below.  “Skip to” means characters up to one of the given type are
4488     ignored, or “no skip” for no skipping.  “Read” is what’s then read,
4489     and “Set” is the field affected in the date object.
4490
4491     For example ‘~Y’ skips input characters until a digit is reached,
4492     at which point it expects a year and stores that to the year field
4493     of the date.
4494
4495            Skip to            Read                        Set
4496
4497     ~~     no skip            literal ~                   nothing
4498
4499     ~a     char-alphabetic?   locale abbreviated          nothing
4500                               weekday name
4501     ~A     char-alphabetic?   locale full weekday name    nothing
4502
4503     ~b     char-alphabetic?   locale abbreviated month    date-month
4504                               name
4505     ~B     char-alphabetic?   locale full month name      date-month
4506
4507     ~d     char-numeric?      day of month                date-day
4508
4509     ~e     no skip            day of month, blank         date-day
4510                               padded
4511     ~h     same as ‘~b’
4512
4513     ~H     char-numeric?      hour                        date-hour
4514
4515     ~k     no skip            hour, blank padded          date-hour
4516
4517     ~m     char-numeric?      month                       date-month
4518
4519     ~M     char-numeric?      minute                      date-minute
4520
4521     ~N     char-numeric?      nanosecond                  date-nanosecond
4522
4523     ~S     char-numeric?      second                      date-second
4524
4525     ~y     no skip            2-digit year                date-year within
4526                                                           50 years
4527
4528     ~Y     char-numeric?      year                        date-year
4529
4530     ~z     no skip            time zone                   date-zone-offset
4531
4532     Notice that the weekday matching forms don’t affect the date object
4533     returned, instead the weekday will be derived from the day, month
4534     and year.
4535
4536     Conversion is locale-dependent on systems that support it (*note
4537     Accessing Locale Information::).  *Note ‘setlocale’: Locales, for
4538     information on how to change the current locale.
4539
4540
4541File: guile.info,  Node: SRFI-23,  Next: SRFI-26,  Prev: SRFI-19,  Up: SRFI Support
4542
45437.5.17 SRFI-23 - Error Reporting
4544--------------------------------
4545
4546The SRFI-23 ‘error’ procedure is always available.
4547
4548
4549File: guile.info,  Node: SRFI-26,  Next: SRFI-27,  Prev: SRFI-23,  Up: SRFI Support
4550
45517.5.18 SRFI-26 - specializing parameters
4552----------------------------------------
4553
4554This SRFI provides a syntax for conveniently specializing selected
4555parameters of a function.  It can be used with,
4556
4557     (use-modules (srfi srfi-26))
4558
4559 -- library syntax: cut slot1 slot2 ...
4560 -- library syntax: cute slot1 slot2 ...
4561     Return a new procedure which will make a call (SLOT1 SLOT2 ...) but
4562     with selected parameters specialized to given expressions.
4563
4564     An example will illustrate the idea.  The following is a
4565     specialization of ‘write’, sending output to ‘my-output-port’,
4566
4567          (cut write <> my-output-port)
45684569          (lambda (obj) (write obj my-output-port))
4570
4571     The special symbol ‘<>’ indicates a slot to be filled by an
4572     argument to the new procedure.  ‘my-output-port’ on the other hand
4573     is an expression to be evaluated and passed, ie. it specializes the
4574     behaviour of ‘write’.
4575
4576     <>
4577          A slot to be filled by an argument from the created procedure.
4578          Arguments are assigned to ‘<>’ slots in the order they appear
4579          in the ‘cut’ form, there’s no way to re-arrange arguments.
4580
4581          The first argument to ‘cut’ is usually a procedure (or
4582          expression giving a procedure), but ‘<>’ is allowed there too.
4583          For example,
4584
4585               (cut <> 1 2 3)
45864587               (lambda (proc) (proc 1 2 3))
4588
4589     <...>
4590          A slot to be filled by all remaining arguments from the new
4591          procedure.  This can only occur at the end of a ‘cut’ form.
4592
4593          For example, a procedure taking a variable number of arguments
4594          like ‘max’ but in addition enforcing a lower bound,
4595
4596               (define my-lower-bound 123)
4597
4598               (cut max my-lower-bound <...>)
45994600               (lambda arglist (apply max my-lower-bound arglist))
4601
4602     For ‘cut’ the specializing expressions are evaluated each time the
4603     new procedure is called.  For ‘cute’ they’re evaluated just once,
4604     when the new procedure is created.  The name ‘cute’ stands for
4605     “‘cut’ with evaluated arguments”.  In all cases the evaluations
4606     take place in an unspecified order.
4607
4608     The following illustrates the difference between ‘cut’ and ‘cute’,
4609
4610          (cut format <> "the time is ~s" (current-time))
46114612          (lambda (port) (format port "the time is ~s" (current-time)))
4613
4614          (cute format <> "the time is ~s" (current-time))
46154616          (let ((val (current-time)))
4617            (lambda (port) (format port "the time is ~s" val))
4618
4619     (There’s no provision for a mixture of ‘cut’ and ‘cute’ where some
4620     expressions would be evaluated every time but others evaluated only
4621     once.)
4622
4623     ‘cut’ is really just a shorthand for the sort of ‘lambda’ forms
4624     shown in the above examples.  But notice ‘cut’ avoids the need to
4625     name unspecialized parameters, and is more compact.  Use in
4626     functional programming style or just with ‘map’, ‘for-each’ or
4627     similar is typical.
4628
4629          (map (cut * 2 <>) '(1 2 3 4))
4630
4631          (for-each (cut write <> my-port) my-list)
4632
4633
4634File: guile.info,  Node: SRFI-27,  Next: SRFI-28,  Prev: SRFI-26,  Up: SRFI Support
4635
46367.5.19 SRFI-27 - Sources of Random Bits
4637---------------------------------------
4638
4639This subsection is based on the specification of SRFI-27
4640(http://srfi.schemers.org/srfi-27/srfi-27.html) written by Sebastian
4641Egner.
4642
4643   This SRFI provides access to a (pseudo) random number generator; for
4644Guile’s built-in random number facilities, which SRFI-27 is implemented
4645upon, *Note Random::.  With SRFI-27, random numbers are obtained from a
4646_random source_, which encapsulates a random number generation algorithm
4647and its state.
4648
4649* Menu:
4650
4651* SRFI-27 Default Random Source::    Obtaining random numbers
4652* SRFI-27 Random Sources::           Creating and manipulating random sources
4653* SRFI-27 Random Number Generators:: Obtaining random number generators
4654
4655
4656File: guile.info,  Node: SRFI-27 Default Random Source,  Next: SRFI-27 Random Sources,  Up: SRFI-27
4657
46587.5.19.1 The Default Random Source
4659..................................
4660
4661 -- Function: random-integer n
4662     Return a random number between zero (inclusive) and N (exclusive),
4663     using the default random source.  The numbers returned have a
4664     uniform distribution.
4665
4666 -- Function: random-real
4667     Return a random number in (0,1), using the default random source.
4668     The numbers returned have a uniform distribution.
4669
4670 -- Function: default-random-source
4671     A random source from which ‘random-integer’ and ‘random-real’ have
4672     been derived using ‘random-source-make-integers’ and
4673     ‘random-source-make-reals’ (*note SRFI-27 Random Number
4674     Generators:: for those procedures).  Note that an assignment to
4675     ‘default-random-source’ does not change ‘random-integer’ or
4676     ‘random-real’; it is also strongly recommended not to assign a new
4677     value.
4678
4679
4680File: guile.info,  Node: SRFI-27 Random Sources,  Next: SRFI-27 Random Number Generators,  Prev: SRFI-27 Default Random Source,  Up: SRFI-27
4681
46827.5.19.2 Random Sources
4683.......................
4684
4685 -- Function: make-random-source
4686     Create a new random source.  The stream of random numbers obtained
4687     from each random source created by this procedure will be
4688     identical, unless its state is changed by one of the procedures
4689     below.
4690
4691 -- Function: random-source? object
4692     Tests whether OBJECT is a random source.  Random sources are a
4693     disjoint type.
4694
4695 -- Function: random-source-randomize! source
4696     Attempt to set the state of the random source to a truly random
4697     value.  The current implementation uses a seed based on the current
4698     system time.
4699
4700 -- Function: random-source-pseudo-randomize! source i j
4701     Changes the state of the random source s into the initial state of
4702     the (I, J)-th independent random source, where I and J are
4703     non-negative integers.  This procedure provides a mechanism to
4704     obtain a large number of independent random sources (usually all
4705     derived from the same backbone generator), indexed by two integers.
4706     In contrast to ‘random-source-randomize!’, this procedure is
4707     entirely deterministic.
4708
4709   The state associated with a random state can be obtained an
4710reinstated with the following procedures:
4711
4712 -- Function: random-source-state-ref source
4713 -- Function: random-source-state-set! source state
4714     Get and set the state of a random source.  No assumptions should be
4715     made about the nature of the state object, besides it having an
4716     external representation (i.e. it can be passed to ‘write’ and
4717     subsequently ‘read’ back).
4718
4719
4720File: guile.info,  Node: SRFI-27 Random Number Generators,  Prev: SRFI-27 Random Sources,  Up: SRFI-27
4721
47227.5.19.3 Obtaining random number generator procedures
4723.....................................................
4724
4725 -- Function: random-source-make-integers source
4726     Obtains a procedure to generate random integers using the random
4727     source SOURCE.  The returned procedure takes a single argument N,
4728     which must be a positive integer, and returns the next uniformly
4729     distributed random integer from the interval {0, ..., N-1} by
4730     advancing the state of SOURCE.
4731
4732     If an application obtains and uses several generators for the same
4733     random source SOURCE, a call to any of these generators advances
4734     the state of SOURCE.  Hence, the generators do not produce the same
4735     sequence of random integers each but rather share a state.  This
4736     also holds for all other types of generators derived from a fixed
4737     random sources.
4738
4739     While the SRFI text specifies that “Implementations that support
4740     concurrency make sure that the state of a generator is properly
4741     advanced”, this is currently not the case in Guile’s implementation
4742     of SRFI-27, as it would cause a severe performance penalty.  So in
4743     multi-threaded programs, you either must perform locking on random
4744     sources shared between threads yourself, or use different random
4745     sources for multiple threads.
4746
4747 -- Function: random-source-make-reals source
4748 -- Function: random-source-make-reals source unit
4749     Obtains a procedure to generate random real numbers 0 < x < 1 using
4750     the random source SOURCE.  The procedure rand is called without
4751     arguments.
4752
4753     The optional parameter UNIT determines the type of numbers being
4754     produced by the returned procedure and the quantization of the
4755     output.  UNIT must be a number such that 0 < UNIT < 1.  The numbers
4756     created by the returned procedure are of the same numerical type as
4757     UNIT and the potential output values are spaced by at most UNIT.
4758     One can imagine rand to create numbers as X * UNIT where X is a
4759     random integer in {1, ..., floor(1/unit)-1}.  Note, however, that
4760     this need not be the way the values are actually created and that
4761     the actual resolution of rand can be much higher than unit.  In
4762     case UNIT is absent it defaults to a reasonably small value
4763     (related to the width of the mantissa of an efficient number
4764     format).
4765
4766
4767File: guile.info,  Node: SRFI-28,  Next: SRFI-30,  Prev: SRFI-27,  Up: SRFI Support
4768
47697.5.20 SRFI-28 - Basic Format Strings
4770-------------------------------------
4771
4772SRFI-28 provides a basic ‘format’ procedure that provides only the ‘~a’,
4773‘~s’, ‘~%’, and ‘~~’ format specifiers.  You can import this procedure
4774by using:
4775
4776     (use-modules (srfi srfi-28))
4777
4778 -- Scheme Procedure: format message arg ...
4779     Returns a formatted message, using MESSAGE as the format string,
4780     which can contain the following format specifiers:
4781
4782     ‘~a’
4783          Insert the textual representation of the next ARG, as if
4784          printed by ‘display’.
4785
4786     ‘~s’
4787          Insert the textual representation of the next ARG, as if
4788          printed by ‘write’.
4789
4790     ‘~%’
4791          Insert a newline.
4792
4793     ‘~~’
4794          Insert a tilde.
4795
4796     This procedure is the same as calling ‘simple-format’ (*note Simple
4797     Output::) with ‘#f’ as the destination.
4798
4799
4800File: guile.info,  Node: SRFI-30,  Next: SRFI-31,  Prev: SRFI-28,  Up: SRFI Support
4801
48027.5.21 SRFI-30 - Nested Multi-line Comments
4803-------------------------------------------
4804
4805Starting from version 2.0, Guile’s ‘read’ supports SRFI-30/R6RS nested
4806multi-line comments by default, *note Block Comments::.
4807
4808
4809File: guile.info,  Node: SRFI-31,  Next: SRFI-34,  Prev: SRFI-30,  Up: SRFI Support
4810
48117.5.22 SRFI-31 - A special form ‘rec’ for recursive evaluation
4812--------------------------------------------------------------
4813
4814SRFI-31 defines a special form that can be used to create
4815self-referential expressions more conveniently.  The syntax is as
4816follows:
4817
4818     <rec expression> --> (rec <variable> <expression>)
4819     <rec expression> --> (rec (<variable>+) <body>)
4820
4821   The first syntax can be used to create self-referential expressions,
4822for example:
4823
4824       guile> (define tmp (rec ones (cons 1 (delay ones))))
4825
4826   The second syntax can be used to create anonymous recursive
4827functions:
4828
4829       guile> (define tmp (rec (display-n item n)
4830                            (if (positive? n)
4831                                (begin (display n) (display-n (- n 1))))))
4832       guile> (tmp 42 3)
4833       424242
4834       guile>
4835
4836
4837File: guile.info,  Node: SRFI-34,  Next: SRFI-35,  Prev: SRFI-31,  Up: SRFI Support
4838
48397.5.23 SRFI-34 - Exception handling for programs
4840------------------------------------------------
4841
4842Guile provides an implementation of SRFI-34’s exception handling
4843mechanisms (http://srfi.schemers.org/srfi-34/srfi-34.html) as an
4844alternative to its own built-in mechanisms (*note Exceptions::).  It can
4845be made available as follows:
4846
4847     (use-modules (srfi srfi-34))
4848
4849   *Note Raising and Handling Exceptions::, for more on
4850‘with-exception-handler’ and ‘raise’ (known as ‘raise-exception’ in core
4851Guile).
4852
4853   SRFI-34’s ‘guard’ form is syntactic sugar over
4854‘with-exception-handler’:
4855
4856 -- Syntax: guard (var clause ...) body ...
4857     Evaluate BODY with an exception handler that binds the raised
4858     object to VAR and within the scope of that binding evaluates
4859     CLAUSE... as if they were the clauses of a cond expression.  That
4860     implicit cond expression is evaluated with the continuation and
4861     dynamic environment of the guard expression.
4862
4863     If every CLAUSE’s test evaluates to false and there is no ‘else’
4864     clause, then ‘raise’ is re-invoked on the raised object within the
4865     dynamic environment of the original call to ‘raise’ except that the
4866     current exception handler is that of the ‘guard’ expression.
4867
4868
4869File: guile.info,  Node: SRFI-35,  Next: SRFI-37,  Prev: SRFI-34,  Up: SRFI Support
4870
48717.5.24 SRFI-35 - Conditions
4872---------------------------
4873
4874SRFI-35 (http://srfi.schemers.org/srfi-35/srfi-35.html) defines
4875“conditions”, a data structure akin to records designed to convey
4876information about exceptional conditions between parts of a program.  It
4877is normally used in conjunction with SRFI-34’s ‘raise’:
4878
4879     (raise (condition (&message
4880                         (message "An error occurred"))))
4881
4882   Users can define “condition types” containing arbitrary information.
4883Condition types may inherit from one another.  This allows the part of
4884the program that handles (or “catches”) conditions to get accurate
4885information about the exceptional condition that arose.
4886
4887   SRFI-35 conditions are made available using:
4888
4889     (use-modules (srfi srfi-35))
4890
4891   The procedures available to manipulate condition types are the
4892following:
4893
4894 -- Scheme Procedure: make-condition-type id parent field-names
4895     Return a new condition type named ID, inheriting from PARENT, and
4896     with the fields whose names are listed in FIELD-NAMES.  FIELD-NAMES
4897     must be a list of symbols and must not contain names already used
4898     by PARENT or one of its supertypes.
4899
4900 -- Scheme Procedure: condition-type? obj
4901     Return true if OBJ is a condition type.
4902
4903   Conditions can be created and accessed with the following procedures:
4904
4905 -- Scheme Procedure: make-condition type . field+value
4906     Return a new condition of type TYPE with fields initialized as
4907     specified by FIELD+VALUE, a sequence of field names (symbols) and
4908     values as in the following example:
4909
4910          (let ((&ct (make-condition-type 'foo &condition '(a b c))))
4911            (make-condition &ct 'a 1 'b 2 'c 3))
4912
4913     Note that all fields of TYPE and its supertypes must be specified.
4914
4915 -- Scheme Procedure: make-compound-condition condition1 condition2 ...
4916     Return a new compound condition composed of CONDITION1 CONDITION2
4917     ....  The returned condition has the type of each condition of
4918     condition1 condition2 ... (per ‘condition-has-type?’).
4919
4920 -- Scheme Procedure: condition-has-type? c type
4921     Return true if condition C has type TYPE.
4922
4923 -- Scheme Procedure: condition-ref c field-name
4924     Return the value of the field named FIELD-NAME from condition C.
4925
4926     If C is a compound condition and several underlying condition types
4927     contain a field named FIELD-NAME, then the value of the first such
4928     field is returned, using the order in which conditions were passed
4929     to ‘make-compound-condition’.
4930
4931 -- Scheme Procedure: extract-condition c type
4932     Return a condition of condition type TYPE with the field values
4933     specified by C.
4934
4935     If C is a compound condition, extract the field values from the
4936     subcondition belonging to TYPE that appeared first in the call to
4937     ‘make-compound-condition’ that created the condition.
4938
4939   Convenience macros are also available to create condition types and
4940conditions.
4941
4942 -- library syntax: define-condition-type type supertype predicate
4943          field-spec...
4944     Define a new condition type named TYPE that inherits from
4945     SUPERTYPE.  In addition, bind PREDICATE to a type predicate that
4946     returns true when passed a condition of type TYPE or any of its
4947     subtypes.  FIELD-SPEC must have the form ‘(field accessor)’ where
4948     FIELD is the name of field of TYPE and ACCESSOR is the name of a
4949     procedure to access field FIELD in conditions of type TYPE.
4950
4951     The example below defines condition type ‘&foo’, inheriting from
4952     ‘&condition’ with fields ‘a’, ‘b’ and ‘c’:
4953
4954          (define-condition-type &foo &condition
4955            foo-condition?
4956            (a  foo-a)
4957            (b  foo-b)
4958            (c  foo-c))
4959
4960 -- library syntax: condition type-field-binding1 type-field-binding2
4961          ...
4962     Return a new condition or compound condition, initialized according
4963     to TYPE-FIELD-BINDING1 TYPE-FIELD-BINDING2 ....  Each
4964     TYPE-FIELD-BINDING must have the form ‘(type field-specs...)’,
4965     where TYPE is the name of a variable bound to a condition type;
4966     each FIELD-SPEC must have the form ‘(field-name value)’ where
4967     FIELD-NAME is a symbol denoting the field being initialized to
4968     VALUE.  As for ‘make-condition’, all fields must be specified.
4969
4970     The following example returns a simple condition:
4971
4972          (condition (&message (message "An error occurred")))
4973
4974     The one below returns a compound condition:
4975
4976          (condition (&message (message "An error occurred"))
4977                     (&serious))
4978
4979   Finally, SRFI-35 defines a several standard condition types.
4980
4981 -- Variable: &condition
4982     This condition type is the root of all condition types.  It has no
4983     fields.
4984
4985 -- Variable: &message
4986     A condition type that carries a message describing the nature of
4987     the condition to humans.
4988
4989 -- Scheme Procedure: message-condition? c
4990     Return true if C is of type ‘&message’ or one of its subtypes.
4991
4992 -- Scheme Procedure: condition-message c
4993     Return the message associated with message condition C.
4994
4995 -- Variable: &serious
4996     This type describes conditions serious enough that they cannot
4997     safely be ignored.  It has no fields.
4998
4999 -- Scheme Procedure: serious-condition? c
5000     Return true if C is of type ‘&serious’ or one of its subtypes.
5001
5002 -- Variable: &error
5003     This condition describes errors, typically caused by something that
5004     has gone wrong in the interaction of the program with the external
5005     world or the user.
5006
5007 -- Scheme Procedure: error? c
5008     Return true if C is of type ‘&error’ or one of its subtypes.
5009
5010   As an implementation note, condition objects in Guile are the same as
5011“exception objects”.  *Note Exception Objects::.  The ‘&condition’,
5012‘&serious’, and ‘&error’ condition types are known in core Guile as
5013‘&exception’, ‘&error’, and ‘&external-error’, respectively.
5014
5015
5016File: guile.info,  Node: SRFI-37,  Next: SRFI-38,  Prev: SRFI-35,  Up: SRFI Support
5017
50187.5.25 SRFI-37 - args-fold
5019--------------------------
5020
5021This is a processor for GNU ‘getopt_long’-style program arguments.  It
5022provides an alternative, less declarative interface than ‘getopt-long’
5023in ‘(ice-9 getopt-long)’ (*note The (ice-9 getopt-long) Module:
5024getopt-long.).  Unlike ‘getopt-long’, it supports repeated options and
5025any number of short and long names per option.  Access it with:
5026
5027     (use-modules (srfi srfi-37))
5028
5029   SRFI-37 principally provides an ‘option’ type and the ‘args-fold’
5030function.  To use the library, create a set of options with ‘option’ and
5031use it as a specification for invoking ‘args-fold’.
5032
5033   Here is an example of a simple argument processor for the typical
5034‘--version’ and ‘--help’ options, which returns a backwards list of
5035files given on the command line:
5036
5037     (args-fold (cdr (program-arguments))
5038                (let ((display-and-exit-proc
5039                       (lambda (msg)
5040                         (lambda (opt name arg loads)
5041                           (display msg) (quit)))))
5042                  (list (option '(#\v "version") #f #f
5043                                (display-and-exit-proc "Foo version 42.0\n"))
5044                        (option '(#\h "help") #f #f
5045                                (display-and-exit-proc
5046                                 "Usage: foo scheme-file ..."))))
5047                (lambda (opt name arg loads)
5048                  (error "Unrecognized option `~A'" name))
5049                (lambda (op loads) (cons op loads))
5050                '())
5051
5052 -- Scheme Procedure: option names required-arg? optional-arg? processor
5053     Return an object that specifies a single kind of program option.
5054
5055     NAMES is a list of command-line option names, and should consist of
5056     characters for traditional ‘getopt’ short options and strings for
5057     ‘getopt_long’-style long options.
5058
5059     REQUIRED-ARG? and OPTIONAL-ARG? are mutually exclusive; one or both
5060     must be ‘#f’.  If REQUIRED-ARG?, the option must be followed by an
5061     argument on the command line, such as ‘--opt=value’ for long
5062     options, or an error will be signalled.  If OPTIONAL-ARG?, an
5063     argument will be taken if available.
5064
5065     PROCESSOR is a procedure that takes at least 3 arguments, called
5066     when ‘args-fold’ encounters the option: the containing option
5067     object, the name used on the command line, and the argument given
5068     for the option (or ‘#f’ if none).  The rest of the arguments are
5069     ‘args-fold’ “seeds”, and the PROCESSOR should return seeds as well.
5070
5071 -- Scheme Procedure: option-names opt
5072 -- Scheme Procedure: option-required-arg? opt
5073 -- Scheme Procedure: option-optional-arg? opt
5074 -- Scheme Procedure: option-processor opt
5075     Return the specified field of OPT, an option object, as described
5076     above for ‘option’.
5077
5078 -- Scheme Procedure: args-fold args options unrecognized-option-proc
5079          operand-proc seed ...
5080     Process ARGS, a list of program arguments such as that returned by
5081     ‘(cdr (program-arguments))’, in order against OPTIONS, a list of
5082     option objects as described above.  All functions called take the
5083     “seeds”, or the last multiple-values as multiple arguments,
5084     starting with SEED ..., and must return the new seeds.  Return the
5085     final seeds.
5086
5087     Call ‘unrecognized-option-proc’, which is like an option object’s
5088     processor, for any options not found in OPTIONS.
5089
5090     Call ‘operand-proc’ with any items on the command line that are not
5091     named options.  This includes arguments after ‘--’.  It is called
5092     with the argument in question, as well as the seeds.
5093
5094
5095File: guile.info,  Node: SRFI-38,  Next: SRFI-39,  Prev: SRFI-37,  Up: SRFI Support
5096
50977.5.26 SRFI-38 - External Representation for Data With Shared Structure
5098-----------------------------------------------------------------------
5099
5100This subsection is based on the specification of SRFI-38
5101(http://srfi.schemers.org/srfi-38/srfi-38.html) written by Ray
5102Dillinger.
5103
5104   This SRFI creates an alternative external representation for data
5105written and read using ‘write-with-shared-structure’ and
5106‘read-with-shared-structure’.  It is identical to the grammar for
5107external representation for data written and read with ‘write’ and
5108‘read’ given in section 7 of R5RS, except that the single production
5109
5110     <datum> --> <simple datum> | <compound datum>
5111
5112   is replaced by the following five productions:
5113
5114     <datum> --> <defining datum> | <nondefining datum> | <defined datum>
5115     <defining datum> -->  #<indexnum>=<nondefining datum>
5116     <defined datum> --> #<indexnum>#
5117     <nondefining datum> --> <simple datum> | <compound datum>
5118     <indexnum> --> <digit 10>+
5119
5120 -- Scheme procedure: write-with-shared-structure obj
5121 -- Scheme procedure: write-with-shared-structure obj port
5122 -- Scheme procedure: write-with-shared-structure obj port optarg
5123
5124     Writes an external representation of OBJ to the given port.
5125     Strings that appear in the written representation are enclosed in
5126     doublequotes, and within those strings backslash and doublequote
5127     characters are escaped by backslashes.  Character objects are
5128     written using the ‘#\’ notation.
5129
5130     Objects which denote locations rather than values (cons cells,
5131     vectors, and non-zero-length strings in R5RS scheme; also Guile’s
5132     structs, bytevectors and ports and hash-tables), if they appear at
5133     more than one point in the data being written, are preceded by
5134     ‘#N=’ the first time they are written and replaced by ‘#N#’ all
5135     subsequent times they are written, where N is a natural number used
5136     to identify that particular object.  If objects which denote
5137     locations occur only once in the structure, then
5138     ‘write-with-shared-structure’ must produce the same external
5139     representation for those objects as ‘write’.
5140
5141     ‘write-with-shared-structure’ terminates in finite time and
5142     produces a finite representation when writing finite data.
5143
5144     ‘write-with-shared-structure’ returns an unspecified value.  The
5145     PORT argument may be omitted, in which case it defaults to the
5146     value returned by ‘(current-output-port)’.  The OPTARG argument may
5147     also be omitted.  If present, its effects on the output and return
5148     value are unspecified but ‘write-with-shared-structure’ must still
5149     write a representation that can be read by
5150     ‘read-with-shared-structure’.  Some implementations may wish to use
5151     OPTARG to specify formatting conventions, numeric radixes, or
5152     return values.  Guile’s implementation ignores OPTARG.
5153
5154     For example, the code
5155
5156          (begin (define a (cons 'val1 'val2))
5157                 (set-cdr! a a)
5158                 (write-with-shared-structure a))
5159
5160     should produce the output ‘#1=(val1 . #1#)’.  This shows a cons
5161     cell whose ‘cdr’ contains itself.
5162
5163 -- Scheme procedure: read-with-shared-structure
5164 -- Scheme procedure: read-with-shared-structure port
5165
5166     ‘read-with-shared-structure’ converts the external representations
5167     of Scheme objects produced by ‘write-with-shared-structure’ into
5168     Scheme objects.  That is, it is a parser for the nonterminal
5169     ‘<datum>’ in the augmented external representation grammar defined
5170     above.  ‘read-with-shared-structure’ returns the next object
5171     parsable from the given input port, updating PORT to point to the
5172     first character past the end of the external representation of the
5173     object.
5174
5175     If an end-of-file is encountered in the input before any characters
5176     are found that can begin an object, then an end-of-file object is
5177     returned.  The port remains open, and further attempts to read it
5178     (by ‘read-with-shared-structure’ or ‘read’ will also return an
5179     end-of-file object.  If an end of file is encountered after the
5180     beginning of an object’s external representation, but the external
5181     representation is incomplete and therefore not parsable, an error
5182     is signalled.
5183
5184     The PORT argument may be omitted, in which case it defaults to the
5185     value returned by ‘(current-input-port)’.  It is an error to read
5186     from a closed port.
5187
5188
5189File: guile.info,  Node: SRFI-39,  Next: SRFI-41,  Prev: SRFI-38,  Up: SRFI Support
5190
51917.5.27 SRFI-39 - Parameters
5192---------------------------
5193
5194This SRFI adds support for dynamically-scoped parameters.  SRFI 39 is
5195implemented in the Guile core; there’s no module needed to get SRFI-39
5196itself.  Parameters are documented in *note Parameters::.
5197
5198   This module does export one extra function: ‘with-parameters*’.  This
5199is a Guile-specific addition to the SRFI, similar to the core
5200‘with-fluids*’ (*note Fluids and Dynamic States::).
5201
5202 -- Function: with-parameters* param-list value-list thunk
5203     Establish a new dynamic scope, as per ‘parameterize’ above, taking
5204     parameters from PARAM-LIST and corresponding values from
5205     VALUE-LIST.  A call ‘(THUNK)’ is made in the new scope and the
5206     result from that THUNK is the return from ‘with-parameters*’.
5207
5208
5209File: guile.info,  Node: SRFI-41,  Next: SRFI-42,  Prev: SRFI-39,  Up: SRFI Support
5210
52117.5.28 SRFI-41 - Streams
5212------------------------
5213
5214This subsection is based on the specification of SRFI-41
5215(http://srfi.schemers.org/srfi-41/srfi-41.html) by Philip L. Bewig.
5216
5217This SRFI implements streams, sometimes called lazy lists, a sequential
5218data structure containing elements computed only on demand.  A stream is
5219either null or is a pair with a stream in its cdr.  Since elements of a
5220stream are computed only when accessed, streams can be infinite.  Once
5221computed, the value of a stream element is cached in case it is needed
5222again.  SRFI-41 can be made available with:
5223
5224     (use-modules (srfi srfi-41))
5225
5226* Menu:
5227
5228* SRFI-41 Stream Fundamentals::
5229* SRFI-41 Stream Primitives::
5230* SRFI-41 Stream Library::
5231
5232
5233File: guile.info,  Node: SRFI-41 Stream Fundamentals,  Next: SRFI-41 Stream Primitives,  Up: SRFI-41
5234
52357.5.28.1 SRFI-41 Stream Fundamentals
5236....................................
5237
5238SRFI-41 Streams are based on two mutually-recursive abstract data types:
5239An object of the ‘stream’ abstract data type is a promise that, when
5240forced, is either ‘stream-null’ or is an object of type ‘stream-pair’.
5241An object of the ‘stream-pair’ abstract data type contains a
5242‘stream-car’ and a ‘stream-cdr’, which must be a ‘stream’.  The
5243essential feature of streams is the systematic suspensions of the
5244recursive promises between the two data types.
5245
5246   The object stored in the ‘stream-car’ of a ‘stream-pair’ is a promise
5247that is forced the first time the ‘stream-car’ is accessed; its value is
5248cached in case it is needed again.  The object may have any type, and
5249different stream elements may have different types.  If the ‘stream-car’
5250is never accessed, the object stored there is never evaluated.
5251Likewise, the ‘stream-cdr’ is a promise to return a stream, and is only
5252forced on demand.
5253
5254
5255File: guile.info,  Node: SRFI-41 Stream Primitives,  Next: SRFI-41 Stream Library,  Prev: SRFI-41 Stream Fundamentals,  Up: SRFI-41
5256
52577.5.28.2 SRFI-41 Stream Primitives
5258..................................
5259
5260This library provides eight operators: constructors for ‘stream-null’
5261and ‘stream-pair’s, type predicates for streams and the two kinds of
5262streams, accessors for both fields of a ‘stream-pair’, and a lambda that
5263creates procedures that return streams.
5264
5265 -- Scheme Variable: stream-null
5266     A promise that, when forced, is a single object, distinguishable
5267     from all other objects, that represents the null stream.
5268     ‘stream-null’ is immutable and unique.
5269
5270 -- Scheme Syntax: stream-cons object-expr stream-expr
5271     Creates a newly-allocated stream containing a promise that, when
5272     forced, is a ‘stream-pair’ with OBJECT-EXPR in its ‘stream-car’ and
5273     STREAM-EXPR in its ‘stream-cdr’.  Neither OBJECT-EXPR nor
5274     STREAM-EXPR is evaluated when ‘stream-cons’ is called.
5275
5276     Once created, a ‘stream-pair’ is immutable; there is no
5277     ‘stream-set-car!’ or ‘stream-set-cdr!’ that modifies an existing
5278     stream-pair.  There is no dotted-pair or improper stream as with
5279     lists.
5280
5281 -- Scheme Procedure: stream? object
5282     Returns true if OBJECT is a stream, otherwise returns false.  If
5283     OBJECT is a stream, its promise will not be forced.  If ‘(stream?
5284     obj)’ returns true, then one of ‘(stream-null? obj)’ or
5285     ‘(stream-pair? obj)’ will return true and the other will return
5286     false.
5287
5288 -- Scheme Procedure: stream-null? object
5289     Returns true if OBJECT is the distinguished null stream, otherwise
5290     returns false.  If OBJECT is a stream, its promise will be forced.
5291
5292 -- Scheme Procedure: stream-pair? object
5293     Returns true if OBJECT is a ‘stream-pair’ constructed by
5294     ‘stream-cons’, otherwise returns false.  If OBJECT is a stream, its
5295     promise will be forced.
5296
5297 -- Scheme Procedure: stream-car stream
5298     Returns the object stored in the ‘stream-car’ of STREAM.  An error
5299     is signalled if the argument is not a ‘stream-pair’.  This causes
5300     the OBJECT-EXPR passed to ‘stream-cons’ to be evaluated if it had
5301     not yet been; the value is cached in case it is needed again.
5302
5303 -- Scheme Procedure: stream-cdr stream
5304     Returns the stream stored in the ‘stream-cdr’ of STREAM.  An error
5305     is signalled if the argument is not a ‘stream-pair’.
5306
5307 -- Scheme Syntax: stream-lambda formals body ...
5308     Creates a procedure that returns a promise to evaluate the BODY of
5309     the procedure.  The last BODY expression to be evaluated must yield
5310     a stream.  As with normal ‘lambda’, FORMALS may be a single
5311     variable name, in which case all the formal arguments are collected
5312     into a single list, or a list of variable names, which may be null
5313     if there are no arguments, proper if there are an exact number of
5314     arguments, or dotted if a fixed number of arguments is to be
5315     followed by zero or more arguments collected into a list.  BODY
5316     must contain at least one expression, and may contain internal
5317     definitions preceding any expressions to be evaluated.
5318
5319     (define strm123
5320       (stream-cons 1
5321         (stream-cons 2
5322           (stream-cons 3
5323             stream-null))))
5324
5325     (stream-car strm123) ⇒ 1
5326     (stream-car (stream-cdr strm123) ⇒ 2
5327
5328     (stream-pair?
5329       (stream-cdr
5330         (stream-cons (/ 1 0) stream-null))) ⇒ #f
5331
5332     (stream? (list 1 2 3)) ⇒ #f
5333
5334     (define iter
5335       (stream-lambda (f x)
5336         (stream-cons x (iter f (f x)))))
5337
5338     (define nats (iter (lambda (x) (+ x 1)) 0))
5339
5340     (stream-car (stream-cdr nats)) ⇒ 1
5341
5342     (define stream-add
5343       (stream-lambda (s1 s2)
5344         (stream-cons
5345           (+ (stream-car s1) (stream-car s2))
5346           (stream-add (stream-cdr s1)
5347                       (stream-cdr s2)))))
5348
5349     (define evens (stream-add nats nats))
5350
5351     (stream-car evens) ⇒ 0
5352     (stream-car (stream-cdr evens)) ⇒ 2
5353     (stream-car (stream-cdr (stream-cdr evens))) ⇒ 4
5354
5355
5356File: guile.info,  Node: SRFI-41 Stream Library,  Prev: SRFI-41 Stream Primitives,  Up: SRFI-41
5357
53587.5.28.3 SRFI-41 Stream Library
5359...............................
5360
5361 -- Scheme Syntax: define-stream (name args ...) body ...
5362     Creates a procedure that returns a stream, and may appear anywhere
5363     a normal ‘define’ may appear, including as an internal definition.
5364     It may contain internal definitions of its own.  The defined
5365     procedure takes arguments in the same way as ‘stream-lambda’.
5366     ‘define-stream’ is syntactic sugar on ‘stream-lambda’; see also
5367     ‘stream-let’, which is also a sugaring of ‘stream-lambda’.
5368
5369     A simple version of ‘stream-map’ that takes only a single input
5370     stream calls itself recursively:
5371
5372          (define-stream (stream-map proc strm)
5373            (if (stream-null? strm)
5374                stream-null
5375                (stream-cons
5376                  (proc (stream-car strm))
5377                  (stream-map proc (stream-cdr strm))))))
5378
5379 -- Scheme Procedure: list->stream list
5380     Returns a newly-allocated stream containing the elements from LIST.
5381
5382 -- Scheme Procedure: port->stream [port]
5383     Returns a newly-allocated stream containing in its elements the
5384     characters on the port.  If PORT is not given it defaults to the
5385     current input port.  The returned stream has finite length and is
5386     terminated by ‘stream-null’.
5387
5388     It looks like one use of ‘port->stream’ would be this:
5389
5390          (define s ;wrong!
5391            (with-input-from-file filename
5392              (lambda () (port->stream))))
5393
5394     But that fails, because ‘with-input-from-file’ is eager, and closes
5395     the input port prematurely, before the first character is read.  To
5396     read a file into a stream, say:
5397
5398          (define-stream (file->stream filename)
5399            (let ((p (open-input-file filename)))
5400              (stream-let loop ((c (read-char p)))
5401                (if (eof-object? c)
5402                    (begin (close-input-port p)
5403                           stream-null)
5404                    (stream-cons c
5405                      (loop (read-char p)))))))
5406
5407 -- Scheme Syntax: stream object-expr ...
5408     Creates a newly-allocated stream containing in its elements the
5409     objects, in order.  The OBJECT-EXPRs are evaluated when they are
5410     accessed, not when the stream is created.  If no objects are given,
5411     as in (stream), the null stream is returned.  See also
5412     ‘list->stream’.
5413
5414          (define strm123 (stream 1 2 3))
5415
5416          ; (/ 1 0) not evaluated when stream is created
5417          (define s (stream 1 (/ 1 0) -1))
5418
5419 -- Scheme Procedure: stream->list [n] stream
5420     Returns a newly-allocated list containing in its elements the first
5421     N items in STREAM.  If STREAM has less than N items, all the items
5422     in the stream will be included in the returned list.  If N is not
5423     given it defaults to infinity, which means that unless STREAM is
5424     finite ‘stream->list’ will never return.
5425
5426          (stream->list 10
5427            (stream-map (lambda (x) (* x x))
5428              (stream-from 0)))
5429            ⇒ (0 1 4 9 16 25 36 49 64 81)
5430
5431 -- Scheme Procedure: stream-append stream ...
5432     Returns a newly-allocated stream containing in its elements those
5433     elements contained in its input STREAMs, in order of input.  If any
5434     of the input streams is infinite, no elements of any of the
5435     succeeding input streams will appear in the output stream.  See
5436     also ‘stream-concat’.
5437
5438 -- Scheme Procedure: stream-concat stream
5439     Takes a STREAM consisting of one or more streams and returns a
5440     newly-allocated stream containing all the elements of the input
5441     streams.  If any of the streams in the input STREAM is infinite,
5442     any remaining streams in the input stream will never appear in the
5443     output stream.  See also ‘stream-append’.
5444
5445 -- Scheme Procedure: stream-constant object ...
5446     Returns a newly-allocated stream containing in its elements the
5447     OBJECTs, repeating in succession forever.
5448
5449          (stream-constant 1) ⇒ 1 1 1 ...
5450          (stream-constant #t #f) ⇒ #t #f #t #f #t #f ...
5451
5452 -- Scheme Procedure: stream-drop n stream
5453     Returns the suffix of the input STREAM that starts at the next
5454     element after the first N elements.  The output stream shares
5455     structure with the input STREAM; thus, promises forced in one
5456     instance of the stream are also forced in the other instance of the
5457     stream.  If the input STREAM has less than N elements,
5458     ‘stream-drop’ returns the null stream.  See also ‘stream-take’.
5459
5460 -- Scheme Procedure: stream-drop-while pred stream
5461     Returns the suffix of the input STREAM that starts at the first
5462     element X for which ‘(pred x)’ returns false.  The output stream
5463     shares structure with the input STREAM.  See also
5464     ‘stream-take-while’.
5465
5466 -- Scheme Procedure: stream-filter pred stream
5467     Returns a newly-allocated stream that contains only those elements
5468     X of the input STREAM which satisfy the predicate ‘pred’.
5469
5470          (stream-filter odd? (stream-from 0))
5471             ⇒ 1 3 5 7 9 ...
5472
5473 -- Scheme Procedure: stream-fold proc base stream
5474     Applies a binary procedure PROC to BASE and the first element of
5475     STREAM to compute a new BASE, then applies the procedure to the new
5476     BASE and the next element of STREAM to compute a succeeding BASE,
5477     and so on, accumulating a value that is finally returned as the
5478     value of ‘stream-fold’ when the end of the stream is reached.
5479     STREAM must be finite, or ‘stream-fold’ will enter an infinite
5480     loop.  See also ‘stream-scan’, which is similar to ‘stream-fold’,
5481     but useful for infinite streams.  For readers familiar with other
5482     functional languages, this is a left-fold; there is no
5483     corresponding right-fold, since right-fold relies on finite streams
5484     that are fully-evaluated, in which case they may as well be
5485     converted to a list.
5486
5487 -- Scheme Procedure: stream-for-each proc stream ...
5488     Applies PROC element-wise to corresponding elements of the input
5489     STREAMs for side-effects; it returns nothing.  ‘stream-for-each’
5490     stops as soon as any of its input streams is exhausted.
5491
5492 -- Scheme Procedure: stream-from first [step]
5493     Creates a newly-allocated stream that contains FIRST as its first
5494     element and increments each succeeding element by STEP.  If STEP is
5495     not given it defaults to 1.  FIRST and STEP may be of any numeric
5496     type.  ‘stream-from’ is frequently useful as a generator in
5497     ‘stream-of’ expressions.  See also ‘stream-range’ for a similar
5498     procedure that creates finite streams.
5499
5500 -- Scheme Procedure: stream-iterate proc base
5501     Creates a newly-allocated stream containing BASE in its first
5502     element and applies PROC to each element in turn to determine the
5503     succeeding element.  See also ‘stream-unfold’ and ‘stream-unfolds’.
5504
5505 -- Scheme Procedure: stream-length stream
5506     Returns the number of elements in the STREAM; it does not evaluate
5507     its elements.  ‘stream-length’ may only be used on finite streams;
5508     it enters an infinite loop with infinite streams.
5509
5510 -- Scheme Syntax: stream-let tag ((var expr) ...) body ...
5511     Creates a local scope that binds each variable to the value of its
5512     corresponding expression.  It additionally binds TAG to a procedure
5513     which takes the bound variables as arguments and BODY as its
5514     defining expressions, binding the TAG with ‘stream-lambda’.  TAG is
5515     in scope within body, and may be called recursively.  When the
5516     expanded expression defined by the ‘stream-let’ is evaluated,
5517     ‘stream-let’ evaluates the expressions in its BODY in an
5518     environment containing the newly-bound variables, returning the
5519     value of the last expression evaluated, which must yield a stream.
5520
5521     ‘stream-let’ provides syntactic sugar on ‘stream-lambda’, in the
5522     same manner as normal ‘let’ provides syntactic sugar on normal
5523     ‘lambda’.  However, unlike normal ‘let’, the TAG is required, not
5524     optional, because unnamed ‘stream-let’ is meaningless.
5525
5526     For example, ‘stream-member’ returns the first ‘stream-pair’ of the
5527     input STRM with a ‘stream-car’ X that satisfies ‘(eql? obj x)’, or
5528     the null stream if X is not present in STRM.
5529
5530          (define-stream (stream-member eql? obj strm)
5531            (stream-let loop ((strm strm))
5532              (cond ((stream-null? strm) strm)
5533                    ((eql? obj (stream-car strm)) strm)
5534                    (else (loop (stream-cdr strm))))))
5535
5536 -- Scheme Procedure: stream-map proc stream ...
5537     Applies PROC element-wise to corresponding elements of the input
5538     STREAMs, returning a newly-allocated stream containing elements
5539     that are the results of those procedure applications.  The output
5540     stream has as many elements as the minimum-length input stream, and
5541     may be infinite.
5542
5543 -- Scheme Syntax: stream-match stream clause ...
5544     Provides pattern-matching for streams.  The input STREAM is an
5545     expression that evaluates to a stream.  Clauses are of the form
5546     ‘(pattern [fender] expression)’, consisting of a PATTERN that
5547     matches a stream of a particular shape, an optional FENDER that
5548     must succeed if the pattern is to match, and an EXPRESSION that is
5549     evaluated if the pattern matches.  There are four types of
5550     patterns:
5551
5552        • () matches the null stream.
5553
5554        • (PAT0 PAT1 ...) matches a finite stream with length exactly
5555          equal to the number of pattern elements.
5556
5557        • (PAT0 PAT1 ... ‘.’  PAT-REST) matches an infinite stream, or a
5558          finite stream with length at least as great as the number of
5559          pattern elements before the literal dot.
5560
5561        • PAT matches an entire stream.  Should always appear last in
5562          the list of clauses; it’s not an error to appear elsewhere,
5563          but subsequent clauses could never match.
5564
5565     Each pattern element may be either:
5566
5567        • An identifier, which matches any stream element.
5568          Additionally, the value of the stream element is bound to the
5569          variable named by the identifier, which is in scope in the
5570          FENDER and EXPRESSION of the corresponding CLAUSE.  Each
5571          identifier in a single pattern must be unique.
5572
5573        • A literal underscore (‘_’), which matches any stream element
5574          but creates no bindings.
5575
5576     The PATTERNs are tested in order, left-to-right, until a matching
5577     pattern is found; if FENDER is present, it must evaluate to a true
5578     value for the match to be successful.  Pattern variables are bound
5579     in the corresponding FENDER and EXPRESSION.  Once the matching
5580     PATTERN is found, the corresponding EXPRESSION is evaluated and
5581     returned as the result of the match.  An error is signaled if no
5582     pattern matches the input STREAM.
5583
5584     ‘stream-match’ is often used to distinguish null streams from
5585     non-null streams, binding HEAD and TAIL:
5586
5587          (define (len strm)
5588            (stream-match strm
5589              (() 0)
5590              ((head . tail) (+ 1 (len tail)))))
5591
5592     Fenders can test the common case where two stream elements must be
5593     identical; the ‘else’ pattern is an identifier bound to the entire
5594     stream, not a keyword as in ‘cond’.
5595
5596          (stream-match strm
5597            ((x y . _) (equal? x y) 'ok)
5598            (else 'error))
5599
5600     A more complex example uses two nested matchers to match two
5601     different stream arguments; ‘(stream-merge lt? . strms)’ stably
5602     merges two or more streams ordered by the ‘lt?’ predicate:
5603
5604          (define-stream (stream-merge lt? . strms)
5605            (define-stream (merge xx yy)
5606              (stream-match xx (() yy) ((x . xs)
5607                (stream-match yy (() xx) ((y . ys)
5608                  (if (lt? y x)
5609                      (stream-cons y (merge xx ys))
5610                      (stream-cons x (merge xs yy))))))))
5611            (stream-let loop ((strms strms))
5612              (cond ((null? strms) stream-null)
5613                    ((null? (cdr strms)) (car strms))
5614                    (else (merge (car strms)
5615                                 (apply stream-merge lt?
5616                                   (cdr strms)))))))
5617
5618 -- Scheme Syntax: stream-of expr clause ...
5619     Provides the syntax of stream comprehensions, which generate
5620     streams by means of looping expressions.  The result is a stream of
5621     objects of the type returned by EXPR.  There are four types of
5622     clauses:
5623
5624        • (VAR ‘in’ STREAM-EXPR) loops over the elements of STREAM-EXPR,
5625          in order from the start of the stream, binding each element of
5626          the stream in turn to VAR.  ‘stream-from’ and ‘stream-range’
5627          are frequently useful as generators for STREAM-EXPR.
5628
5629        • (VAR ‘is’ EXPR) binds VAR to the value obtained by evaluating
5630          EXPR.
5631
5632        • (PRED EXPR) includes in the output stream only those elements
5633          X which satisfy the predicate PRED.
5634
5635     The scope of variables bound in the stream comprehension is the
5636     clauses to the right of the binding clause (but not the binding
5637     clause itself) plus the result expression.
5638
5639     When two or more generators are present, the loops are processed as
5640     if they are nested from left to right; that is, the rightmost
5641     generator varies fastest.  A consequence of this is that only the
5642     first generator may be infinite and all subsequent generators must
5643     be finite.  If no generators are present, the result of a stream
5644     comprehension is a stream containing the result expression; thus,
5645     ‘(stream-of 1)’ produces a finite stream containing only the
5646     element 1.
5647
5648          (stream-of (* x x)
5649            (x in (stream-range 0 10))
5650            (even? x))
5651            ⇒ 0 4 16 36 64
5652
5653          (stream-of (list a b)
5654            (a in (stream-range 1 4))
5655            (b in (stream-range 1 3)))
5656            ⇒ (1 1) (1 2) (2 1) (2 2) (3 1) (3 2)
5657
5658          (stream-of (list i j)
5659            (i in (stream-range 1 5))
5660            (j in (stream-range (+ i 1) 5)))
5661            ⇒ (1 2) (1 3) (1 4) (2 3) (2 4) (3 4)
5662
5663 -- Scheme Procedure: stream-range first past [step]
5664     Creates a newly-allocated stream that contains FIRST as its first
5665     element and increments each succeeding element by STEP.  The stream
5666     is finite and ends before PAST, which is not an element of the
5667     stream.  If STEP is not given it defaults to 1 if FIRST is less
5668     than past and -1 otherwise.  FIRST, PAST and STEP may be of any
5669     real numeric type.  ‘stream-range’ is frequently useful as a
5670     generator in ‘stream-of’ expressions.  See also ‘stream-from’ for a
5671     similar procedure that creates infinite streams.
5672
5673          (stream-range 0 10) ⇒ 0 1 2 3 4 5 6 7 8 9
5674          (stream-range 0 10 2) ⇒ 0 2 4 6 8
5675
5676     Successive elements of the stream are calculated by adding STEP to
5677     FIRST, so if any of FIRST, PAST or STEP are inexact, the length of
5678     the output stream may differ from ‘(ceiling (- (/ (- past first)
5679     step) 1)’.
5680
5681 -- Scheme Procedure: stream-ref stream n
5682     Returns the Nth element of stream, counting from zero.  An error is
5683     signaled if N is greater than or equal to the length of stream.
5684
5685          (define (fact n)
5686            (stream-ref
5687              (stream-scan * 1 (stream-from 1))
5688              n))
5689
5690 -- Scheme Procedure: stream-reverse stream
5691     Returns a newly-allocated stream containing the elements of the
5692     input STREAM but in reverse order.  ‘stream-reverse’ may only be
5693     used with finite streams; it enters an infinite loop with infinite
5694     streams.  ‘stream-reverse’ does not force evaluation of the
5695     elements of the stream.
5696
5697 -- Scheme Procedure: stream-scan proc base stream
5698     Accumulates the partial folds of an input STREAM into a
5699     newly-allocated output stream.  The output stream is the BASE
5700     followed by ‘(stream-fold proc base (stream-take i stream))’ for
5701     each of the first I elements of STREAM.
5702
5703          (stream-scan + 0 (stream-from 1))
5704            ⇒ (stream 0 1 3 6 10 15 ...)
5705
5706          (stream-scan * 1 (stream-from 1))
5707            ⇒ (stream 1 1 2 6 24 120 ...)
5708
5709 -- Scheme Procedure: stream-take n stream
5710     Returns a newly-allocated stream containing the first N elements of
5711     the input STREAM.  If the input STREAM has less than N elements, so
5712     does the output stream.  See also ‘stream-drop’.
5713
5714 -- Scheme Procedure: stream-take-while pred stream
5715     Takes a predicate and a ‘stream’ and returns a newly-allocated
5716     stream containing those elements ‘x’ that form the maximal prefix
5717     of the input stream which satisfy PRED.  See also
5718     ‘stream-drop-while’.
5719
5720 -- Scheme Procedure: stream-unfold map pred gen base
5721     The fundamental recursive stream constructor.  It constructs a
5722     stream by repeatedly applying GEN to successive values of BASE, in
5723     the manner of ‘stream-iterate’, then applying MAP to each of the
5724     values so generated, appending each of the mapped values to the
5725     output stream as long as ‘(pred? base)’ returns a true value.  See
5726     also ‘stream-iterate’ and ‘stream-unfolds’.
5727
5728     The expression below creates the finite stream ‘0 1 4 9 16 25 36 49
5729     64 81’.  Initially the BASE is 0, which is less than 10, so MAP
5730     squares the BASE and the mapped value becomes the first element of
5731     the output stream.  Then GEN increments the BASE by 1, so it
5732     becomes 1; this is less than 10, so MAP squares the new BASE and 1
5733     becomes the second element of the output stream.  And so on, until
5734     the base becomes 10, when PRED stops the recursion and stream-null
5735     ends the output stream.
5736
5737          (stream-unfold
5738            (lambda (x) (expt x 2)) ; map
5739            (lambda (x) (< x 10))   ; pred?
5740            (lambda (x) (+ x 1))    ; gen
5741            0)                      ; base
5742
5743 -- Scheme Procedure: stream-unfolds proc seed
5744     Returns N newly-allocated streams containing those elements
5745     produced by successive calls to the generator PROC, which takes the
5746     current SEED as its argument and returns N+1 values
5747
5748     (PROC SEED) ⇒ SEED RESULT_0 ... RESULT_N-1
5749
5750     where the returned SEED is the input SEED to the next call to the
5751     generator and RESULT_I indicates how to produce the next element of
5752     the Ith result stream:
5753
5754        • (VALUE): VALUE is the next car of the result stream.
5755
5756        • ‘#f’: no value produced by this iteration of the generator
5757          PROC for the result stream.
5758
5759        • (): the end of the result stream.
5760
5761     It may require multiple calls of PROC to produce the next element
5762     of any particular result stream.  See also ‘stream-iterate’ and
5763     ‘stream-unfold’.
5764
5765          (define (stream-partition pred? strm)
5766            (stream-unfolds
5767              (lambda (s)
5768                (if (stream-null? s)
5769                    (values s '() '())
5770                    (let ((a (stream-car s))
5771                          (d (stream-cdr s)))
5772                      (if (pred? a)
5773                          (values d (list a) #f)
5774                          (values d #f (list a))))))
5775              strm))
5776
5777          (call-with-values
5778            (lambda ()
5779              (stream-partition odd?
5780                (stream-range 1 6)))
5781            (lambda (odds evens)
5782              (list (stream->list odds)
5783                    (stream->list evens))))
5784            ⇒ ((1 3 5) (2 4))
5785
5786 -- Scheme Procedure: stream-zip stream ...
5787     Returns a newly-allocated stream in which each element is a list
5788     (not a stream) of the corresponding elements of the input STREAMs.
5789     The output stream is as long as the shortest input STREAM, if any
5790     of the input STREAMs is finite, or is infinite if all the input
5791     STREAMs are infinite.
5792
5793
5794File: guile.info,  Node: SRFI-42,  Next: SRFI-43,  Prev: SRFI-41,  Up: SRFI Support
5795
57967.5.29 SRFI-42 - Eager Comprehensions
5797-------------------------------------
5798
5799See the specification of SRFI-42
5800(http://srfi.schemers.org/srfi-42/srfi-42.html).
5801
5802
5803File: guile.info,  Node: SRFI-43,  Next: SRFI-45,  Prev: SRFI-42,  Up: SRFI Support
5804
58057.5.30 SRFI-43 - Vector Library
5806-------------------------------
5807
5808This subsection is based on the specification of SRFI-43
5809(http://srfi.schemers.org/srfi-43/srfi-43.html) by Taylor Campbell.
5810
5811SRFI-43 implements a comprehensive library of vector operations.  It can
5812be made available with:
5813
5814     (use-modules (srfi srfi-43))
5815
5816* Menu:
5817
5818* SRFI-43 Constructors::
5819* SRFI-43 Predicates::
5820* SRFI-43 Selectors::
5821* SRFI-43 Iteration::
5822* SRFI-43 Searching::
5823* SRFI-43 Mutators::
5824* SRFI-43 Conversion::
5825
5826
5827File: guile.info,  Node: SRFI-43 Constructors,  Next: SRFI-43 Predicates,  Up: SRFI-43
5828
58297.5.30.1 SRFI-43 Constructors
5830.............................
5831
5832 -- Scheme Procedure: make-vector size [fill]
5833     Create and return a vector of size SIZE, optionally filling it with
5834     FILL.  The default value of FILL is unspecified.
5835
5836          (make-vector 5 3) ⇒ #(3 3 3 3 3)
5837
5838 -- Scheme Procedure: vector x ...
5839     Create and return a vector whose elements are X ....
5840
5841          (vector 0 1 2 3 4) ⇒ #(0 1 2 3 4)
5842
5843 -- Scheme Procedure: vector-unfold f length initial-seed ...
5844     The fundamental vector constructor.  Create a vector whose length
5845     is LENGTH and iterates across each index k from 0 up to LENGTH - 1,
5846     applying F at each iteration to the current index and current
5847     seeds, in that order, to receive n + 1 values: the element to put
5848     in the kth slot of the new vector, and n new seeds for the next
5849     iteration.  It is an error for the number of seeds to vary between
5850     iterations.
5851
5852          (vector-unfold (lambda (i x) (values x (- x 1)))
5853                         10 0)
5854          ⇒ #(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)
5855
5856          (vector-unfold values 10)
5857          ⇒ #(0 1 2 3 4 5 6 7 8 9)
5858
5859 -- Scheme Procedure: vector-unfold-right f length initial-seed ...
5860     Like ‘vector-unfold’, but it uses F to generate elements from
5861     right-to-left, rather than left-to-right.
5862
5863          (vector-unfold-right (lambda (i x) (values x (+ x 1)))
5864                               10 0)
5865          ⇒ #(9 8 7 6 5 4 3 2 1 0)
5866
5867 -- Scheme Procedure: vector-copy vec [start [end [fill]]]
5868     Allocate a new vector whose length is END - START and fills it with
5869     elements from VEC, taking elements from VEC starting at index START
5870     and stopping at index END.  START defaults to 0 and END defaults to
5871     the value of ‘(vector-length vec)’.  If END extends beyond the
5872     length of VEC, the slots in the new vector that obviously cannot be
5873     filled by elements from VEC are filled with FILL, whose default
5874     value is unspecified.
5875
5876          (vector-copy '#(a b c d e f g h i))
5877          ⇒ #(a b c d e f g h i)
5878
5879          (vector-copy '#(a b c d e f g h i) 6)
5880          ⇒ #(g h i)
5881
5882          (vector-copy '#(a b c d e f g h i) 3 6)
5883          ⇒ #(d e f)
5884
5885          (vector-copy '#(a b c d e f g h i) 6 12 'x)
5886          ⇒ #(g h i x x x)
5887
5888 -- Scheme Procedure: vector-reverse-copy vec [start [end]]
5889     Like ‘vector-copy’, but it copies the elements in the reverse order
5890     from VEC.
5891
5892          (vector-reverse-copy '#(5 4 3 2 1 0) 1 5)
5893          ⇒ #(1 2 3 4)
5894
5895 -- Scheme Procedure: vector-append vec ...
5896     Return a newly allocated vector that contains all elements in order
5897     from the subsequent locations in VEC ....
5898
5899          (vector-append '#(a) '#(b c d))
5900          ⇒ #(a b c d)
5901
5902 -- Scheme Procedure: vector-concatenate list-of-vectors
5903     Append each vector in LIST-OF-VECTORS.  Equivalent to ‘(apply
5904     vector-append list-of-vectors)’.
5905
5906          (vector-concatenate '(#(a b) #(c d)))
5907          ⇒ #(a b c d)
5908
5909
5910File: guile.info,  Node: SRFI-43 Predicates,  Next: SRFI-43 Selectors,  Prev: SRFI-43 Constructors,  Up: SRFI-43
5911
59127.5.30.2 SRFI-43 Predicates
5913...........................
5914
5915 -- Scheme Procedure: vector? obj
5916     Return true if OBJ is a vector, else return false.
5917
5918 -- Scheme Procedure: vector-empty? vec
5919     Return true if VEC is empty, i.e.  its length is 0, else return
5920     false.
5921
5922 -- Scheme Procedure: vector= elt=? vec ...
5923     Return true if the vectors VEC ... have equal lengths and equal
5924     elements according to ELT=?.  ELT=? is always applied to two
5925     arguments.  Element comparison must be consistent with ‘eq?’ in the
5926     following sense: if ‘(eq? a b)’ returns true, then ‘(elt=? a b)’
5927     must also return true.  The order in which comparisons are
5928     performed is unspecified.
5929
5930
5931File: guile.info,  Node: SRFI-43 Selectors,  Next: SRFI-43 Iteration,  Prev: SRFI-43 Predicates,  Up: SRFI-43
5932
59337.5.30.3 SRFI-43 Selectors
5934..........................
5935
5936 -- Scheme Procedure: vector-ref vec i
5937     Return the element at index I in VEC.  Indexing is based on zero.
5938
5939 -- Scheme Procedure: vector-length vec
5940     Return the length of VEC.
5941
5942
5943File: guile.info,  Node: SRFI-43 Iteration,  Next: SRFI-43 Searching,  Prev: SRFI-43 Selectors,  Up: SRFI-43
5944
59457.5.30.4 SRFI-43 Iteration
5946..........................
5947
5948 -- Scheme Procedure: vector-fold kons knil vec1 vec2 ...
5949     The fundamental vector iterator.  KONS is iterated over each index
5950     in all of the vectors, stopping at the end of the shortest; KONS is
5951     applied as
5952          (kons i state (vector-ref vec1 i) (vector-ref vec2 i) ...)
5953     where STATE is the current state value, and I is the current index.
5954     The current state value begins with KNIL, and becomes whatever KONS
5955     returned at the respective iteration.  The iteration is strictly
5956     left-to-right.
5957
5958 -- Scheme Procedure: vector-fold-right kons knil vec1 vec2 ...
5959     Similar to ‘vector-fold’, but it iterates right-to-left instead of
5960     left-to-right.
5961
5962 -- Scheme Procedure: vector-map f vec1 vec2 ...
5963     Return a new vector of the shortest size of the vector arguments.
5964     Each element at index i of the new vector is mapped from the old
5965     vectors by
5966          (f i (vector-ref vec1 i) (vector-ref vec2 i) ...)
5967     The dynamic order of application of F is unspecified.
5968
5969 -- Scheme Procedure: vector-map! f vec1 vec2 ...
5970     Similar to ‘vector-map’, but rather than mapping the new elements
5971     into a new vector, the new mapped elements are destructively
5972     inserted into VEC1.  The dynamic order of application of F is
5973     unspecified.
5974
5975 -- Scheme Procedure: vector-for-each f vec1 vec2 ...
5976     Call ‘(f i (vector-ref vec1 i) (vector-ref vec2 i) ...)’ for each
5977     index i less than the length of the shortest vector passed.  The
5978     iteration is strictly left-to-right.
5979
5980 -- Scheme Procedure: vector-count pred? vec1 vec2 ...
5981     Count the number of parallel elements in the vectors that satisfy
5982     PRED?, which is applied, for each index i less than the length of
5983     the smallest vector, to i and each parallel element in the vectors
5984     at that index, in order.
5985
5986          (vector-count (lambda (i elt) (even? elt))
5987                        '#(3 1 4 1 5 9 2 5 6))
5988          ⇒ 3
5989          (vector-count (lambda (i x y) (< x y))
5990                        '#(1 3 6 9) '#(2 4 6 8 10 12))
5991          ⇒ 2
5992
5993
5994File: guile.info,  Node: SRFI-43 Searching,  Next: SRFI-43 Mutators,  Prev: SRFI-43 Iteration,  Up: SRFI-43
5995
59967.5.30.5 SRFI-43 Searching
5997..........................
5998
5999 -- Scheme Procedure: vector-index pred? vec1 vec2 ...
6000     Find and return the index of the first elements in VEC1 VEC2 ...
6001     that satisfy PRED?.  If no matching element is found by the end of
6002     the shortest vector, return ‘#f’.
6003
6004          (vector-index even? '#(3 1 4 1 5 9))
6005          ⇒ 2
6006          (vector-index < '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2))
6007          ⇒ 1
6008          (vector-index = '#(3 1 4 1 5 9 2 5 6) '#(2 7 1 8 2))
6009          ⇒ #f
6010
6011 -- Scheme Procedure: vector-index-right pred? vec1 vec2 ...
6012     Like ‘vector-index’, but it searches right-to-left, rather than
6013     left-to-right.  Note that the SRFI 43 specification requires that
6014     all the vectors must have the same length, but both the SRFI 43
6015     reference implementation and Guile’s implementation allow vectors
6016     with unequal lengths, and start searching from the last index of
6017     the shortest vector.
6018
6019 -- Scheme Procedure: vector-skip pred? vec1 vec2 ...
6020     Find and return the index of the first elements in VEC1 VEC2 ...
6021     that do not satisfy PRED?.  If no matching element is found by the
6022     end of the shortest vector, return ‘#f’.  Equivalent to
6023     ‘vector-index’ but with the predicate inverted.
6024
6025          (vector-skip number? '#(1 2 a b 3 4 c d)) ⇒ 2
6026
6027 -- Scheme Procedure: vector-skip-right pred? vec1 vec2 ...
6028     Like ‘vector-skip’, but it searches for a non-matching element
6029     right-to-left, rather than left-to-right.  Note that the SRFI 43
6030     specification requires that all the vectors must have the same
6031     length, but both the SRFI 43 reference implementation and Guile’s
6032     implementation allow vectors with unequal lengths, and start
6033     searching from the last index of the shortest vector.
6034
6035 -- Scheme Procedure: vector-binary-search vec value cmp [start [end]]
6036     Find and return an index of VEC between START and END whose value
6037     is VALUE using a binary search.  If no matching element is found,
6038     return ‘#f’.  The default START is 0 and the default END is the
6039     length of VEC.
6040
6041     CMP must be a procedure of two arguments such that ‘(cmp a b)’
6042     returns a negative integer if a < b, a positive integer if a > b,
6043     or zero if a = b.  The elements of VEC must be sorted in
6044     non-decreasing order according to CMP.
6045
6046     Note that SRFI 43 does not document the START and END arguments,
6047     but both its reference implementation and Guile’s implementation
6048     support them.
6049
6050          (define (char-cmp c1 c2)
6051            (cond ((char<? c1 c2) -1)
6052                  ((char>? c1 c2) 1)
6053                  (else 0)))
6054
6055          (vector-binary-search '#(#\a #\b #\c #\d #\e #\f #\g #\h)
6056                                #\g
6057                                char-cmp)
6058          ⇒ 6
6059
6060 -- Scheme Procedure: vector-any pred? vec1 vec2 ...
6061     Find the first parallel set of elements from VEC1 VEC2 ... for
6062     which PRED? returns a true value.  If such a parallel set of
6063     elements exists, ‘vector-any’ returns the value that PRED? returned
6064     for that set of elements.  The iteration is strictly left-to-right.
6065
6066 -- Scheme Procedure: vector-every pred? vec1 vec2 ...
6067     If, for every index i between 0 and the length of the shortest
6068     vector argument, the set of elements ‘(vector-ref vec1 i)’
6069     ‘(vector-ref vec2 i)’ ... satisfies PRED?, ‘vector-every’ returns
6070     the value that PRED? returned for the last set of elements, at the
6071     last index of the shortest vector.  Otherwise it returns ‘#f’.  The
6072     iteration is strictly left-to-right.
6073
6074
6075File: guile.info,  Node: SRFI-43 Mutators,  Next: SRFI-43 Conversion,  Prev: SRFI-43 Searching,  Up: SRFI-43
6076
60777.5.30.6 SRFI-43 Mutators
6078.........................
6079
6080 -- Scheme Procedure: vector-set! vec i value
6081     Assign the contents of the location at I in VEC to VALUE.
6082
6083 -- Scheme Procedure: vector-swap! vec i j
6084     Swap the values of the locations in VEC at I and J.
6085
6086 -- Scheme Procedure: vector-fill! vec fill [start [end]]
6087     Assign the value of every location in VEC between START and END to
6088     FILL.  START defaults to 0 and END defaults to the length of VEC.
6089
6090 -- Scheme Procedure: vector-reverse! vec [start [end]]
6091     Destructively reverse the contents of VEC between START and END.
6092     START defaults to 0 and END defaults to the length of VEC.
6093
6094 -- Scheme Procedure: vector-copy! target tstart source [sstart [send]]
6095     Copy a block of elements from SOURCE to TARGET, both of which must
6096     be vectors, starting in TARGET at TSTART and starting in SOURCE at
6097     SSTART, ending when (SEND - SSTART) elements have been copied.  It
6098     is an error for TARGET to have a length less than (TSTART + SEND -
6099     SSTART).  SSTART defaults to 0 and SEND defaults to the length of
6100     SOURCE.
6101
6102 -- Scheme Procedure: vector-reverse-copy! target tstart source [sstart
6103          [send]]
6104     Like ‘vector-copy!’, but this copies the elements in the reverse
6105     order.  It is an error if TARGET and SOURCE are identical vectors
6106     and the TARGET and SOURCE ranges overlap; however, if TSTART =
6107     SSTART, ‘vector-reverse-copy!’ behaves as ‘(vector-reverse! target
6108     tstart send)’ would.
6109
6110
6111File: guile.info,  Node: SRFI-43 Conversion,  Prev: SRFI-43 Mutators,  Up: SRFI-43
6112
61137.5.30.7 SRFI-43 Conversion
6114...........................
6115
6116 -- Scheme Procedure: vector->list vec [start [end]]
6117     Return a newly allocated list containing the elements in VEC
6118     between START and END.  START defaults to 0 and END defaults to the
6119     length of VEC.
6120
6121 -- Scheme Procedure: reverse-vector->list vec [start [end]]
6122     Like ‘vector->list’, but the resulting list contains the specified
6123     range of elements of VEC in reverse order.
6124
6125 -- Scheme Procedure: list->vector proper-list [start [end]]
6126     Return a newly allocated vector of the elements from PROPER-LIST
6127     with indices between START and END.  START defaults to 0 and END
6128     defaults to the length of PROPER-LIST.  Note that SRFI 43 does not
6129     document the START and END arguments, but both its reference
6130     implementation and Guile’s implementation support them.
6131
6132 -- Scheme Procedure: reverse-list->vector proper-list [start [end]]
6133     Like ‘list->vector’, but the resulting vector contains the
6134     specified range of elements of PROPER-LIST in reverse order.  Note
6135     that SRFI 43 does not document the START and END arguments, but
6136     both its reference implementation and Guile’s implementation
6137     support them.
6138
6139
6140File: guile.info,  Node: SRFI-45,  Next: SRFI-46,  Prev: SRFI-43,  Up: SRFI Support
6141
61427.5.31 SRFI-45 - Primitives for Expressing Iterative Lazy Algorithms
6143--------------------------------------------------------------------
6144
6145This subsection is based on the specification of SRFI-45
6146(http://srfi.schemers.org/srfi-45/srfi-45.html) written by André van
6147Tonder.
6148
6149   Lazy evaluation is traditionally simulated in Scheme using ‘delay’
6150and ‘force’.  However, these primitives are not powerful enough to
6151express a large class of lazy algorithms that are iterative.  Indeed, it
6152is folklore in the Scheme community that typical iterative lazy
6153algorithms written using delay and force will often require unbounded
6154memory.
6155
6156   This SRFI provides set of three operations: {‘lazy’, ‘delay’,
6157‘force’}, which allow the programmer to succinctly express lazy
6158algorithms while retaining bounded space behavior in cases that are
6159properly tail-recursive.  A general recipe for using these primitives is
6160provided.  An additional procedure ‘eager’ is provided for the
6161construction of eager promises in cases where efficiency is a concern.
6162
6163   Although this SRFI redefines ‘delay’ and ‘force’, the extension is
6164conservative in the sense that the semantics of the subset {‘delay’,
6165‘force’} in isolation (i.e., as long as the program does not use ‘lazy’)
6166agrees with that in R5RS. In other words, no program that uses the R5RS
6167definitions of delay and force will break if those definition are
6168replaced by the SRFI-45 definitions of delay and force.
6169
6170   Guile also adds ‘promise?’ to the list of exports, which is not part
6171of the official SRFI-45.
6172
6173 -- Scheme Procedure: promise? obj
6174     Return true if OBJ is an SRFI-45 promise, otherwise return false.
6175
6176 -- Scheme Syntax: delay expression
6177     Takes an expression of arbitrary type A and returns a promise of
6178     type ‘(Promise A)’ which at some point in the future may be asked
6179     (by the ‘force’ procedure) to evaluate the expression and deliver
6180     the resulting value.
6181
6182 -- Scheme Syntax: lazy expression
6183     Takes an expression of type ‘(Promise A)’ and returns a promise of
6184     type ‘(Promise A)’ which at some point in the future may be asked
6185     (by the ‘force’ procedure) to evaluate the expression and deliver
6186     the resulting promise.
6187
6188 -- Scheme Procedure: force expression
6189     Takes an argument of type ‘(Promise A)’ and returns a value of type
6190     A as follows: If a value of type A has been computed for the
6191     promise, this value is returned.  Otherwise, the promise is first
6192     evaluated, then overwritten by the obtained promise or value, and
6193     then force is again applied (iteratively) to the promise.
6194
6195 -- Scheme Procedure: eager expression
6196     Takes an argument of type A and returns a value of type ‘(Promise
6197     A)’.  As opposed to ‘delay’, the argument is evaluated eagerly.
6198     Semantically, writing ‘(eager expression)’ is equivalent to writing
6199
6200          (let ((value expression)) (delay value)).
6201
6202     However, the former is more efficient since it does not require
6203     unnecessary creation and evaluation of thunks.  We also have the
6204     equivalence
6205
6206          (delay expression) = (lazy (eager expression))
6207
6208   The following reduction rules may be helpful for reasoning about
6209these primitives.  However, they do not express the memoization and
6210memory usage semantics specified above:
6211
6212     (force (delay expression)) -> expression
6213     (force (lazy  expression)) -> (force expression)
6214     (force (eager value))      -> value
6215
6216Correct usage
6217.............
6218
6219We now provide a general recipe for using the primitives {‘lazy’,
6220‘delay’, ‘force’} to express lazy algorithms in Scheme.  The
6221transformation is best described by way of an example: Consider the
6222stream-filter algorithm, expressed in a hypothetical lazy language as
6223
6224     (define (stream-filter p? s)
6225       (if (null? s) '()
6226           (let ((h (car s))
6227                 (t (cdr s)))
6228             (if (p? h)
6229                 (cons h (stream-filter p? t))
6230                 (stream-filter p? t)))))
6231
6232   This algorithm can be expressed as follows in Scheme:
6233
6234     (define (stream-filter p? s)
6235       (lazy
6236          (if (null? (force s)) (delay '())
6237              (let ((h (car (force s)))
6238                    (t (cdr (force s))))
6239                (if (p? h)
6240                    (delay (cons h (stream-filter p? t)))
6241                    (stream-filter p? t))))))
6242
6243   In other words, we
6244
6245   • wrap all constructors (e.g., ‘'()’, ‘cons’) with ‘delay’,
6246   • apply ‘force’ to arguments of deconstructors (e.g., ‘car’, ‘cdr’
6247     and ‘null?’),
6248   • wrap procedure bodies with ‘(lazy ...)’.
6249
6250
6251File: guile.info,  Node: SRFI-46,  Next: SRFI-55,  Prev: SRFI-45,  Up: SRFI Support
6252
62537.5.32 SRFI-46 Basic syntax-rules Extensions
6254--------------------------------------------
6255
6256Guile’s core ‘syntax-rules’ supports the extensions specified by
6257SRFI-46/R7RS. Tail patterns have been supported since at least Guile
62582.0, and custom ellipsis identifiers have been supported since Guile
62592.0.10.  *Note Syntax Rules::.
6260
6261
6262File: guile.info,  Node: SRFI-55,  Next: SRFI-60,  Prev: SRFI-46,  Up: SRFI Support
6263
62647.5.33 SRFI-55 - Requiring Features
6265-----------------------------------
6266
6267SRFI-55 provides ‘require-extension’ which is a portable mechanism to
6268load selected SRFI modules.  This is implemented in the Guile core,
6269there’s no module needed to get SRFI-55 itself.
6270
6271 -- library syntax: require-extension clause1 clause2 ...
6272     Require the features of CLAUSE1 CLAUSE2 ... , throwing an error if
6273     any are unavailable.
6274
6275     A CLAUSE is of the form ‘(IDENTIFIER arg...)’.  The only IDENTIFIER
6276     currently supported is ‘srfi’ and the arguments are SRFI numbers.
6277     For example to get SRFI-1 and SRFI-6,
6278
6279          (require-extension (srfi 1 6))
6280
6281     ‘require-extension’ can only be used at the top-level.
6282
6283     A Guile-specific program can simply ‘use-modules’ to load SRFIs not
6284     already in the core, ‘require-extension’ is for programs designed
6285     to be portable to other Scheme implementations.
6286
6287
6288File: guile.info,  Node: SRFI-60,  Next: SRFI-61,  Prev: SRFI-55,  Up: SRFI Support
6289
62907.5.34 SRFI-60 - Integers as Bits
6291---------------------------------
6292
6293This SRFI provides various functions for treating integers as bits and
6294for bitwise manipulations.  These functions can be obtained with,
6295
6296     (use-modules (srfi srfi-60))
6297
6298   Integers are treated as infinite precision twos-complement, the same
6299as in the core logical functions (*note Bitwise Operations::).  And
6300likewise bit indexes start from 0 for the least significant bit.  The
6301following functions in this SRFI are already in the Guile core,
6302
6303     ‘logand’, ‘logior’, ‘logxor’, ‘lognot’, ‘logtest’, ‘logcount’,
6304     ‘integer-length’, ‘logbit?’, ‘ash’
6305
6306
6307 -- Function: bitwise-and n1 ...
6308 -- Function: bitwise-ior n1 ...
6309 -- Function: bitwise-xor n1 ...
6310 -- Function: bitwise-not n
6311 -- Function: any-bits-set? j k
6312 -- Function: bit-set? index n
6313 -- Function: arithmetic-shift n count
6314 -- Function: bit-field n start end
6315 -- Function: bit-count n
6316     Aliases for ‘logand’, ‘logior’, ‘logxor’, ‘lognot’, ‘logtest’,
6317     ‘logbit?’, ‘ash’, ‘bit-extract’ and ‘logcount’ respectively.
6318
6319     Note that the name ‘bit-count’ conflicts with ‘bit-count’ in the
6320     core (*note Bit Vectors::).
6321
6322 -- Function: bitwise-if mask n1 n0
6323 -- Function: bitwise-merge mask n1 n0
6324     Return an integer with bits selected from N1 and N0 according to
6325     MASK.  Those bits where MASK has 1s are taken from N1, and those
6326     where MASK has 0s are taken from N0.
6327
6328          (bitwise-if 3 #b0101 #b1010) ⇒ 9
6329
6330 -- Function: log2-binary-factors n
6331 -- Function: first-set-bit n
6332     Return a count of how many factors of 2 are present in N.  This is
6333     also the bit index of the lowest 1 bit in N.  If N is 0, the return
6334     is -1.
6335
6336          (log2-binary-factors 6) ⇒ 1
6337          (log2-binary-factors -8) ⇒ 3
6338
6339 -- Function: copy-bit index n newbit
6340     Return N with the bit at INDEX set according to NEWBIT.  NEWBIT
6341     should be ‘#t’ to set the bit to 1, or ‘#f’ to set it to 0.  Bits
6342     other than at INDEX are unchanged in the return.
6343
6344          (copy-bit 1 #b0101 #t) ⇒ 7
6345
6346 -- Function: copy-bit-field n newbits start end
6347     Return N with the bits from START (inclusive) to END (exclusive)
6348     changed to the value NEWBITS.
6349
6350     The least significant bit in NEWBITS goes to START, the next to
6351     START+1, etc.  Anything in NEWBITS past the END given is ignored.
6352
6353          (copy-bit-field #b10000 #b11 1 3) ⇒ #b10110
6354
6355 -- Function: rotate-bit-field n count start end
6356     Return N with the bit field from START (inclusive) to END
6357     (exclusive) rotated upwards by COUNT bits.
6358
6359     COUNT can be positive or negative, and it can be more than the
6360     field width (it’ll be reduced modulo the width).
6361
6362          (rotate-bit-field #b0110 2 1 4) ⇒ #b1010
6363
6364 -- Function: reverse-bit-field n start end
6365     Return N with the bits from START (inclusive) to END (exclusive)
6366     reversed.
6367
6368          (reverse-bit-field #b101001 2 4) ⇒ #b100101
6369
6370 -- Function: integer->list n [len]
6371     Return bits from N in the form of a list of ‘#t’ for 1 and ‘#f’ for
6372     0.  The least significant LEN bits are returned, and the first list
6373     element is the most significant of those bits.  If LEN is not
6374     given, the default is ‘(integer-length N)’ (*note Bitwise
6375     Operations::).
6376
6377          (integer->list 6)   ⇒ (#t #t #f)
6378          (integer->list 1 4) ⇒ (#f #f #f #t)
6379
6380 -- Function: list->integer lst
6381 -- Function: booleans->integer bool...
6382     Return an integer formed bitwise from the given LST list of
6383     booleans, or for ‘booleans->integer’ from the BOOL arguments.
6384
6385     Each boolean is ‘#t’ for a 1 and ‘#f’ for a 0.  The first element
6386     becomes the most significant bit in the return.
6387
6388          (list->integer '(#t #f #t #f)) ⇒ 10
6389
6390
6391File: guile.info,  Node: SRFI-61,  Next: SRFI-62,  Prev: SRFI-60,  Up: SRFI Support
6392
63937.5.35 SRFI-61 - A more general ‘cond’ clause
6394---------------------------------------------
6395
6396This SRFI extends RnRS ‘cond’ to support test expressions that return
6397multiple values, as well as arbitrary definitions of test success.  SRFI
639861 is implemented in the Guile core; there’s no module needed to get
6399SRFI-61 itself.  Extended ‘cond’ is documented in *note Simple
6400Conditional Evaluation: Conditionals.
6401
6402
6403File: guile.info,  Node: SRFI-62,  Next: SRFI-64,  Prev: SRFI-61,  Up: SRFI Support
6404
64057.5.36 SRFI-62 - S-expression comments.
6406---------------------------------------
6407
6408Starting from version 2.0, Guile’s ‘read’ supports SRFI-62/R7RS
6409S-expression comments by default.
6410
6411
6412File: guile.info,  Node: SRFI-64,  Next: SRFI-67,  Prev: SRFI-62,  Up: SRFI Support
6413
64147.5.37 SRFI-64 - A Scheme API for test suites.
6415----------------------------------------------
6416
6417See the specification of SRFI-64
6418(http://srfi.schemers.org/srfi-64/srfi-64.html).
6419
6420
6421File: guile.info,  Node: SRFI-67,  Next: SRFI-69,  Prev: SRFI-64,  Up: SRFI Support
6422
64237.5.38 SRFI-67 - Compare procedures
6424-----------------------------------
6425
6426See the specification of SRFI-67
6427(http://srfi.schemers.org/srfi-67/srfi-67.html).
6428
6429
6430File: guile.info,  Node: SRFI-69,  Next: SRFI-71,  Prev: SRFI-67,  Up: SRFI Support
6431
64327.5.39 SRFI-69 - Basic hash tables
6433----------------------------------
6434
6435This is a portable wrapper around Guile’s built-in hash table and weak
6436table support.  *Note Hash Tables::, for information on that built-in
6437support.  Above that, this hash-table interface provides association of
6438equality and hash functions with tables at creation time, so variants of
6439each function are not required, as well as a procedure that takes care
6440of most uses for Guile hash table handles, which this SRFI does not
6441provide as such.
6442
6443   Access it with:
6444
6445     (use-modules (srfi srfi-69))
6446
6447* Menu:
6448
6449* SRFI-69 Creating hash tables::
6450* SRFI-69 Accessing table items::
6451* SRFI-69 Table properties::
6452* SRFI-69 Hash table algorithms::
6453
6454
6455File: guile.info,  Node: SRFI-69 Creating hash tables,  Next: SRFI-69 Accessing table items,  Up: SRFI-69
6456
64577.5.39.1 Creating hash tables
6458.............................
6459
6460 -- Scheme Procedure: make-hash-table [equal-proc hash-proc #:weak
6461          weakness start-size]
6462     Create and answer a new hash table with EQUAL-PROC as the equality
6463     function and HASH-PROC as the hashing function.
6464
6465     By default, EQUAL-PROC is ‘equal?’.  It can be any two-argument
6466     procedure, and should answer whether two keys are the same for this
6467     table’s purposes.
6468
6469     My default HASH-PROC assumes that ‘equal-proc’ is no coarser than
6470     ‘equal?’ unless it is literally ‘string-ci=?’.  If provided,
6471     HASH-PROC should be a two-argument procedure that takes a key and
6472     the current table size, and answers a reasonably good hash integer
6473     between 0 (inclusive) and the size (exclusive).
6474
6475     WEAKNESS should be ‘#f’ or a symbol indicating how “weak” the hash
6476     table is:
6477
6478     ‘#f’
6479          An ordinary non-weak hash table.  This is the default.
6480
6481     ‘key’
6482          When the key has no more non-weak references at GC, remove
6483          that entry.
6484
6485     ‘value’
6486          When the value has no more non-weak references at GC, remove
6487          that entry.
6488
6489     ‘key-or-value’
6490          When either has no more non-weak references at GC, remove the
6491          association.
6492
6493     As a legacy of the time when Guile couldn’t grow hash tables,
6494     START-SIZE is an optional integer argument that specifies the
6495     approximate starting size for the hash table, which will be rounded
6496     to an algorithmically-sounder number.
6497
6498   By “coarser” than ‘equal?’, we mean that for all X and Y values where
6499‘(EQUAL-PROC X Y)’, ‘(equal? X Y)’ as well.  If that does not hold for
6500your EQUAL-PROC, you must provide a HASH-PROC.
6501
6502   In the case of weak tables, remember that “references” above always
6503refers to ‘eq?’-wise references.  Just because you have a reference to
6504some string ‘"foo"’ doesn’t mean that an association with key ‘"foo"’ in
6505a weak-key table _won’t_ be collected; it only counts as a reference if
6506the two ‘"foo"’s are ‘eq?’, regardless of EQUAL-PROC.  As such, it is
6507usually only sensible to use ‘eq?’ and ‘hashq’ as the equivalence and
6508hash functions for a weak table.  *Note Weak References::, for more
6509information on Guile’s built-in weak table support.
6510
6511 -- Scheme Procedure: alist->hash-table alist [equal-proc hash-proc
6512          #:weak weakness start-size]
6513     As with ‘make-hash-table’, but initialize it with the associations
6514     in ALIST.  Where keys are repeated in ALIST, the leftmost
6515     association takes precedence.
6516
6517
6518File: guile.info,  Node: SRFI-69 Accessing table items,  Next: SRFI-69 Table properties,  Prev: SRFI-69 Creating hash tables,  Up: SRFI-69
6519
65207.5.39.2 Accessing table items
6521..............................
6522
6523 -- Scheme Procedure: hash-table-ref table key [default-thunk]
6524 -- Scheme Procedure: hash-table-ref/default table key default
6525     Answer the value associated with KEY in TABLE.  If KEY is not
6526     present, answer the result of invoking the thunk DEFAULT-THUNK,
6527     which signals an error instead by default.
6528
6529hash-table-ref/default’ is a variant that requires a third
6530     argument, DEFAULT, and answers DEFAULT itself instead of invoking
6531     it.
6532
6533 -- Scheme Procedure: hash-table-set! table key new-value
6534     Set KEY to NEW-VALUE in TABLE.
6535
6536 -- Scheme Procedure: hash-table-delete! table key
6537     Remove the association of KEY in TABLE, if present.  If absent, do
6538     nothing.
6539
6540 -- Scheme Procedure: hash-table-exists? table key
6541     Answer whether KEY has an association in TABLE.
6542
6543 -- Scheme Procedure: hash-table-update! table key modifier
6544          [default-thunk]
6545 -- Scheme Procedure: hash-table-update!/default table key modifier
6546          default
6547     Replace KEY’s associated value in TABLE by invoking MODIFIER with
6548     one argument, the old value.
6549
6550     If KEY is not present, and DEFAULT-THUNK is provided, invoke it
6551     with no arguments to get the “old value” to be passed to MODIFIER
6552     as above.  If DEFAULT-THUNK is not provided in such a case, signal
6553     an error.
6554
6555     ‘hash-table-update!/default’ is a variant that requires the fourth
6556     argument, which is used directly as the “old value” rather than as
6557     a thunk to be invoked to retrieve the “old value”.
6558
6559
6560File: guile.info,  Node: SRFI-69 Table properties,  Next: SRFI-69 Hash table algorithms,  Prev: SRFI-69 Accessing table items,  Up: SRFI-69
6561
65627.5.39.3 Table properties
6563.........................
6564
6565 -- Scheme Procedure: hash-table-size table
6566     Answer the number of associations in TABLE.  This is guaranteed to
6567     run in constant time for non-weak tables.
6568
6569 -- Scheme Procedure: hash-table-keys table
6570     Answer an unordered list of the keys in TABLE.
6571
6572 -- Scheme Procedure: hash-table-values table
6573     Answer an unordered list of the values in TABLE.
6574
6575 -- Scheme Procedure: hash-table-walk table proc
6576     Invoke PROC once for each association in TABLE, passing the key and
6577     value as arguments.
6578
6579 -- Scheme Procedure: hash-table-fold table proc init
6580     Invoke ‘(PROC KEY VALUE PREVIOUS)’ for each KEY and VALUE in TABLE,
6581     where PREVIOUS is the result of the previous invocation, using INIT
6582     as the first PREVIOUS value.  Answer the final PROC result.
6583
6584 -- Scheme Procedure: hash-table->alist table
6585     Answer an alist where each association in TABLE is an association
6586     in the result.
6587
6588
6589File: guile.info,  Node: SRFI-69 Hash table algorithms,  Prev: SRFI-69 Table properties,  Up: SRFI-69
6590
65917.5.39.4 Hash table algorithms
6592..............................
6593
6594Each hash table carries an “equivalence function” and a “hash function”,
6595used to implement key lookups.  Beginning users should follow the rules
6596for consistency of the default HASH-PROC specified above.  Advanced
6597users can use these to implement their own equivalence and hash
6598functions for specialized lookup semantics.
6599
6600 -- Scheme Procedure: hash-table-equivalence-function hash-table
6601 -- Scheme Procedure: hash-table-hash-function hash-table
6602     Answer the equivalence and hash function of HASH-TABLE,
6603     respectively.
6604
6605 -- Scheme Procedure: hash obj [size]
6606 -- Scheme Procedure: string-hash obj [size]
6607 -- Scheme Procedure: string-ci-hash obj [size]
6608 -- Scheme Procedure: hash-by-identity obj [size]
6609     Answer a hash value appropriate for equality predicate ‘equal?’,
6610     ‘string=?’, ‘string-ci=?’, and ‘eq?’, respectively.
6611
6612   ‘hash’ is a backwards-compatible replacement for Guile’s built-in
6613‘hash’.
6614
6615
6616File: guile.info,  Node: SRFI-71,  Next: SRFI-87,  Prev: SRFI-69,  Up: SRFI Support
6617
66187.5.40 SRFI-71 - Extended let-syntax for multiple values
6619--------------------------------------------------------
6620
6621This SRFI shadows the forms for ‘let’, ‘let*’, and ‘letrec’ so that they
6622may accept multiple values.  For example:
6623
6624     (use-modules (srfi srfi-71))
6625
6626     (let* ((x y (values 1 2))
6627            (z (+ x y)))
6628       (* z 2))
6629     ⇒ 6
6630
6631   See the specification of SRFI-71
6632(http://srfi.schemers.org/srfi-71/srfi-71.html).
6633
6634
6635File: guile.info,  Node: SRFI-87,  Next: SRFI-88,  Prev: SRFI-71,  Up: SRFI Support
6636
66377.5.41 SRFI-87 => in case clauses
6638---------------------------------
6639
6640Starting from version 2.0.6, Guile’s core ‘case’ syntax supports ‘=>’ in
6641clauses, as specified by SRFI-87/R7RS. *Note Conditionals::.
6642
6643
6644File: guile.info,  Node: SRFI-88,  Next: SRFI-98,  Prev: SRFI-87,  Up: SRFI Support
6645
66467.5.42 SRFI-88 Keyword Objects
6647------------------------------
6648
6649SRFI-88 (http://srfi.schemers.org/srfi-88/srfi-88.html) provides
6650“keyword objects”, which are equivalent to Guile’s keywords (*note
6651Keywords::).  SRFI-88 keywords can be entered using the “postfix keyword
6652syntax”, which consists of an identifier followed by ‘:’ (*note
6653‘postfix’ keyword syntax: Scheme Read.).  SRFI-88 can be made available
6654with:
6655
6656     (use-modules (srfi srfi-88))
6657
6658   Doing so installs the right reader option for keyword syntax, using
6659‘(read-set! keywords 'postfix)’.  It also provides the procedures
6660described below.
6661
6662 -- Scheme Procedure: keyword? obj
6663     Return ‘#t’ if OBJ is a keyword.  This is the same procedure as the
6664     same-named built-in procedure (*note ‘keyword?’: Keyword
6665     Procedures.).
6666
6667          (keyword? foo:)         ⇒ #t
6668          (keyword? 'foo:)        ⇒ #t
6669          (keyword? "foo")        ⇒ #f
6670
6671 -- Scheme Procedure: keyword->string kw
6672     Return the name of KW as a string, i.e., without the trailing
6673     colon.  The returned string may not be modified, e.g., with
6674     ‘string-set!’.
6675
6676          (keyword->string foo:)  ⇒ "foo"
6677
6678 -- Scheme Procedure: string->keyword str
6679     Return the keyword object whose name is STR.
6680
6681          (keyword->string (string->keyword "a b c"))     ⇒ "a b c"
6682
6683
6684File: guile.info,  Node: SRFI-98,  Next: SRFI-105,  Prev: SRFI-88,  Up: SRFI Support
6685
66867.5.43 SRFI-98 Accessing environment variables.
6687-----------------------------------------------
6688
6689This is a portable wrapper around Guile’s built-in support for
6690interacting with the current environment, *Note Runtime Environment::.
6691
6692 -- Scheme Procedure: get-environment-variable name
6693     Returns a string containing the value of the environment variable
6694     given by the string ‘name’, or ‘#f’ if the named environment
6695     variable is not found.  This is equivalent to ‘(getenv name)’.
6696
6697 -- Scheme Procedure: get-environment-variables
6698     Returns the names and values of all the environment variables as an
6699     association list in which both the keys and the values are strings.
6700
6701
6702File: guile.info,  Node: SRFI-105,  Next: SRFI-111,  Prev: SRFI-98,  Up: SRFI Support
6703
67047.5.44 SRFI-105 Curly-infix expressions.
6705----------------------------------------
6706
6707Guile’s built-in reader includes support for SRFI-105 curly-infix
6708expressions.  See the specification of SRFI-105
6709(http://srfi.schemers.org/srfi-105/srfi-105.html).  Some examples:
6710
6711     {n <= 5}                ⇒  (<= n 5)
6712     {a + b + c}             ⇒  (+ a b c)
6713     {a * {b + c}}           ⇒  (* a (+ b c))
6714     {(- a) / b}             ⇒  (/ (- a) b)
6715     {-(a) / b}              ⇒  (/ (- a) b) as well
6716     {(f a b) + (g h)}       ⇒  (+ (f a b) (g h))
6717     {f(a b) + g(h)}         ⇒  (+ (f a b) (g h)) as well
6718     {f[a b] + g(h)}         ⇒  (+ ($bracket-apply$ f a b) (g h))
6719     '{a + f(b) + x}         ⇒  '(+ a (f b) x)
6720     {length(x) >= 6}        ⇒  (>= (length x) 6)
6721     {n-1 + n-2}             ⇒  (+ n-1 n-2)
6722     {n * factorial{n - 1}}  ⇒  (* n (factorial (- n 1)))
6723     {{a > 0} and {b >= 1}}  ⇒  (and (> a 0) (>= b 1))
6724     {f{n - 1}(x)}           ⇒  ((f (- n 1)) x)
6725     {a . z}                 ⇒  ($nfx$ a . z)
6726     {a + b - c}             ⇒  ($nfx$ a + b - c)
6727
6728   To enable curly-infix expressions within a file, place the reader
6729directive ‘#!curly-infix’ before the first use of curly-infix notation.
6730To globally enable curly-infix expressions in Guile’s reader, set the
6731‘curly-infix’ read option.
6732
6733   Guile also implements the following non-standard extension to
6734SRFI-105: if ‘curly-infix’ is enabled and there is no other meaning
6735assigned to square brackets (i.e.  the ‘square-brackets’ read option is
6736turned off), then lists within square brackets are read as normal lists
6737but with the special symbol ‘$bracket-list$’ added to the front.  To
6738enable this combination of read options within a file, use the reader
6739directive ‘#!curly-infix-and-bracket-lists’.  For example:
6740
6741     [a b]    ⇒  ($bracket-list$ a b)
6742     [a . b]  ⇒  ($bracket-list$ a . b)
6743
6744   For more information on reader options, *Note Scheme Read::.
6745
6746
6747File: guile.info,  Node: SRFI-111,  Next: SRFI-171,  Prev: SRFI-105,  Up: SRFI Support
6748
67497.5.45 SRFI-111 Boxes.
6750----------------------
6751
6752SRFI-111 (http://srfi.schemers.org/srfi-111/srfi-111.html) provides
6753boxes: objects with a single mutable cell.
6754
6755 -- Scheme Procedure: box value
6756     Return a newly allocated box whose contents is initialized to
6757     VALUE.
6758
6759 -- Scheme Procedure: box? obj
6760     Return true if OBJ is a box, otherwise return false.
6761
6762 -- Scheme Procedure: unbox box
6763     Return the current contents of BOX.
6764
6765 -- Scheme Procedure: set-box! box value
6766     Set the contents of BOX to VALUE.
6767
6768
6769File: guile.info,  Node: SRFI-171,  Prev: SRFI-111,  Up: SRFI Support
6770
67717.5.46 Transducers
6772------------------
6773
6774Some of the most common operations used in the Scheme language are those
6775transforming lists: map, filter, take and so on.  They work well, are
6776well understood, and are used daily by most Scheme programmers.  They
6777are however not general because they only work on lists, and they do not
6778compose very well since combining N of them builds ‘(- N 1)’
6779intermediate lists.
6780
6781   Transducers are oblivious to what kind of process they are used in,
6782and are composable without building intermediate collections.  This
6783means we can create a transducer that squares all even numbers:
6784
6785     (compose (tfilter odd?) (tmap (lambda (x) (* x x))))
6786
6787   and reuse it with lists, vectors, or in just about any context where
6788data flows in one direction.  We could use it as a processing step for
6789asynchronous channels, with an event framework as a pre-processing step,
6790or even in lazy contexts where you pass a lazy collection and a
6791transducer to a function and get a new lazy collection back.
6792
6793   The traditional Scheme approach of having collection-specific
6794procedures is not changed.  We instead specify a general form of
6795transformations that complement these procedures.  The benefits are
6796obvious: a clear, well-understood way of describing common
6797transformations in a way that is faster than just chaining the
6798collection-specific counterparts.  For guile in particular this means a
6799lot better GC performance.
6800
6801   Notice however that ‘(compose ...)’ composes transducers
6802left-to-right, due to how transducers are initiated.
6803
6804* Menu:
6805
6806* SRFI-171 General Discussion::       General information about transducers
6807* SRFI-171 Applying Transducers::     Documentation of collection-specific forms
6808* SRFI-171 Reducers::                 Reducers specified by the SRFI
6809* SRFI-171 Transducers::              Transducers specified by the SRFI
6810* SRFI-171 Helpers::                  Utilities for writing your own transducers
6811
6812
6813File: guile.info,  Node: SRFI-171 General Discussion,  Next: SRFI-171 Applying Transducers,  Up: SRFI-171
6814
68157.5.46.1 SRFI-171 General Discussion
6816....................................
6817
6818The concept of reducers
6819-----------------------
6820
6821The central part of transducers are 3-arity reducing procedures.
6822
6823   • no arguments: Produces the identity of the reducer.
6824
6825   • (result-so-far): completion.  Returns ‘result-so-far’ either with
6826     or without transforming it first.
6827
6828   • (result-so-far input) combines ‘result-so-far’ and ‘input’ to
6829     produce a new ‘result-so-far’.
6830
6831   In the case of a summing ‘+’ reducer, the reducer would produce, in
6832arity order: ‘0’, ‘result-so-far’, ‘(+ result-so-far input)’.  This
6833happens to be exactly what the regular ‘+’ does.
6834
6835The concept of transducers
6836--------------------------
6837
6838A transducer is a one-arity procedure that takes a reducer and produces
6839a reducing function that behaves as follows:
6840
6841   • no arguments: calls reducer with no arguments (producing its
6842     identity)
6843
6844   • (result-so-far): Maybe transform the result-so-far and call reducer
6845     with it.
6846
6847   • (result-so-far input) Maybe do something to input and maybe call
6848     the reducer with result-so-far and the maybe-transformed input.
6849
6850   A simple example is as following:
6851
6852     (list-transduce (tfilter odd?)+ '(1 2 3 4 5)).
6853
6854   This first returns a transducer filtering all odd elements, then it
6855runs ‘+’ without arguments to retrieve its identity.  It then starts the
6856transduction by passing ‘+’ to the transducer returned by ‘(tfilter
6857odd?)’ which returns a reducing function.  It works not unlike reduce
6858from SRFI 1, but also checks whether one of the intermediate transducers
6859returns a "reduced" value (implemented as a SRFI 9 record), which means
6860the reduction finished early.
6861
6862   Because transducers compose and the final reduction is only executed
6863in the last step, composed transducers will not build any intermediate
6864result or collections.  Although the normal way of thinking about
6865application of composed functions is right to left, due to how the
6866transduction is built it is applied left to right.  ‘(compose (tfilter
6867odd?) (tmap sqrt))’ will create a transducer that first filters out any
6868odd values and then computes the square root of the rest.
6869
6870State
6871-----
6872
6873Even though transducers appear to be somewhat of a generalisation of
6874‘map’ and friends, this is not really true.  Since transducers don’t
6875know in which context they are being used, some transducers must keep
6876state where their collection-specific counterparts do not.  The
6877transducers that keep state do so using hidden mutable state, and as
6878such all the caveats of mutation, parallelism, and multi-shot
6879continuations apply.  Each transducer keeping state is clearly described
6880as doing so in the documentation.
6881
6882Naming
6883------
6884
6885Reducers exported from the transducers module are named as in their
6886SRFI-1 counterpart, but prepended with an r.  Transducers also follow
6887that naming, but are prepended with a t.
6888
6889
6890File: guile.info,  Node: SRFI-171 Applying Transducers,  Next: SRFI-171 Reducers,  Prev: SRFI-171 General Discussion,  Up: SRFI-171
6891
68927.5.46.2 Applying Transducers
6893.............................
6894
6895 -- Scheme Procedure: list-transduce xform f lst
6896 -- Scheme Procedure: list-transduce xform f identity lst
6897     Initialize the transducer XFORM by passing the reducer F to it.  If
6898     no identity is provided, F runs without arguments to return the
6899     reducer identity.  It then reduces over LST using the identity as
6900     the seed.
6901
6902     If one of the transducers finishes early (such as ‘ttake’ or
6903     ‘tdrop’), it communicates this by returning a reduced value, which
6904     in the guile implementation is just a value wrapped in a SRFI 9
6905     record type named “reduced”.  If such a value is returned by the
6906     transducer, ‘list-transduce’ must stop execution and return an
6907     unreduced value immediately.
6908
6909 -- Scheme Procedure: vector-transduce xform f vec
6910 -- Scheme Procedure: vector-transduce xform f identity vec
6911 -- Scheme Procedure: string-transduce xform f str
6912 -- Scheme Procedure: string-transduce xform f identity str
6913 -- Scheme Procedure: bytevector-u8-transduce xform f bv
6914 -- Scheme Procedure: bytevector-u8-transduce xform f identity bv
6915 -- Scheme Procedure: generator-transduce xform f gen
6916 -- Scheme Procedure: generator-transduce xform f identity gen
6917
6918     Same as ‘list-transduce’, but for vectors, strings, u8-bytevectors
6919     and SRFI-158-styled generators respectively.
6920
6921 -- Scheme Procedure: port-transduce xform f reader
6922 -- Scheme Procedure: port-transduce xform f reader port
6923 -- Scheme Procedure: port-transduce xform f identity reader port
6924
6925     Same as ‘list-reduce’ but for ports.  Called without a port, it
6926     reduces over the results of applying READER until the EOF-object is
6927     returned, presumably to read from ‘current-input-port’.  With a
6928     port READER is applied to PORT instead of without any arguments.
6929     If IDENTITY is provided, that is used as the initial identity in
6930     the reduction.
6931
6932
6933File: guile.info,  Node: SRFI-171 Reducers,  Next: SRFI-171 Transducers,  Prev: SRFI-171 Applying Transducers,  Up: SRFI-171
6934
69357.5.46.3 Reducers
6936.................
6937
6938 -- Scheme Procedure: rcons
6939     a simple consing reducer.  When called without values, it returns
6940     its identity, ‘'()’.  With one value, which will be a list, it
6941     reverses the list (using ‘reverse!’).  When called with two values,
6942     it conses the second value to the first.
6943
6944          (list-transduce (tmap (lambda (x) (+ x 1)) rcons (list 0 1 2 3))
6945          ⇒ (1 2 3 4)
6946
6947 -- Scheme Procedure: reverse-rcons
6948     same as rcons, but leaves the values in their reversed order.
6949          (list-transduce (tmap (lambda (x) (+ x 1))) reverse-rcons (list 0 1 2 3))
6950          ⇒ (4 3 2 1)
6951
6952 -- Scheme Procedure: rany pred?
6953     The reducer version of any.  Returns ‘(reduced (pred? value))’ if
6954     any ‘(pred? value)’ returns non-#f.  The identity is #f.
6955
6956          (list-transduce (tmap (lambda (x) (+ x 1))) (rany odd?) (list 1 3 5))
6957          ⇒ #f
6958
6959          (list-transduce (tmap (lambda (x) (+ x 1))) (rany odd?) (list 1 3 4 5))
6960          ⇒ #t
6961
6962 -- Scheme Procedure: revery pred?
6963     The reducer version of every.  Stops the transduction and returns
6964     ‘(reduced #f)’ if any ‘(pred? value)’ returns #f.  If every ‘(pred?
6965     value)’ returns true, it returns the result of the last invocation
6966     of ‘(pred? value)’.  The identity is #t.
6967
6968          (list-transduce
6969            (tmap (lambda (x) (+ x 1)))
6970            (revery (lambda (v) (if (odd? v) v #f)))
6971            (list 2 4 6))
6972            ⇒ 7
6973
6974          (list-transduce (tmap (lambda (x) (+ x 1)) (revery odd?) (list 2 4 5 6))
6975          ⇒ #f
6976
6977 -- Scheme Procedure: rcount
6978     A simple counting reducer.  Counts the values that pass through the
6979     transduction.
6980          (list-transduce (tfilter odd?) rcount (list 1 2 3 4)) ⇒ 2.
6981
6982
6983File: guile.info,  Node: SRFI-171 Transducers,  Next: SRFI-171 Helpers,  Prev: SRFI-171 Reducers,  Up: SRFI-171
6984
69857.5.46.4 Transducers
6986....................
6987
6988 -- Scheme Procedure: tmap proc
6989     Returns a transducer that applies PROC to all values.  Stateless.
6990
6991 -- tfilter: pred?
6992     Returns a transducer that removes values for which PRED? returns
6993     #f.
6994
6995     Stateless.
6996
6997 -- Scheme Procedure: tremove pred?
6998     Returns a transducer that removes values for which PRED? returns
6999     non-#f.
7000
7001     Stateless
7002
7003 -- Scheme Procedure: tfilter-map proc
7004     The same as ‘(compose (tmap proc) (tfilter values))’.  Stateless.
7005
7006 -- Scheme Procedure: treplace mapping
7007     The argument MAPPING is an association list (using ‘equal?’ to
7008     compare keys), a hash-table, a one-argument procedure taking one
7009     argument and either producing that same argument or a replacement
7010     value.
7011
7012     Returns a transducer which checks for the presence of any value
7013     passed through it in mapping.  If a mapping is found, the value of
7014     that mapping is returned, otherwise it just returns the original
7015     value.
7016
7017     Does not keep internal state, but modifying the mapping while it’s
7018     in use by treplace is an error.
7019
7020 -- Scheme Procedure: tdrop n
7021     Returns a transducer that discards the first N values.
7022
7023     Stateful.
7024
7025 -- Scheme Procedure: ttake n
7026     Returns a transducer that discards all values and stops the
7027     transduction after the first N values have been let through.  Any
7028     subsequent values are ignored.
7029
7030     Stateful.
7031
7032 -- Scheme Procedure: tdrop-while pred?
7033     Returns a transducer that discards the the first values for which
7034     PRED? returns true.
7035
7036     Stateful.
7037
7038 -- Scheme Procedure: ttake-while pred?
7039 -- Scheme Procedure: ttake-while pred? retf
7040     Returns a transducer that stops the transduction after PRED? has
7041     returned #f.  Any subsequent values are ignored and the last
7042     successful value is returned.  RETF is a function that gets called
7043     whenever PRED? returns false.  The arguments passed are the result
7044     so far and the input for which pred?  returns ‘#f’.  The default
7045     function is ‘(lambda (result input) result)’.
7046
7047     Stateful.
7048
7049 -- Scheme Procedure: tconcatenate
7050     tconcatenate _is_ a transducer that concatenates the content of
7051     each value (that must be a list) into the reduction.
7052          (list-transduce tconcatenate rcons '((1 2) (3 4 5) (6 (7 8) 9)))
7053          ⇒ (1 2 3 4 5 6 (7 8) 9)
7054
7055 -- Scheme Procedure: tappend-map proc
7056     The same as ‘(compose (tmap proc) tconcatenate)’.
7057
7058 -- Scheme Procedure: tflatten
7059     tflatten _is_ a transducer that flattens an input consisting of
7060     lists.
7061
7062          (list-transduce tflatten rcons '((1 2) 3 (4 (5 6) 7 8) 9)
7063          ⇒ (1 2 3 4 5 6 7 8 9)
7064
7065 -- Scheme Procedure: tdelete-neighbor-duplicates
7066 -- Scheme Procedure: tdelete-neighbor-duplicates equality-predicate
7067     Returns a transducer that removes any directly following duplicate
7068     elements.  The default EQUALITY-PREDICATE is ‘equal?’.
7069
7070     Stateful.
7071
7072 -- Scheme Procedure: tdelete-duplicates
7073 -- Scheme Procedure: tdelete-duplicates equality-predicate
7074     Returns a transducer that removes any subsequent duplicate elements
7075     compared using EQUALITY-PREDICATE.  The default EQUALITY-PREDICATE
7076     is ‘equal?’.
7077
7078     Stateful.
7079
7080 -- Scheme Procedure: tsegment n
7081     Returns a transducer that groups N inputs in lists of N elements.
7082     When the transduction stops, it flushes any remaining collection,
7083     even if it contains fewer than N elements.
7084
7085     Stateful.
7086
7087 -- Scheme Procedure: tpartition pred?
7088     Returns a transducer that groups inputs in lists by whenever
7089     ‘(pred? input)’ changes value.
7090
7091     Stateful.
7092
7093 -- Scheme Procedure: tadd-between value
7094     Returns a transducer which interposes VALUE between each value and
7095     the next.  This does not compose gracefully with transducers like
7096     ‘ttake’, as you might end up ending the transduction on ‘value’.
7097
7098     Stateful.
7099
7100 -- Scheme Procedure: tenumerate
7101 -- Scheme Procedure: tenumerate start
7102     Returns a transducer that indexes values passed through it,
7103     starting at START, which defaults to 0.  The indexing is done
7104     through cons pairs like ‘(index . input)’.
7105
7106          (list-transduce (tenumerate 1) rcons (list 'first 'second 'third))
7107          ⇒ ((1 . first) (2 . second) (3 . third))
7108
7109     Stateful.
7110
7111 -- Scheme Procedure: tlog
7112 -- Scheme Procedure: tlog logger
7113     Returns a transducer that can be used to log or print values and
7114     results.  The result of the LOGGER procedure is discarded.  The
7115     default LOGGER is ‘(lambda (result input) (write input)
7116     (newline))’.
7117
7118     Stateless.
7119
7120Guile-specific transducers
7121--------------------------
7122
7123These transducers are available in the ‘(srfi srfi-171 gnu)’ library,
7124and are provided outside the standard described by the SRFI-171
7125document.
7126
7127 -- Scheme Procedure: tbatch reducer
7128 -- Scheme Procedure: tbatch transducer reducer
7129     A batching transducer that accumulates results using REDUCER or
7130     ‘((transducer) reducer)’ until it returns a reduced value.  This
7131     can be used to generalize something like ‘tsegment’:
7132
7133          ;; This behaves exactly like (tsegment 4).
7134          (list-transduce (tbatch (ttake 4) rcons) rcons (iota 10))
7135          ⇒ ((0 1 2 3) (4 5 6 7) (8 9))
7136
7137 -- Scheme Procedure: tfold reducer
7138 -- Scheme Procedure: tfold reducer seed
7139
7140     A folding transducer that yields the result of ‘(reducer seed
7141     value)’, saving it’s result between iterations.
7142
7143          (list-transduce (tfold +) rcons (iota 10))
7144          ⇒ (0 1 3 6 10 15 21 28 36 45)
7145
7146