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: Vtables,  Next: Structure Basics,  Up: Structures
21
226.6.18.1 Vtables
23................
24
25A vtable is a structure type, specifying its layout, and other
26information.  A vtable is actually itself a structure, but there’s no
27need to worry about that initially (*note Vtable Contents::.)
28
29 -- Scheme Procedure: make-vtable fields [print]
30     Create a new vtable.
31
32     FIELDS is a string describing the fields in the structures to be
33     created.  Each field is represented by two characters, a type
34     letter and a permissions letter, for example ‘"pw"’.  The types are
35     as follows.
36
37        • ‘p’ – a Scheme value.  “p” stands for “protected” meaning it’s
38          protected against garbage collection.
39
40        • ‘u’ – an arbitrary word of data (an ‘scm_t_bits’).  At the
41          Scheme level it’s read and written as an unsigned integer.
42          “u” stands for “unboxed”, as it’s stored as a raw value
43          without additional type annotations.
44
45     It used to be that the second letter for each field was a
46     permission code, such as ‘w’ for writable or ‘r’ for read-only.
47     However over time structs have become more of a raw low-level
48     facility; access control is better implemented as a layer on top.
49     After all, ‘struct-set!’ is a cross-cutting operator that can
50     bypass abstractions made by higher-level record facilities; it’s
51     not generally safe (in the sense of abstraction-preserving) to
52     expose ‘struct-set!’ to “untrusted” code, even if the fields happen
53     to be writable.  Additionally, permission checks added overhead to
54     every structure access in a way that couldn’t be optimized out,
55     hampering the ability of structs to act as a low-level building
56     block.  For all of these reasons, all fields in Guile structs are
57     now writable; attempting to make a read-only field will now issue a
58     deprecation warning, and the field will be writable regardless.
59
60          (make-vtable "pw")      ;; one scheme field
61          (make-vtable "pwuwuw")  ;; one scheme and two unboxed fields
62
63     The optional PRINT argument is a function called by ‘display’ and
64     ‘write’ (etc) to give a printed representation of a structure
65     created from this vtable.  It’s called ‘(PRINT struct port)’ and
66     should look at STRUCT and write to PORT.  The default print merely
67     gives a form like ‘#<struct ADDR:ADDR>’ with a pair of machine
68     addresses.
69
70     The following print function for example shows the two fields of
71     its structure.
72
73          (make-vtable "pwpw"
74                       (lambda (struct port)
75                         (format port "#<~a and ~a>"
76                                 (struct-ref struct 0)
77                                 (struct-ref struct 1))))
78
79
80File: guile.info,  Node: Structure Basics,  Next: Vtable Contents,  Prev: Vtables,  Up: Structures
81
826.6.18.2 Structure Basics
83.........................
84
85This section describes the basic procedures for working with structures.
86make-struct/no-tail’ creates a structure, and ‘struct-ref’ and
87‘struct-set!’ access its fields.
88
89 -- Scheme Procedure: make-struct/no-tail vtable init ...
90     Create a new structure, with layout per the given VTABLE (*note
91     Vtables::).
92
93     The optional INIT... arguments are initial values for the fields of
94     the structure.  This is the only way to put values in read-only
95     fields.  If there are fewer INIT arguments than fields then the
96     defaults are ‘#f’ for a Scheme field (type ‘p’) or 0 for an unboxed
97     field (type ‘u’).
98
99     The name is a bit strange, we admit.  The reason for it is that
100     Guile used to have a ‘make-struct’ that took an additional
101     argument; while we deprecate that old interface,
102make-struct/no-tail’ is the new name for this functionality.
103
104     For example,
105
106          (define v (make-vtable "pwpwpw"))
107          (define s (make-struct/no-tail v 123 "abc" 456))
108          (struct-ref s 0) ⇒ 123
109          (struct-ref s 1) ⇒ "abc"
110
111 -- C Function: SCM scm_make_struct (SCM vtable, SCM tail_size, SCM
112          init_list)
113 -- C Function: SCM scm_c_make_struct (SCM vtable, SCM tail_size, SCM
114          init, ...)
115 -- C Function: SCM scm_c_make_structv (SCM vtable, SCM tail_size,
116          size_t n_inits, scm_t_bits init[])
117     There are a few ways to make structures from C. ‘scm_make_struct’
118     takes a list, ‘scm_c_make_struct’ takes variable arguments
119     terminated with SCM_UNDEFINED, and ‘scm_c_make_structv’ takes a
120     packed array.
121
122     For all of these, TAIL_SIZE should be zero (as a SCM value).
123
124 -- Scheme Procedure: struct? obj
125 -- C Function: scm_struct_p (obj)
126     Return ‘#t’ if OBJ is a structure, or ‘#f’ if not.
127
128 -- Scheme Procedure: struct-ref struct n
129 -- C Function: scm_struct_ref (struct, n)
130     Return the contents of field number N in STRUCT.  The first field
131     is number 0.
132
133     An error is thrown if N is out of range.
134
135 -- Scheme Procedure: struct-set! struct n value
136 -- C Function: scm_struct_set_x (struct, n, value)
137     Set field number N in STRUCT to VALUE.  The first field is number
138     0.
139
140     An error is thrown if N is out of range, or if the field cannot be
141     written because it’s ‘r’ read-only.
142
143   Unboxed fields (those with type ‘u’) need to be accessed with special
144procedures.
145
146 -- Scheme Procedure: struct-ref/unboxed struct n
147 -- Scheme Procedure: struct-set!/unboxed struct n value
148 -- C Function: scm_struct_ref_unboxed (struct, n)
149 -- C Function: scm_struct_set_x_unboxed (struct, n, value)
150     Like ‘struct-ref’ and ‘struct-set!’, except that these may only be
151     used on unboxed fields.  ‘struct-ref/unboxed’ will always return a
152     positive integer.  Likewise, ‘struct-set!/unboxed’ takes an
153     unsigned integer as the VALUE argument, and will signal an error
154     otherwise.
155
156 -- Scheme Procedure: struct-vtable struct
157 -- C Function: scm_struct_vtable (struct)
158     Return the vtable that describes STRUCT.
159
160     The vtable is effectively the type of the structure.  See *note
161     Vtable Contents::, for more on vtables.
162
163
164File: guile.info,  Node: Vtable Contents,  Next: Meta-Vtables,  Prev: Structure Basics,  Up: Structures
165
1666.6.18.3 Vtable Contents
167........................
168
169A vtable is itself a structure.  It has a specific set of fields
170describing various aspects of its “instances”: the structures created
171from a vtable.  Some of the fields are internal to Guile, some of them
172are part of the public interface, and there may be additional fields
173added on by the user.
174
175   Every vtable has a field for the layout of their instances, a field
176for the procedure used to print its instances, and a field for the name
177of the vtable itself.  Access to the layout and printer is exposed
178directly via field indexes.  Access to the vtable name is exposed via
179accessor procedures.
180
181 -- Scheme Variable: vtable-index-layout
182 -- C Macro: scm_vtable_index_layout
183     The field number of the layout specification in a vtable.  The
184     layout specification is a symbol like ‘pwpw’ formed from the fields
185     string passed to ‘make-vtable’, or created by ‘make-struct-layout’
186     (*note Meta-Vtables::).
187
188          (define v (make-vtable "pwpw" 0))
189          (struct-ref v vtable-index-layout) ⇒ pwpw
190
191     This field is read-only, since the layout of structures using a
192     vtable cannot be changed.
193
194 -- Scheme Variable: vtable-index-printer
195 -- C Macro: scm_vtable_index_printer
196     The field number of the printer function.  This field contains ‘#f’
197     if the default print function should be used.
198
199          (define (my-print-func struct port)
200            ...)
201          (define v (make-vtable "pwpw" my-print-func))
202          (struct-ref v vtable-index-printer) ⇒ my-print-func
203
204     This field is writable, allowing the print function to be changed
205     dynamically.
206
207 -- Scheme Procedure: struct-vtable-name vtable
208 -- Scheme Procedure: set-struct-vtable-name! vtable name
209 -- C Function: scm_struct_vtable_name (vtable)
210 -- C Function: scm_set_struct_vtable_name_x (vtable, name)
211     Get or set the name of VTABLE.  NAME is a symbol and is used in the
212     default print function when printing structures created from
213     VTABLE.
214
215          (define v (make-vtable "pw"))
216          (set-struct-vtable-name! v 'my-name)
217
218          (define s (make-struct v 0))
219          (display s) ⊣ #<my-name b7ab3ae0:b7ab3730>
220
221
222File: guile.info,  Node: Meta-Vtables,  Next: Vtable Example,  Prev: Vtable Contents,  Up: Structures
223
2246.6.18.4 Meta-Vtables
225.....................
226
227As a structure, a vtable also has a vtable, which is also a structure.
228Structures, their vtables, the vtables of the vtables, and so on form a
229tree of structures.  Making a new structure adds a leaf to the tree, and
230if that structure is a vtable, it may be used to create other leaves.
231
232   If you traverse up the tree of vtables, via calling ‘struct-vtable’,
233eventually you reach a root which is the vtable of itself:
234
235     scheme@(guile-user)> (current-module)
236     $1 = #<directory (guile-user) 221b090>
237     scheme@(guile-user)> (struct-vtable $1)
238     $2 = #<record-type module>
239     scheme@(guile-user)> (struct-vtable $2)
240     $3 = #<<standard-vtable> 12c30a0>
241     scheme@(guile-user)> (struct-vtable $3)
242     $4 = #<<standard-vtable> 12c3fa0>
243     scheme@(guile-user)> (struct-vtable $4)
244     $5 = #<<standard-vtable> 12c3fa0>
245     scheme@(guile-user)> <standard-vtable>
246     $6 = #<<standard-vtable> 12c3fa0>
247
248   In this example, we can say that ‘$1’ is an instance of ‘$2’, ‘$2’ is
249an instance of ‘$3’, ‘$3’ is an instance of ‘$4’, and ‘$4’, strangely
250enough, is an instance of itself.  The value bound to ‘$4’ in this
251console session also bound to ‘<standard-vtable>’ in the default
252environment.
253
254 -- Scheme Variable: <standard-vtable>
255     A meta-vtable, useful for making new vtables.
256
257   All of these values are structures.  All but ‘$1’ are vtables.  As
258‘$2’ is an instance of ‘$3’, and ‘$3’ is a vtable, we can say that ‘$3’
259is a “meta-vtable”: a vtable that can create vtables.
260
261   With this definition, we can specify more precisely what a vtable is:
262a vtable is a structure made from a meta-vtable.  Making a structure
263from a meta-vtable runs some special checks to ensure that the first
264field of the structure is a valid layout.  Additionally, if these checks
265see that the layout of the child vtable contains all the required fields
266of a vtable, in the correct order, then the child vtable will also be a
267meta-table, inheriting a magical bit from the parent.
268
269 -- Scheme Procedure: struct-vtable? obj
270 -- C Function: scm_struct_vtable_p (obj)
271     Return ‘#t’ if OBJ is a vtable structure: an instance of a
272     meta-vtable.
273
274   ‘<standard-vtable>’ is a root of the vtable tree.  (Normally there is
275only one root in a given Guile process, but due to some legacy
276interfaces there may be more than one.)
277
278   The set of required fields of a vtable is the set of fields in the
279‘<standard-vtable>’, and is bound to ‘standard-vtable-fields’ in the
280default environment.  It is possible to create a meta-vtable that with
281additional fields in its layout, which can be used to create vtables
282with additional data:
283
284     scheme@(guile-user)> (struct-ref $3 vtable-index-layout)
285     $6 = pwuhuhpwphuhuhpwpwpw
286     scheme@(guile-user)> (struct-ref $4 vtable-index-layout)
287     $7 = pwuhuhpwphuhuh
288     scheme@(guile-user)> standard-vtable-fields
289     $8 = "pwuhuhpwphuhuh"
290     scheme@(guile-user)> (struct-ref $2 vtable-offset-user)
291     $9 = module
292
293   In this continuation of our earlier example, ‘$2’ is a vtable that
294has extra fields, because its vtable, ‘$3’, was made from a meta-vtable
295with an extended layout.  ‘vtable-offset-user’ is a convenient
296definition that indicates the number of fields in
297‘standard-vtable-fields’.
298
299 -- Scheme Variable: standard-vtable-fields
300     A string containing the ordered set of fields that a vtable must
301     have.
302
303 -- Scheme Variable: vtable-offset-user
304     The first index in a vtable that is available for a user.
305
306 -- Scheme Procedure: make-struct-layout fields
307 -- C Function: scm_make_struct_layout (fields)
308     Return a structure layout symbol, from a FIELDS string.  FIELDS is
309     as described under ‘make-vtable’ (*note Vtables::).  An invalid
310     FIELDS string is an error.
311
312   With these definitions, one can define ‘make-vtable’ in this way:
313
314     (define* (make-vtable fields #:optional printer)
315       (make-struct/no-tail <standard-vtable>
316         (make-struct-layout fields)
317         printer))
318
319
320File: guile.info,  Node: Vtable Example,  Prev: Meta-Vtables,  Up: Structures
321
3226.6.18.5 Vtable Example
323.......................
324
325Let us bring these points together with an example.  Consider a simple
326object system with single inheritance.  Objects will be normal
327structures, and classes will be vtables with three extra class fields:
328the name of the class, the parent class, and the list of fields.
329
330   So, first we need a meta-vtable that allocates instances with these
331extra class fields.
332
333     (define <class>
334       (make-vtable
335        (string-append standard-vtable-fields "pwpwpw")
336        (lambda (x port)
337          (format port "<<class> ~a>" (class-name x)))))
338
339     (define (class? x)
340       (and (struct? x)
341            (eq? (struct-vtable x) <class>)))
342
343   To make a structure with a specific meta-vtable, we will use
344make-struct/no-tail’, passing it the computed instance layout and
345printer, as with ‘make-vtable’, and additionally the extra three class
346fields.
347
348     (define (make-class name parent fields)
349       (let* ((fields (compute-fields parent fields))
350              (layout (compute-layout fields)))
351         (make-struct/no-tail <class>
352           layout
353           (lambda (x port)
354             (print-instance x port))
355           name
356           parent
357           fields)))
358
359   Instances will store their associated data in slots in the structure:
360as many slots as there are fields.  The ‘compute-layout’ procedure below
361can compute a layout, and ‘field-index’ returns the slot corresponding
362to a field.
363
364     (define-syntax-rule (define-accessor name n)
365       (define (name obj)
366         (struct-ref obj n)))
367
368     ;; Accessors for classes
369     (define-accessor class-name (+ vtable-offset-user 0))
370     (define-accessor class-parent (+ vtable-offset-user 1))
371     (define-accessor class-fields (+ vtable-offset-user 2))
372
373     (define (compute-fields parent fields)
374       (if parent
375           (append (class-fields parent) fields)
376           fields))
377
378     (define (compute-layout fields)
379       (make-struct-layout
380        (string-concatenate (make-list (length fields) "pw"))))
381
382     (define (field-index class field)
383       (list-index (class-fields class) field))
384
385     (define (print-instance x port)
386       (format port "<~a" (class-name (struct-vtable x)))
387       (for-each (lambda (field idx)
388                   (format port " ~a: ~a" field (struct-ref x idx)))
389                 (class-fields (struct-vtable x))
390                 (iota (length (class-fields (struct-vtable x)))))
391       (format port ">"))
392
393   So, at this point we can actually make a few classes:
394
395     (define-syntax-rule (define-class name parent field ...)
396       (define name (make-class 'name parent '(field ...))))
397
398     (define-class <surface> #f
399       width height)
400
401     (define-class <window> <surface>
402       x y)
403
404   And finally, make an instance:
405
406     (make-struct/no-tail <window> 400 300 10 20)
407     ⇒ <<window> width: 400 height: 300 x: 10 y: 20>
408
409   And that’s that.  Note that there are many possible optimizations and
410feature enhancements that can be made to this object system, and the
411included GOOPS system does make most of them.  For more simple use
412cases, the records facility is usually sufficient.  But sometimes you
413need to make new kinds of data abstractions, and for that purpose,
414structs are here.
415
416
417File: guile.info,  Node: Dictionary Types,  Next: Association Lists,  Prev: Structures,  Up: Data Types
418
4196.6.19 Dictionary Types
420-----------------------
421
422A “dictionary” object is a data structure used to index information in a
423user-defined way.  In standard Scheme, the main aggregate data types are
424lists and vectors.  Lists are not really indexed at all, and vectors are
425indexed only by number (e.g. ‘(vector-ref foo 5)’).  Often you will find
426it useful to index your data on some other type; for example, in a
427library catalog you might want to look up a book by the name of its
428author.  Dictionaries are used to help you organize information in such
429a way.
430
431   An “association list” (or “alist” for short) is a list of key-value
432pairs.  Each pair represents a single quantity or object; the ‘car’ of
433the pair is a key which is used to identify the object, and the ‘cdr’ is
434the object’s value.
435
436   A “hash table” also permits you to index objects with arbitrary keys,
437but in a way that makes looking up any one object extremely fast.  A
438well-designed hash system makes hash table lookups almost as fast as
439conventional array or vector references.
440
441   Alists are popular among Lisp programmers because they use only the
442language’s primitive operations (lists, “car”, “cdr” and the equality
443primitives).  No changes to the language core are necessary.  Therefore,
444with Scheme’s built-in list manipulation facilities, it is very
445convenient to handle data stored in an association list.  Also, alists
446are highly portable and can be easily implemented on even the most
447minimal Lisp systems.
448
449   However, alists are inefficient, especially for storing large
450quantities of data.  Because we want Guile to be useful for large
451software systems as well as small ones, Guile provides a rich set of
452tools for using either association lists or hash tables.
453
454
455File: guile.info,  Node: Association Lists,  Next: VHashes,  Prev: Dictionary Types,  Up: Data Types
456
4576.6.20 Association Lists
458------------------------
459
460An association list is a conventional data structure that is often used
461to implement simple key-value databases.  It consists of a list of
462entries in which each entry is a pair.  The “key” of each entry is the
463‘car’ of the pair and the “value” of each entry is the ‘cdr’.
464
465     ASSOCIATION LIST ::=  '( (KEY1 . VALUE1)
466                              (KEY2 . VALUE2)
467                              (KEY3 . VALUE3)
468                              ...
469                            )
470
471Association lists are also known, for short, as “alists”.
472
473   The structure of an association list is just one example of the
474infinite number of possible structures that can be built using pairs and
475lists.  As such, the keys and values in an association list can be
476manipulated using the general list structure procedures ‘cons’, ‘car’,
477‘cdr’, ‘set-car!’, ‘set-cdr!’ and so on.  However, because association
478lists are so useful, Guile also provides specific procedures for
479manipulating them.
480
481* Menu:
482
483* Alist Key Equality::
484* Adding or Setting Alist Entries::
485* Retrieving Alist Entries::
486* Removing Alist Entries::
487* Sloppy Alist Functions::
488* Alist Example::
489
490
491File: guile.info,  Node: Alist Key Equality,  Next: Adding or Setting Alist Entries,  Up: Association Lists
492
4936.6.20.1 Alist Key Equality
494...........................
495
496All of Guile’s dedicated association list procedures, apart from
497‘acons’, come in three flavours, depending on the level of equality that
498is required to decide whether an existing key in the association list is
499the same as the key that the procedure call uses to identify the
500required entry.
501
502   • Procedures with “assq” in their name use ‘eq?’ to determine key
503     equality.
504
505   • Procedures with “assv” in their name use ‘eqv?’ to determine key
506     equality.
507
508   • Procedures with “assoc” in their name use ‘equal?’ to determine key
509     equality.
510
511   ‘acons’ is an exception because it is used to build association lists
512which do not require their entries’ keys to be unique.
513
514
515File: guile.info,  Node: Adding or Setting Alist Entries,  Next: Retrieving Alist Entries,  Prev: Alist Key Equality,  Up: Association Lists
516
5176.6.20.2 Adding or Setting Alist Entries
518........................................
519
520‘acons’ adds a new entry to an association list and returns the combined
521association list.  The combined alist is formed by consing the new entry
522onto the head of the alist specified in the ‘acons’ procedure call.  So
523the specified alist is not modified, but its contents become shared with
524the tail of the combined alist that ‘acons’ returns.
525
526   In the most common usage of ‘acons’, a variable holding the original
527association list is updated with the combined alist:
528
529     (set! address-list (acons name address address-list))
530
531   In such cases, it doesn’t matter that the old and new values of
532‘address-list’ share some of their contents, since the old value is
533usually no longer independently accessible.
534
535   Note that ‘acons’ adds the specified new entry regardless of whether
536the alist may already contain entries with keys that are, in some sense,
537the same as that of the new entry.  Thus ‘acons’ is ideal for building
538alists where there is no concept of key uniqueness.
539
540     (set! task-list (acons 3 "pay gas bill" '()))
541     task-list
542543     ((3 . "pay gas bill"))
544
545     (set! task-list (acons 3 "tidy bedroom" task-list))
546     task-list
547548     ((3 . "tidy bedroom") (3 . "pay gas bill"))
549
550   ‘assq-set!’, ‘assv-set!’ and ‘assoc-set!’ are used to add or replace
551an entry in an association list where there _is_ a concept of key
552uniqueness.  If the specified association list already contains an entry
553whose key is the same as that specified in the procedure call, the
554existing entry is replaced by the new one.  Otherwise, the new entry is
555consed onto the head of the old association list to create the combined
556alist.  In all cases, these procedures return the combined alist.
557
558   ‘assq-set!’ and friends _may_ destructively modify the structure of
559the old association list in such a way that an existing variable is
560correctly updated without having to ‘set!’ it to the value returned:
561
562     address-list
563564     (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
565
566     (assoc-set! address-list "james" "1a London Road")
567568     (("mary" . "34 Elm Road") ("james" . "1a London Road"))
569
570     address-list
571572     (("mary" . "34 Elm Road") ("james" . "1a London Road"))
573
574   Or they may not:
575
576     (assoc-set! address-list "bob" "11 Newington Avenue")
577578     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
579      ("james" . "1a London Road"))
580
581     address-list
582583     (("mary" . "34 Elm Road") ("james" . "1a London Road"))
584
585   The only safe way to update an association list variable when adding
586or replacing an entry like this is to ‘set!’ the variable to the
587returned value:
588
589     (set! address-list
590           (assoc-set! address-list "bob" "11 Newington Avenue"))
591     address-list
592593     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
594      ("james" . "1a London Road"))
595
596   Because of this slight inconvenience, you may find it more convenient
597to use hash tables to store dictionary data.  If your application will
598not be modifying the contents of an alist very often, this may not make
599much difference to you.
600
601   If you need to keep the old value of an association list in a form
602independent from the list that results from modification by ‘acons’,
603‘assq-set!’, ‘assv-set!’ or ‘assoc-set!’, use ‘list-copy’ to copy the
604old association list before modifying it.
605
606 -- Scheme Procedure: acons key value alist
607 -- C Function: scm_acons (key, value, alist)
608     Add a new key-value pair to ALIST.  A new pair is created whose car
609     is KEY and whose cdr is VALUE, and the pair is consed onto ALIST,
610     and the new list is returned.  This function is _not_ destructive;
611     ALIST is not modified.
612
613 -- Scheme Procedure: assq-set! alist key val
614 -- Scheme Procedure: assv-set! alist key value
615 -- Scheme Procedure: assoc-set! alist key value
616 -- C Function: scm_assq_set_x (alist, key, val)
617 -- C Function: scm_assv_set_x (alist, key, val)
618 -- C Function: scm_assoc_set_x (alist, key, val)
619     Reassociate KEY in ALIST with VALUE: find any existing ALIST entry
620     for KEY and associate it with the new VALUE.  If ALIST does not
621     contain an entry for KEY, add a new one.  Return the (possibly new)
622     alist.
623
624     These functions do not attempt to verify the structure of ALIST,
625     and so may cause unusual results if passed an object that is not an
626     association list.
627
628
629File: guile.info,  Node: Retrieving Alist Entries,  Next: Removing Alist Entries,  Prev: Adding or Setting Alist Entries,  Up: Association Lists
630
6316.6.20.3 Retrieving Alist Entries
632.................................
633
634‘assq’, ‘assv’ and ‘assoc’ find the entry in an alist for a given key,
635and return the ‘(KEY . VALUE)’ pair.  ‘assq-ref’, ‘assv-ref’ and
636‘assoc-ref’ do a similar lookup, but return just the VALUE.
637
638 -- Scheme Procedure: assq key alist
639 -- Scheme Procedure: assv key alist
640 -- Scheme Procedure: assoc key alist
641 -- C Function: scm_assq (key, alist)
642 -- C Function: scm_assv (key, alist)
643 -- C Function: scm_assoc (key, alist)
644     Return the first entry in ALIST with the given KEY.  The return is
645     the pair ‘(KEY . VALUE)’ from ALIST.  If there’s no matching entry
646     the return is ‘#f’.
647
648     ‘assq’ compares keys with ‘eq?’, ‘assv’ uses ‘eqv?’ and ‘assoc’
649     uses ‘equal?’.  See also SRFI-1 which has an extended ‘assoc’
650     (*note SRFI-1 Association Lists::).
651
652 -- Scheme Procedure: assq-ref alist key
653 -- Scheme Procedure: assv-ref alist key
654 -- Scheme Procedure: assoc-ref alist key
655 -- C Function: scm_assq_ref (alist, key)
656 -- C Function: scm_assv_ref (alist, key)
657 -- C Function: scm_assoc_ref (alist, key)
658     Return the value from the first entry in ALIST with the given KEY,
659     or ‘#f’ if there’s no such entry.
660
661     ‘assq-ref’ compares keys with ‘eq?’, ‘assv-ref’ uses ‘eqv?’ and
662     ‘assoc-ref’ uses ‘equal?’.
663
664     Notice these functions have the KEY argument last, like other
665     ‘-ref’ functions, but this is opposite to what ‘assq’ etc above
666     use.
667
668     When the return is ‘#f’ it can be either KEY not found, or an entry
669     which happens to have value ‘#f’ in the ‘cdr’.  Use ‘assq’ etc
670     above if you need to differentiate these cases.
671
672
673File: guile.info,  Node: Removing Alist Entries,  Next: Sloppy Alist Functions,  Prev: Retrieving Alist Entries,  Up: Association Lists
674
6756.6.20.4 Removing Alist Entries
676...............................
677
678To remove the element from an association list whose key matches a
679specified key, use ‘assq-remove!’, ‘assv-remove!’ or ‘assoc-remove!’
680(depending, as usual, on the level of equality required between the key
681that you specify and the keys in the association list).
682
683   As with ‘assq-set!’ and friends, the specified alist may or may not
684be modified destructively, and the only safe way to update a variable
685containing the alist is to ‘set!’ it to the value that ‘assq-remove!’
686and friends return.
687
688     address-list
689690     (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
691      ("james" . "1a London Road"))
692
693     (set! address-list (assoc-remove! address-list "mary"))
694     address-list
695696     (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
697
698   Note that, when ‘assq/v/oc-remove!’ is used to modify an association
699list that has been constructed only using the corresponding
700assq/v/oc-set!’, there can be at most one matching entry in the alist,
701so the question of multiple entries being removed in one go does not
702arise.  If ‘assq/v/oc-remove!’ is applied to an association list that
703has been constructed using ‘acons’, or an ‘assq/v/oc-set!’ with a
704different level of equality, or any mixture of these, it removes only
705the first matching entry from the alist, even if the alist might contain
706further matching entries.  For example:
707
708     (define address-list '())
709     (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
710     (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
711     address-list
712713     (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
714
715     (set! address-list (assoc-remove! address-list "mary"))
716     address-list
717718     (("mary" . "11 Elm Street"))
719
720   In this example, the two instances of the string "mary" are not the
721same when compared using ‘eq?’, so the two ‘assq-set!’ calls add two
722distinct entries to ‘address-list’.  When compared using ‘equal?’, both
723"mary"s in ‘address-list’ are the same as the "mary" in the
724‘assoc-remove!’ call, but ‘assoc-remove!’ stops after removing the first
725matching entry that it finds, and so one of the "mary" entries is left
726in place.
727
728 -- Scheme Procedure: assq-remove! alist key
729 -- Scheme Procedure: assv-remove! alist key
730 -- Scheme Procedure: assoc-remove! alist key
731 -- C Function: scm_assq_remove_x (alist, key)
732 -- C Function: scm_assv_remove_x (alist, key)
733 -- C Function: scm_assoc_remove_x (alist, key)
734     Delete the first entry in ALIST associated with KEY, and return the
735     resulting alist.
736
737
738File: guile.info,  Node: Sloppy Alist Functions,  Next: Alist Example,  Prev: Removing Alist Entries,  Up: Association Lists
739
7406.6.20.5 Sloppy Alist Functions
741...............................
742
743‘sloppy-assq’, ‘sloppy-assv’ and ‘sloppy-assoc’ behave like the
744corresponding non-‘sloppy-’ procedures, except that they return ‘#f’
745when the specified association list is not well-formed, where the
746non-‘sloppy-’ versions would signal an error.
747
748   Specifically, there are two conditions for which the non-‘sloppy-’
749procedures signal an error, which the ‘sloppy-’ procedures handle
750instead by returning ‘#f’.  Firstly, if the specified alist as a whole
751is not a proper list:
752
753     (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
754755     ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
756     ERROR: Wrong type argument in position 2 (expecting
757        association list): ((1 . 2) ("key" . "door") . "open sesame")
758
759     (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
760761     #f
762
763Secondly, if one of the entries in the specified alist is not a pair:
764
765     (assoc 2 '((1 . 1) 2 (3 . 9)))
766767     ERROR: In procedure assoc in expression (assoc 2 (quote #)):
768     ERROR: Wrong type argument in position 2 (expecting
769        association list): ((1 . 1) 2 (3 . 9))
770
771     (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
772773     #f
774
775   Unless you are explicitly working with badly formed association
776lists, it is much safer to use the non-‘sloppy-’ procedures, because
777they help to highlight coding and data errors that the ‘sloppy-’
778versions would silently cover up.
779
780 -- Scheme Procedure: sloppy-assq key alist
781 -- C Function: scm_sloppy_assq (key, alist)
782     Behaves like ‘assq’ but does not do any error checking.
783     Recommended only for use in Guile internals.
784
785 -- Scheme Procedure: sloppy-assv key alist
786 -- C Function: scm_sloppy_assv (key, alist)
787     Behaves like ‘assv’ but does not do any error checking.
788     Recommended only for use in Guile internals.
789
790 -- Scheme Procedure: sloppy-assoc key alist
791 -- C Function: scm_sloppy_assoc (key, alist)
792     Behaves like ‘assoc’ but does not do any error checking.
793     Recommended only for use in Guile internals.
794
795
796File: guile.info,  Node: Alist Example,  Prev: Sloppy Alist Functions,  Up: Association Lists
797
7986.6.20.6 Alist Example
799......................
800
801Here is a longer example of how alists may be used in practice.
802
803     (define capitals '(("New York" . "Albany")
804                        ("Oregon"   . "Salem")
805                        ("Florida"  . "Miami")))
806
807     ;; What's the capital of Oregon?
808     (assoc "Oregon" capitals)       ⇒ ("Oregon" . "Salem")
809     (assoc-ref capitals "Oregon")   ⇒ "Salem"
810
811     ;; We left out South Dakota.
812     (set! capitals
813           (assoc-set! capitals "South Dakota" "Pierre"))
814     capitals
815     ⇒ (("South Dakota" . "Pierre")
816         ("New York" . "Albany")
817         ("Oregon" . "Salem")
818         ("Florida" . "Miami"))
819
820     ;; And we got Florida wrong.
821     (set! capitals
822           (assoc-set! capitals "Florida" "Tallahassee"))
823     capitals
824     ⇒ (("South Dakota" . "Pierre")
825         ("New York" . "Albany")
826         ("Oregon" . "Salem")
827         ("Florida" . "Tallahassee"))
828
829     ;; After Oregon secedes, we can remove it.
830     (set! capitals
831           (assoc-remove! capitals "Oregon"))
832     capitals
833     ⇒ (("South Dakota" . "Pierre")
834         ("New York" . "Albany")
835         ("Florida" . "Tallahassee"))
836
837
838File: guile.info,  Node: VHashes,  Next: Hash Tables,  Prev: Association Lists,  Up: Data Types
839
8406.6.21 VList-Based Hash Lists or “VHashes”
841------------------------------------------
842
843The ‘(ice-9 vlist)’ module provides an implementation of “VList-based
844hash lists” (*note VLists::).  VList-based hash lists, or “vhashes”, are
845an immutable dictionary type similar to association lists that maps
846“keys” to “values”.  However, unlike association lists, accessing a
847value given its key is typically a constant-time operation.
848
849   The VHash programming interface of ‘(ice-9 vlist)’ is mostly the same
850as that of association lists found in SRFI-1, with procedure names
851prefixed by ‘vhash-’ instead of ‘alist-’ (*note SRFI-1 Association
852Lists::).
853
854   In addition, vhashes can be manipulated using VList operations:
855
856     (vlist-head (vhash-consq 'a 1 vlist-null))
857     ⇒ (a . 1)
858
859     (define vh1 (vhash-consq 'b 2 (vhash-consq 'a 1 vlist-null)))
860     (define vh2 (vhash-consq 'c 3 (vlist-tail vh1)))
861
862     (vhash-assq 'a vh2)
863     ⇒ (a . 1)
864     (vhash-assq 'b vh2)
865     ⇒ #f
866     (vhash-assq 'c vh2)
867     ⇒ (c . 3)
868     (vlist->list vh2)
869     ⇒ ((c . 3) (a . 1))
870
871   However, keep in mind that procedures that construct new VLists
872(‘vlist-map’, ‘vlist-filter’, etc.)  return raw VLists, not vhashes:
873
874     (define vh (alist->vhash '((a . 1) (b . 2) (c . 3)) hashq))
875     (vhash-assq 'a vh)
876     ⇒ (a . 1)
877
878     (define vl
879       ;; This will create a raw vlist.
880       (vlist-filter (lambda (key+value) (odd? (cdr key+value))) vh))
881     (vhash-assq 'a vl)
882     ⇒ ERROR: Wrong type argument in position 2
883
884     (vlist->list vl)
885     ⇒ ((a . 1) (c . 3))
886
887 -- Scheme Procedure: vhash? obj
888     Return true if OBJ is a vhash.
889
890 -- Scheme Procedure: vhash-cons key value vhash [hash-proc]
891 -- Scheme Procedure: vhash-consq key value vhash
892 -- Scheme Procedure: vhash-consv key value vhash
893     Return a new hash list based on VHASH where KEY is associated with
894     VALUE, using HASH-PROC to compute the hash of KEY.  VHASH must be
895     either ‘vlist-null’ or a vhash returned by a previous call to
896     ‘vhash-cons’.  HASH-PROC defaults to ‘hash’ (*note ‘hash’
897     procedure: Hash Table Reference.).  With ‘vhash-consq’, the ‘hashq’
898     hash function is used; with ‘vhash-consv’ the ‘hashv’ hash function
899     is used.
900
901     All ‘vhash-cons’ calls made to construct a vhash should use the
902     same HASH-PROC.  Failing to do that, the result is undefined.
903
904 -- Scheme Procedure: vhash-assoc key vhash [equal? [hash-proc]]
905 -- Scheme Procedure: vhash-assq key vhash
906 -- Scheme Procedure: vhash-assv key vhash
907     Return the first key/value pair from VHASH whose key is equal to
908     KEY according to the EQUAL? equality predicate (which defaults to
909     ‘equal?’), and using HASH-PROC (which defaults to ‘hash’) to
910     compute the hash of KEY.  The second form uses ‘eq?’ as the
911     equality predicate and ‘hashq’ as the hash function; the last form
912     uses ‘eqv?’ and ‘hashv’.
913
914     Note that it is important to consistently use the same hash
915     function for HASH-PROC as was passed to ‘vhash-cons’.  Failing to
916     do that, the result is unpredictable.
917
918 -- Scheme Procedure: vhash-delete key vhash [equal? [hash-proc]]
919 -- Scheme Procedure: vhash-delq key vhash
920 -- Scheme Procedure: vhash-delv key vhash
921     Remove all associations from VHASH with KEY, comparing keys with
922     EQUAL? (which defaults to ‘equal?’), and computing the hash of KEY
923     using HASH-PROC (which defaults to ‘hash’).  The second form uses
924     ‘eq?’ as the equality predicate and ‘hashq’ as the hash function;
925     the last one uses ‘eqv?’ and ‘hashv’.
926
927     Again the choice of HASH-PROC must be consistent with previous
928     calls to ‘vhash-cons’.
929
930 -- Scheme Procedure: vhash-fold proc init vhash
931 -- Scheme Procedure: vhash-fold-right proc init vhash
932     Fold over the key/value elements of VHASH in the given direction,
933     with each call to PROC having the form ‘(PROC key value result)’,
934     where RESULT is the result of the previous call to PROC and INIT
935     the value of RESULT for the first call to PROC.
936
937 -- Scheme Procedure: vhash-fold* proc init key vhash [equal? [hash]]
938 -- Scheme Procedure: vhash-foldq* proc init key vhash
939 -- Scheme Procedure: vhash-foldv* proc init key vhash
940     Fold over all the values associated with KEY in VHASH, with each
941     call to PROC having the form ‘(proc value result)’, where RESULT is
942     the result of the previous call to PROC and INIT the value of
943     RESULT for the first call to PROC.
944
945     Keys in VHASH are hashed using HASH are compared using EQUAL?.  The
946     second form uses ‘eq?’ as the equality predicate and ‘hashq’ as the
947     hash function; the third one uses ‘eqv?’ and ‘hashv’.
948
949     Example:
950
951          (define vh
952            (alist->vhash '((a . 1) (a . 2) (z . 0) (a . 3))))
953
954          (vhash-fold* cons '() 'a vh)
955          ⇒ (3 2 1)
956
957          (vhash-fold* cons '() 'z vh)
958          ⇒ (0)
959
960 -- Scheme Procedure: alist->vhash alist [hash-proc]
961     Return the vhash corresponding to ALIST, an association list, using
962     HASH-PROC to compute key hashes.  When omitted, HASH-PROC defaults
963     to ‘hash’.
964
965
966File: guile.info,  Node: Hash Tables,  Next: Other Types,  Prev: VHashes,  Up: Data Types
967
9686.6.22 Hash Tables
969------------------
970
971Hash tables are dictionaries which offer similar functionality as
972association lists: They provide a mapping from keys to values.  The
973difference is that association lists need time linear in the size of
974elements when searching for entries, whereas hash tables can normally
975search in constant time.  The drawback is that hash tables require a
976little bit more memory, and that you can not use the normal list
977procedures (*note Lists::) for working with them.
978
979* Menu:
980
981* Hash Table Examples::         Demonstration of hash table usage.
982* Hash Table Reference::        Hash table procedure descriptions.
983
984
985File: guile.info,  Node: Hash Table Examples,  Next: Hash Table Reference,  Up: Hash Tables
986
9876.6.22.1 Hash Table Examples
988............................
989
990For demonstration purposes, this section gives a few usage examples of
991some hash table procedures, together with some explanation what they do.
992
993   First we start by creating a new hash table with 31 slots, and
994populate it with two key/value pairs.
995
996     (define h (make-hash-table 31))
997
998     ;; This is an opaque object
999     h
10001001     #<hash-table 0/31>
1002
1003     ;; Inserting into a hash table can be done with hashq-set!
1004     (hashq-set! h 'foo "bar")
10051006     "bar"
1007
1008     (hashq-set! h 'braz "zonk")
10091010     "zonk"
1011
1012     ;; Or with hash-create-handle!
1013     (hashq-create-handle! h 'frob #f)
10141015     (frob . #f)
1016
1017   You can get the value for a given key with the procedure ‘hashq-ref’,
1018but the problem with this procedure is that you cannot reliably
1019determine whether a key does exists in the table.  The reason is that
1020the procedure returns ‘#f’ if the key is not in the table, but it will
1021return the same value if the key is in the table and just happens to
1022have the value ‘#f’, as you can see in the following examples.
1023
1024     (hashq-ref h 'foo)
10251026     "bar"
1027
1028     (hashq-ref h 'frob)
10291030     #f
1031
1032     (hashq-ref h 'not-there)
10331034     #f
1035
1036   It is often better is to use the procedure ‘hashq-get-handle’, which
1037makes a distinction between the two cases.  Just like ‘assq’, this
1038procedure returns a key/value-pair on success, and ‘#f’ if the key is
1039not found.
1040
1041     (hashq-get-handle h 'foo)
10421043     (foo . "bar")
1044
1045     (hashq-get-handle h 'not-there)
10461047     #f
1048
1049   Interesting results can be computed by using ‘hash-fold’ to work
1050through each element.  This example will count the total number of
1051elements:
1052
1053     (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
10541055     3
1056
1057   The same thing can be done with the procedure ‘hash-count’, which can
1058also count the number of elements matching a particular predicate.  For
1059example, count the number of elements with string values:
1060
1061     (hash-count (lambda (key value) (string? value)) h)
10621063     2
1064
1065   Counting all the elements is a simple task using ‘const’:
1066
1067     (hash-count (const #t) h)
10681069     3
1070
1071
1072File: guile.info,  Node: Hash Table Reference,  Prev: Hash Table Examples,  Up: Hash Tables
1073
10746.6.22.2 Hash Table Reference
1075.............................
1076
1077Like the association list functions, the hash table functions come in
1078several varieties, according to the equality test used for the keys.
1079Plain ‘hash-’ functions use ‘equal?’, ‘hashq-’ functions use ‘eq?’,
1080‘hashv-’ functions use ‘eqv?’, and the ‘hashx-’ functions use an
1081application supplied test.
1082
1083   A single ‘make-hash-table’ creates a hash table suitable for use with
1084any set of functions, but it’s imperative that just one set is then used
1085consistently, or results will be unpredictable.
1086
1087   Hash tables are implemented as a vector indexed by a hash value
1088formed from the key, with an association list of key/value pairs for
1089each bucket in case distinct keys hash together.  Direct access to the
1090pairs in those lists is provided by the ‘-handle-’ functions.
1091
1092   When the number of entries in a hash table goes above a threshold,
1093the vector is made larger and the entries are rehashed, to prevent the
1094bucket lists from becoming too long and slowing down accesses.  When the
1095number of entries goes below a threshold, the vector is shrunk to save
1096space.
1097
1098   For the ‘hashx-’ “extended” routines, an application supplies a HASH
1099function producing an integer index like ‘hashq’ etc below, and an ASSOC
1100alist search function like ‘assq’ etc (*note Retrieving Alist
1101Entries::).  Here’s an example of such functions implementing
1102case-insensitive hashing of string keys,
1103
1104     (use-modules (srfi srfi-1)
1105                  (srfi srfi-13))
1106
1107     (define (my-hash str size)
1108       (remainder (string-hash-ci str) size))
1109     (define (my-assoc str alist)
1110       (find (lambda (pair) (string-ci=? str (car pair))) alist))
1111
1112     (define my-table (make-hash-table))
1113     (hashx-set! my-hash my-assoc my-table "foo" 123)
1114
1115     (hashx-ref my-hash my-assoc my-table "FOO")
1116     ⇒ 123
1117
1118   In a ‘hashx-’ HASH function the aim is to spread keys across the
1119vector, so bucket lists don’t become long.  But the actual values are
1120arbitrary as long as they’re in the range 0 to SIZE-1.  Helpful
1121functions for forming a hash value, in addition to ‘hashq’ etc below,
1122include ‘symbol-hash’ (*note Symbol Keys::), ‘string-hash’ and
1123‘string-hash-ci’ (*note String Comparison::), and ‘char-set-hash’ (*note
1124Character Set Predicates/Comparison::).
1125
1126
1127 -- Scheme Procedure: make-hash-table [size]
1128     Create a new hash table object, with an optional minimum vector
1129     SIZE.
1130
1131     When SIZE is given, the table vector will still grow and shrink
1132     automatically, as described above, but with SIZE as a minimum.  If
1133     an application knows roughly how many entries the table will hold
1134     then it can use SIZE to avoid rehashing when initial entries are
1135     added.
1136
1137 -- Scheme Procedure: alist->hash-table alist
1138 -- Scheme Procedure: alist->hashq-table alist
1139 -- Scheme Procedure: alist->hashv-table alist
1140 -- Scheme Procedure: alist->hashx-table hash assoc alist
1141     Convert ALIST into a hash table.  When keys are repeated in ALIST,
1142     the leftmost association takes precedence.
1143
1144          (use-modules (ice-9 hash-table))
1145          (alist->hash-table '((foo . 1) (bar . 2)))
1146
1147     When converting to an extended hash table, custom HASH and ASSOC
1148     procedures must be provided.
1149
1150          (alist->hashx-table hash assoc '((foo . 1) (bar . 2)))
1151
1152 -- Scheme Procedure: hash-table? obj
1153 -- C Function: scm_hash_table_p (obj)
1154     Return ‘#t’ if OBJ is a abstract hash table object.
1155
1156 -- Scheme Procedure: hash-clear! table
1157 -- C Function: scm_hash_clear_x (table)
1158     Remove all items from TABLE (without triggering a resize).
1159
1160 -- Scheme Procedure: hash-ref table key [dflt]
1161 -- Scheme Procedure: hashq-ref table key [dflt]
1162 -- Scheme Procedure: hashv-ref table key [dflt]
1163 -- Scheme Procedure: hashx-ref hash assoc table key [dflt]
1164 -- C Function: scm_hash_ref (table, key, dflt)
1165 -- C Function: scm_hashq_ref (table, key, dflt)
1166 -- C Function: scm_hashv_ref (table, key, dflt)
1167 -- C Function: scm_hashx_ref (hash, assoc, table, key, dflt)
1168     Lookup KEY in the given hash TABLE, and return the associated
1169     value.  If KEY is not found, return DFLT, or ‘#f’ if DFLT is not
1170     given.
1171
1172 -- Scheme Procedure: hash-set! table key val
1173 -- Scheme Procedure: hashq-set! table key val
1174 -- Scheme Procedure: hashv-set! table key val
1175 -- Scheme Procedure: hashx-set! hash assoc table key val
1176 -- C Function: scm_hash_set_x (table, key, val)
1177 -- C Function: scm_hashq_set_x (table, key, val)
1178 -- C Function: scm_hashv_set_x (table, key, val)
1179 -- C Function: scm_hashx_set_x (hash, assoc, table, key, val)
1180     Associate VAL with KEY in the given hash TABLE.  If KEY is already
1181     present then it’s associated value is changed.  If it’s not present
1182     then a new entry is created.
1183
1184 -- Scheme Procedure: hash-remove! table key
1185 -- Scheme Procedure: hashq-remove! table key
1186 -- Scheme Procedure: hashv-remove! table key
1187 -- Scheme Procedure: hashx-remove! hash assoc table key
1188 -- C Function: scm_hash_remove_x (table, key)
1189 -- C Function: scm_hashq_remove_x (table, key)
1190 -- C Function: scm_hashv_remove_x (table, key)
1191 -- C Function: scm_hashx_remove_x (hash, assoc, table, key)
1192     Remove any association for KEY in the given hash TABLE.  If KEY is
1193     not in TABLE then nothing is done.
1194
1195 -- Scheme Procedure: hash key size
1196 -- Scheme Procedure: hashq key size
1197 -- Scheme Procedure: hashv key size
1198 -- C Function: scm_hash (key, size)
1199 -- C Function: scm_hashq (key, size)
1200 -- C Function: scm_hashv (key, size)
1201     Return a hash value for KEY.  This is a number in the range 0 to
1202     SIZE-1, which is suitable for use in a hash table of the given
1203     SIZE.
1204
1205     Note that ‘hashq’ and ‘hashv’ may use internal addresses of
1206     objects, so if an object is garbage collected and re-created it can
1207     have a different hash value, even when the two are notionally
1208     ‘eq?’.  For instance with symbols,
1209
1210          (hashq 'something 123)   ⇒ 19
1211          (gc)
1212          (hashq 'something 123)   ⇒ 62
1213
1214     In normal use this is not a problem, since an object entered into a
1215     hash table won’t be garbage collected until removed.  It’s only if
1216     hashing calculations are somehow separated from normal references
1217     that its lifetime needs to be considered.
1218
1219 -- Scheme Procedure: hash-get-handle table key
1220 -- Scheme Procedure: hashq-get-handle table key
1221 -- Scheme Procedure: hashv-get-handle table key
1222 -- Scheme Procedure: hashx-get-handle hash assoc table key
1223 -- C Function: scm_hash_get_handle (table, key)
1224 -- C Function: scm_hashq_get_handle (table, key)
1225 -- C Function: scm_hashv_get_handle (table, key)
1226 -- C Function: scm_hashx_get_handle (hash, assoc, table, key)
1227     Return the ‘(KEY . VALUE)’ pair for KEY in the given hash TABLE, or
1228     ‘#f’ if KEY is not in TABLE.
1229
1230 -- Scheme Procedure: hash-create-handle! table key init
1231 -- Scheme Procedure: hashq-create-handle! table key init
1232 -- Scheme Procedure: hashv-create-handle! table key init
1233 -- Scheme Procedure: hashx-create-handle! hash assoc table key init
1234 -- C Function: scm_hash_create_handle_x (table, key, init)
1235 -- C Function: scm_hashq_create_handle_x (table, key, init)
1236 -- C Function: scm_hashv_create_handle_x (table, key, init)
1237 -- C Function: scm_hashx_create_handle_x (hash, assoc, table, key,
1238          init)
1239     Return the ‘(KEY . VALUE)’ pair for KEY in the given hash TABLE.
1240     If KEY is not in TABLE then create an entry for it with INIT as the
1241     value, and return that pair.
1242
1243 -- Scheme Procedure: hash-map->list proc table
1244 -- Scheme Procedure: hash-for-each proc table
1245 -- C Function: scm_hash_map_to_list (proc, table)
1246 -- C Function: scm_hash_for_each (proc, table)
1247     Apply PROC to the entries in the given hash TABLE.  Each call is
1248     ‘(PROC KEY VALUE)’.  ‘hash-map->list’ returns a list of the results
1249     from these calls, ‘hash-for-each’ discards the results and returns
1250     an unspecified value.
1251
1252     Calls are made over the table entries in an unspecified order, and
1253     for ‘hash-map->list’ the order of the values in the returned list
1254     is unspecified.  Results will be unpredictable if TABLE is modified
1255     while iterating.
1256
1257     For example the following returns a new alist comprising all the
1258     entries from ‘mytable’, in no particular order.
1259
1260          (hash-map->list cons mytable)
1261
1262 -- Scheme Procedure: hash-for-each-handle proc table
1263 -- C Function: scm_hash_for_each_handle (proc, table)
1264     Apply PROC to the entries in the given hash TABLE.  Each call is
1265     ‘(PROC HANDLE)’, where HANDLE is a ‘(KEY . VALUE)’ pair.  Return an
1266     unspecified value.
1267
1268     ‘hash-for-each-handle’ differs from ‘hash-for-each’ only in the
1269     argument list of PROC.
1270
1271 -- Scheme Procedure: hash-fold proc init table
1272 -- C Function: scm_hash_fold (proc, init, table)
1273     Accumulate a result by applying PROC to the elements of the given
1274     hash TABLE.  Each call is ‘(PROC KEY VALUE PRIOR-RESULT)’, where
1275     KEY and VALUE are from the TABLE and PRIOR-RESULT is the return
1276     from the previous PROC call.  For the first call, PRIOR-RESULT is
1277     the given INIT value.
1278
1279     Calls are made over the table entries in an unspecified order.
1280     Results will be unpredictable if TABLE is modified while
1281     ‘hash-fold’ is running.
1282
1283     For example, the following returns a count of how many keys in
1284     ‘mytable’ are strings.
1285
1286          (hash-fold (lambda (key value prior)
1287                       (if (string? key) (1+ prior) prior))
1288                     0 mytable)
1289
1290 -- Scheme Procedure: hash-count pred table
1291 -- C Function: scm_hash_count (pred, table)
1292     Return the number of elements in the given hash TABLE that cause
1293     ‘(PRED KEY VALUE)’ to return true.  To quickly determine the total
1294     number of elements, use ‘(const #t)’ for PRED.
1295
1296
1297File: guile.info,  Node: Other Types,  Prev: Hash Tables,  Up: Data Types
1298
12996.6.23 Other Types
1300------------------
1301
1302Procedures are documented in their own section.  *Note Procedures::.
1303
1304   Variable objects are documented as part of the description of Guile’s
1305module system: see *note Variables::.
1306
1307   *Note Scheduling::, for discussion of threads, mutexes, and so on.
1308
1309   Ports are described in the section on I/O: see *note Input and
1310Output::.
1311
1312   Regular expressions are described in their own section: see *note
1313Regular Expressions::.
1314
1315   There are quite a number of additional data types documented in this
1316manual; if you feel a link is missing here, please file a bug.
1317
1318
1319File: guile.info,  Node: Procedures,  Next: Macros,  Prev: Data Types,  Up: API Reference
1320
13216.7 Procedures
1322==============
1323
1324* Menu:
1325
1326* Lambda::                      Basic procedure creation using lambda.
1327* Primitive Procedures::        Procedures defined in C.
1328* Compiled Procedures::         Scheme procedures can be compiled.
1329* Optional Arguments::          Handling keyword, optional and rest arguments.
1330* Case-lambda::                 One function, multiple arities.
1331* Higher-Order Functions::      Function that take or return functions.
1332* Procedure Properties::        Procedure properties and meta-information.
1333* Procedures with Setters::     Procedures with setters.
1334* Inlinable Procedures::        Procedures that can be inlined.
1335
1336
1337File: guile.info,  Node: Lambda,  Next: Primitive Procedures,  Up: Procedures
1338
13396.7.1 Lambda: Basic Procedure Creation
1340--------------------------------------
1341
1342A ‘lambda’ expression evaluates to a procedure.  The environment which
1343is in effect when a ‘lambda’ expression is evaluated is enclosed in the
1344newly created procedure, this is referred to as a “closure” (*note About
1345Closure::).
1346
1347   When a procedure created by ‘lambda’ is called with some actual
1348arguments, the environment enclosed in the procedure is extended by
1349binding the variables named in the formal argument list to new locations
1350and storing the actual arguments into these locations.  Then the body of
1351the ‘lambda’ expression is evaluated sequentially.  The result of the
1352last expression in the procedure body is then the result of the
1353procedure invocation.
1354
1355   The following examples will show how procedures can be created using
1356‘lambda’, and what you can do with these procedures.
1357
1358     (lambda (x) (+ x x))       ⇒ a procedure
1359     ((lambda (x) (+ x x)) 4)   ⇒ 8
1360
1361   The fact that the environment in effect when creating a procedure is
1362enclosed in the procedure is shown with this example:
1363
1364     (define add4
1365       (let ((x 4))
1366         (lambda (y) (+ x y))))
1367     (add4 6)                   ⇒ 10
1368
1369 -- syntax: lambda formals body
1370     FORMALS should be a formal argument list as described in the
1371     following table.
1372
1373     ‘(VARIABLE1 ...)’
1374          The procedure takes a fixed number of arguments; when the
1375          procedure is called, the arguments will be stored into the
1376          newly created location for the formal variables.
1377     ‘VARIABLE’
1378          The procedure takes any number of arguments; when the
1379          procedure is called, the sequence of actual arguments will
1380          converted into a list and stored into the newly created
1381          location for the formal variable.
1382     ‘(VARIABLE1 ... VARIABLEN . VARIABLEN+1)’
1383          If a space-delimited period precedes the last variable, then
1384          the procedure takes N or more variables where N is the number
1385          of formal arguments before the period.  There must be at least
1386          one argument before the period.  The first N actual arguments
1387          will be stored into the newly allocated locations for the
1388          first N formal arguments and the sequence of the remaining
1389          actual arguments is converted into a list and the stored into
1390          the location for the last formal argument.  If there are
1391          exactly N actual arguments, the empty list is stored into the
1392          location of the last formal argument.
1393
1394     The list in VARIABLE or VARIABLEN+1 is always newly created and the
1395     procedure can modify it if desired.  This is the case even when the
1396     procedure is invoked via ‘apply’, the required part of the list
1397     argument there will be copied (*note Procedures for On the Fly
1398     Evaluation: Fly Evaluation.).
1399
1400     BODY is a sequence of Scheme expressions which are evaluated in
1401     order when the procedure is invoked.
1402
1403
1404File: guile.info,  Node: Primitive Procedures,  Next: Compiled Procedures,  Prev: Lambda,  Up: Procedures
1405
14066.7.2 Primitive Procedures
1407--------------------------
1408
1409Procedures written in C can be registered for use from Scheme, provided
1410they take only arguments of type ‘SCM’ and return ‘SCM’ values.
1411‘scm_c_define_gsubr’ is likely to be the most useful mechanism,
1412combining the process of registration (‘scm_c_make_gsubr’) and
1413definition (‘scm_define’).
1414
1415 -- Function: SCM scm_c_make_gsubr (const char *name, int req, int opt,
1416          int rst, fcn)
1417     Register a C procedure FCN as a “subr” — a primitive subroutine
1418     that can be called from Scheme.  It will be associated with the
1419     given NAME but no environment binding will be created.  The
1420     arguments REQ, OPT and RST specify the number of required, optional
1421     and “rest” arguments respectively.  The total number of these
1422     arguments should match the actual number of arguments to FCN, but
1423     may not exceed 10.  The number of rest arguments should be 0 or 1.
1424     ‘scm_c_make_gsubr’ returns a value of type ‘SCM’ which is a
1425     “handle” for the procedure.
1426
1427 -- Function: SCM scm_c_define_gsubr (const char *name, int req, int
1428          opt, int rst, fcn)
1429     Register a C procedure FCN, as for ‘scm_c_make_gsubr’ above, and
1430     additionally create a top-level Scheme binding for the procedure in
1431     the “current environment” using ‘scm_define’.  ‘scm_c_define_gsubr’
1432     returns a handle for the procedure in the same way as
1433     ‘scm_c_make_gsubr’, which is usually not further required.
1434
1435
1436File: guile.info,  Node: Compiled Procedures,  Next: Optional Arguments,  Prev: Primitive Procedures,  Up: Procedures
1437
14386.7.3 Compiled Procedures
1439-------------------------
1440
1441The evaluation strategy given in *note Lambda:: describes how procedures
1442are “interpreted”.  Interpretation operates directly on expanded Scheme
1443source code, recursively calling the evaluator to obtain the value of
1444nested expressions.
1445
1446   Most procedures are compiled, however.  This means that Guile has
1447done some pre-computation on the procedure, to determine what it will
1448need to do each time the procedure runs.  Compiled procedures run faster
1449than interpreted procedures.
1450
1451   Loading files is the normal way that compiled procedures come to
1452being.  If Guile sees that a file is uncompiled, or that its compiled
1453file is out of date, it will attempt to compile the file when it is
1454loaded, and save the result to disk.  Procedures can be compiled at
1455runtime as well.  *Note Read/Load/Eval/Compile::, for more information
1456on runtime compilation.
1457
1458   Compiled procedures, also known as “programs”, respond to all
1459procedures that operate on procedures: you can pass a program to
1460‘procedure?’, ‘procedure-name’, and so on (*note Procedure
1461Properties::).  In addition, there are a few more accessors for
1462low-level details on programs.
1463
1464   Most people won’t need to use the routines described in this section,
1465but it’s good to have them documented.  You’ll have to include the
1466appropriate module first, though:
1467
1468     (use-modules (system vm program))
1469
1470 -- Scheme Procedure: program? obj
1471 -- C Function: scm_program_p (obj)
1472     Returns ‘#t’ if OBJ is a compiled procedure, or ‘#f’ otherwise.
1473
1474 -- Scheme Procedure: program-code program
1475 -- C Function: scm_program_code (program)
1476     Returns the address of the program’s entry, as an integer.  This
1477     address is mostly useful to procedures in ‘(system vm debug)’.
1478
1479 -- Scheme Procedure: program-num-free-variable program
1480 -- C Function: scm_program_num_free_variables (program)
1481     Return the number of free variables captured by this program.
1482
1483 -- Scheme Procedure: program-free-variable-ref program n
1484 -- C Function: scm_program_free_variable-ref (program, n)
1485 -- Scheme Procedure: program-free-variable-set! program n val
1486 -- C Function: scm_program_free_variable_set_x (program, n, val)
1487     Accessors for a program’s free variables.  Some of the values
1488     captured are actually in variable “boxes”.  *Note Variables and the
1489     VM::, for more information.
1490
1491     Users must not modify the returned value unless they think they’re
1492     really clever.
1493
1494 -- Scheme Procedure: program-bindings program
1495 -- Scheme Procedure: make-binding name boxed? index start end
1496 -- Scheme Procedure: binding:name binding
1497 -- Scheme Procedure: binding:boxed? binding
1498 -- Scheme Procedure: binding:index binding
1499 -- Scheme Procedure: binding:start binding
1500 -- Scheme Procedure: binding:end binding
1501     Bindings annotations for programs, along with their accessors.
1502
1503     Bindings declare names and liveness extents for block-local
1504     variables.  The best way to see what these are is to play around
1505     with them at a REPL. *Note VM Concepts::, for more information.
1506
1507     Note that bindings information is stored in a program as part of
1508     its metadata thunk, so including it in the generated object code
1509     does not impose a runtime performance penalty.
1510
1511 -- Scheme Procedure: program-sources program
1512 -- Scheme Procedure: source:addr source
1513 -- Scheme Procedure: source:line source
1514 -- Scheme Procedure: source:column source
1515 -- Scheme Procedure: source:file source
1516     Source location annotations for programs, along with their
1517     accessors.
1518
1519     Source location information propagates through the compiler and
1520     ends up being serialized to the program’s metadata.  This
1521     information is keyed by the offset of the instruction pointer
1522     within the object code of the program.  Specifically, it is keyed
1523     on the ‘ip’ _just following_ an instruction, so that backtraces can
1524     find the source location of a call that is in progress.
1525
1526 -- Scheme Procedure: program-arities program
1527 -- C Function: scm_program_arities (program)
1528 -- Scheme Procedure: program-arity program ip
1529 -- Scheme Procedure: arity:start arity
1530 -- Scheme Procedure: arity:end arity
1531 -- Scheme Procedure: arity:nreq arity
1532 -- Scheme Procedure: arity:nopt arity
1533 -- Scheme Procedure: arity:rest? arity
1534 -- Scheme Procedure: arity:kw arity
1535 -- Scheme Procedure: arity:allow-other-keys? arity
1536     Accessors for a representation of the “arity” of a program.
1537
1538     The normal case is that a procedure has one arity.  For example,
1539     ‘(lambda (x) x)’, takes one required argument, and that’s it.  One
1540     could access that number of required arguments via ‘(arity:nreq
1541     (program-arities (lambda (x) x)))’.  Similarly, ‘arity:nopt’ gets
1542     the number of optional arguments, and ‘arity:rest?’ returns a true
1543     value if the procedure has a rest arg.
1544
1545     ‘arity:kw’ returns a list of ‘(KW . IDX)’ pairs, if the procedure
1546     has keyword arguments.  The IDX refers to the IDXth local variable;
1547     *Note Variables and the VM::, for more information.  Finally
1548     ‘arity:allow-other-keys?’ returns a true value if other keys are
1549     allowed.  *Note Optional Arguments::, for more information.
1550
1551     So what about ‘arity:start’ and ‘arity:end’, then?  They return the
1552     range of bytes in the program’s bytecode for which a given arity is
1553     valid.  You see, a procedure can actually have more than one arity.
1554     The question, “what is a procedure’s arity” only really makes sense
1555     at certain points in the program, delimited by these ‘arity:start’
1556     and ‘arity:end’ values.
1557
1558 -- Scheme Procedure: program-arguments-alist program [ip]
1559     Return an association list describing the arguments that PROGRAM
1560     accepts, or ‘#f’ if the information cannot be obtained.
1561
1562     The alist keys that are currently defined are ‘required’,
1563     ‘optional’, ‘keyword’, ‘allow-other-keys?’, and ‘rest’.  For
1564     example:
1565
1566          (program-arguments-alist
1567           (lambda* (a b #:optional c #:key (d 1) #:rest e)
1568             #t)) ⇒
1569          ((required . (a b))
1570           (optional . (c))
1571           (keyword . ((#:d . 4)))
1572           (allow-other-keys? . #f)
1573           (rest . d))
1574
1575 -- Scheme Procedure: program-lambda-list program [ip]
1576     Return a representation of the arguments of PROGRAM as a lambda
1577     list, or ‘#f’ if this information is not available.
1578
1579     For example:
1580
1581          (program-lambda-list
1582           (lambda* (a b #:optional c #:key (d 1) #:rest e)
1583             #t)) ⇒
1584
1585
1586File: guile.info,  Node: Optional Arguments,  Next: Case-lambda,  Prev: Compiled Procedures,  Up: Procedures
1587
15886.7.4 Optional Arguments
1589------------------------
1590
1591Scheme procedures, as defined in R5RS, can either handle a fixed number
1592of actual arguments, or a fixed number of actual arguments followed by
1593arbitrarily many additional arguments.  Writing procedures of variable
1594arity can be useful, but unfortunately, the syntactic means for handling
1595argument lists of varying length is a bit inconvenient.  It is possible
1596to give names to the fixed number of arguments, but the remaining
1597(optional) arguments can be only referenced as a list of values (*note
1598Lambda::).
1599
1600   For this reason, Guile provides an extension to ‘lambda’, ‘lambda*’,
1601which allows the user to define procedures with optional and keyword
1602arguments.  In addition, Guile’s virtual machine has low-level support
1603for optional and keyword argument dispatch.  Calls to procedures with
1604optional and keyword arguments can be made cheaply, without allocating a
1605rest list.
1606
1607* Menu:
1608
1609* lambda* and define*::         Creating advanced argument handling procedures.
1610* ice-9 optargs::               (ice-9 optargs) provides some utilities.
1611
1612
1613File: guile.info,  Node: lambda* and define*,  Next: ice-9 optargs,  Up: Optional Arguments
1614
16156.7.4.1 lambda* and define*.
1616............................
1617
1618‘lambda*’ is like ‘lambda’, except with some extensions to allow
1619optional and keyword arguments.
1620
1621 -- library syntax: lambda* ([var...]
1622          [#:optional vardef...]
1623          [#:key vardef... [#:allow-other-keys]]
1624          [#:rest var | . var])
1625          body1 body2 ...
1626
1627     Create a procedure which takes optional and/or keyword arguments
1628     specified with ‘#:optional’ and ‘#:key’.  For example,
1629
1630          (lambda* (a b #:optional c d . e) '())
1631
1632     is a procedure with fixed arguments A and B, optional arguments C
1633     and D, and rest argument E.  If the optional arguments are omitted
1634     in a call, the variables for them are bound to ‘#f’.
1635
1636     Likewise, ‘define*’ is syntactic sugar for defining procedures
1637     using ‘lambda*’.
1638
1639     ‘lambda*’ can also make procedures with keyword arguments.  For
1640     example, a procedure defined like this:
1641
1642          (define* (sir-yes-sir #:key action how-high)
1643            (list action how-high))
1644
1645     can be called as ‘(sir-yes-sir #:action 'jump)’, ‘(sir-yes-sir
1646     #:how-high 13)’, ‘(sir-yes-sir #:action 'lay-down #:how-high 0)’,
1647     or just ‘(sir-yes-sir)’.  Whichever arguments are given as keywords
1648     are bound to values (and those not given are ‘#f’).
1649
1650     Optional and keyword arguments can also have default values to take
1651     when not present in a call, by giving a two-element list of
1652     variable name and expression.  For example in
1653
1654          (define* (frob foo #:optional (bar 42) #:key (baz 73))
1655            (list foo bar baz))
1656
1657     FOO is a fixed argument, BAR is an optional argument with default
1658     value 42, and baz is a keyword argument with default value 73.
1659     Default value expressions are not evaluated unless they are needed,
1660     and until the procedure is called.
1661
1662     Normally it’s an error if a call has keywords other than those
1663     specified by ‘#:key’, but adding ‘#:allow-other-keys’ to the
1664     definition (after the keyword argument declarations) will ignore
1665     unknown keywords.
1666
1667     If a call has a keyword given twice, the last value is used.  For
1668     example,
1669
1670          (define* (flips #:key (heads 0) (tails 0))
1671            (display (list heads tails)))
1672
1673          (flips #:heads 37 #:tails 42 #:heads 99)
1674          ⊣ (99 42)
1675
1676     ‘#:rest’ is a synonym for the dotted syntax rest argument.  The
1677     argument lists ‘(a . b)’ and ‘(a #:rest b)’ are equivalent in all
1678     respects.  This is provided for more similarity to DSSSL,
1679     MIT-Scheme and Kawa among others, as well as for refugees from
1680     other Lisp dialects.
1681
1682     When ‘#:key’ is used together with a rest argument, the keyword
1683     parameters in a call all remain in the rest list.  This is the same
1684     as Common Lisp.  For example,
1685
1686          ((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
1687             (display r))
1688           #:x 123 #:y 456)
1689          ⊣ (#:x 123 #:y 456)
1690
1691     ‘#:optional’ and ‘#:key’ establish their bindings successively,
1692     from left to right.  This means default expressions can refer back
1693     to prior parameters, for example
1694
1695          (lambda* (start #:optional (end (+ 10 start)))
1696            (do ((i start (1+ i)))
1697                ((> i end))
1698              (display i)))
1699
1700     The exception to this left-to-right scoping rule is the rest
1701     argument.  If there is a rest argument, it is bound after the
1702     optional arguments, but before the keyword arguments.
1703
1704
1705File: guile.info,  Node: ice-9 optargs,  Prev: lambda* and define*,  Up: Optional Arguments
1706
17076.7.4.2 (ice-9 optargs)
1708.......................
1709
1710Before Guile 2.0, ‘lambda*’ and ‘define*’ were implemented using macros
1711that processed rest list arguments.  This was not optimal, as calling
1712procedures with optional arguments had to allocate rest lists at every
1713procedure invocation.  Guile 2.0 improved this situation by bringing
1714optional and keyword arguments into Guile’s core.
1715
1716   However there are occasions in which you have a list and want to
1717parse it for optional or keyword arguments.  Guile’s ‘(ice-9 optargs)’
1718provides some macros to help with that task.
1719
1720   The syntax ‘let-optional’ and ‘let-optional*’ are for destructuring
1721rest argument lists and giving names to the various list elements.
1722‘let-optional’ binds all variables simultaneously, while ‘let-optional*’
1723binds them sequentially, consistent with ‘let’ and ‘let*’ (*note Local
1724Bindings::).
1725
1726 -- library syntax: let-optional rest-arg (binding ...) body1 body2 ...
1727 -- library syntax: let-optional* rest-arg (binding ...) body1 body2 ...
1728     These two macros give you an optional argument interface that is
1729     very “Schemey” and introduces no fancy syntax.  They are compatible
1730     with the scsh macros of the same name, but are slightly extended.
1731     Each of BINDING may be of one of the forms VAR or ‘(VAR
1732     DEFAULT-VALUE)’.  REST-ARG should be the rest-argument of the
1733     procedures these are used from.  The items in REST-ARG are
1734     sequentially bound to the variable names are given.  When REST-ARG
1735     runs out, the remaining vars are bound either to the default values
1736     or ‘#f’ if no default value was specified.  REST-ARG remains bound
1737     to whatever may have been left of REST-ARG.
1738
1739     After binding the variables, the expressions BODY1 BODY2 ... are
1740     evaluated in order.
1741
1742   Similarly, ‘let-keywords’ and ‘let-keywords*’ extract values from
1743keyword style argument lists, binding local variables to those values or
1744to defaults.
1745
1746 -- library syntax: let-keywords args allow-other-keys? (binding ...)
1747          body1 body2 ...
1748 -- library syntax: let-keywords* args allow-other-keys? (binding ...)
1749          body1 body2 ...
1750     ARGS is evaluated and should give a list of the form ‘(#:keyword1
1751     value1 #:keyword2 value2 ...)’.  The BINDINGs are variables and
1752     default expressions, with the variables to be set (by name) from
1753     the keyword values.  The BODY1 BODY2 ... forms are then evaluated
1754     and the last is the result.  An example will make the syntax
1755     clearest,
1756
1757          (define args '(#:xyzzy "hello" #:foo "world"))
1758
1759          (let-keywords args #t
1760                ((foo  "default for foo")
1761                 (bar  (string-append "default" "for" "bar")))
1762            (display foo)
1763            (display ", ")
1764            (display bar))
1765          ⊣ world, defaultforbar
1766
1767     The binding for ‘foo’ comes from the ‘#:foo’ keyword in ‘args’.
1768     But the binding for ‘bar’ is the default in the ‘let-keywords’,
1769     since there’s no ‘#:bar’ in the args.
1770
1771     ALLOW-OTHER-KEYS? is evaluated and controls whether unknown
1772     keywords are allowed in the ARGS list.  When true other keys are
1773     ignored (such as ‘#:xyzzy’ in the example), when ‘#f’ an error is
1774     thrown for anything unknown.
1775
1776   ‘(ice-9 optargs)’ also provides some more ‘define*’ sugar, which is
1777not so useful with modern Guile coding, but still supported:
1778‘define*-public’ is the ‘lambda*’ version of ‘define-public’;
1779‘defmacro*’ and ‘defmacro*-public’ exist for defining macros with the
1780improved argument list handling possibilities.  The ‘-public’ versions
1781not only define the procedures/macros, but also export them from the
1782current module.
1783
1784 -- library syntax: define*-public formals body1 body2 ...
1785     Like a mix of ‘define*’ and ‘define-public’.
1786
1787 -- library syntax: defmacro* name formals body1 body2 ...
1788 -- library syntax: defmacro*-public name formals body1 body2 ...
1789     These are just like ‘defmacro’ and ‘defmacro-public’ except that
1790     they take ‘lambda*’-style extended parameter lists, where
1791     ‘#:optional’, ‘#:key’, ‘#:allow-other-keys’ and ‘#:rest’ are
1792     allowed with the usual semantics.  Here is an example of a macro
1793     with an optional argument:
1794
1795          (defmacro* transmogrify (a #:optional b)
1796            (a 1))
1797
1798
1799File: guile.info,  Node: Case-lambda,  Next: Higher-Order Functions,  Prev: Optional Arguments,  Up: Procedures
1800
18016.7.5 Case-lambda
1802-----------------
1803
1804R5RS’s rest arguments are indeed useful and very general, but they often
1805aren’t the most appropriate or efficient means to get the job done.  For
1806example, ‘lambda*’ is a much better solution to the optional argument
1807problem than ‘lambda’ with rest arguments.
1808
1809   Likewise, ‘case-lambda’ works well for when you want one procedure to
1810do double duty (or triple, or ...), without the penalty of consing a
1811rest list.
1812
1813   For example:
1814
1815     (define (make-accum n)
1816       (case-lambda
1817         (() n)
1818         ((m) (set! n (+ n m)) n)))
1819
1820     (define a (make-accum 20))
1821     (a) ⇒ 20
1822     (a 10) ⇒ 30
1823     (a) ⇒ 30
1824
1825   The value returned by a ‘case-lambda’ form is a procedure which
1826matches the number of actual arguments against the formals in the
1827various clauses, in order.  The first matching clause is selected, the
1828corresponding values from the actual parameter list are bound to the
1829variable names in the clauses and the body of the clause is evaluated.
1830If no clause matches, an error is signalled.
1831
1832   The syntax of the ‘case-lambda’ form is defined in the following EBNF
1833grammar.  “Formals” means a formal argument list just like with ‘lambda’
1834(*note Lambda::).
1835
1836     <case-lambda>
1837        --> (case-lambda <case-lambda-clause>*)
1838        --> (case-lambda <docstring> <case-lambda-clause>*)
1839     <case-lambda-clause>
1840        --> (<formals> <definition-or-command>*)
1841     <formals>
1842        --> (<identifier>*)
1843          | (<identifier>* . <identifier>)
1844          | <identifier>
1845
1846   Rest lists can be useful with ‘case-lambda’:
1847
1848     (define plus
1849       (case-lambda
1850         "Return the sum of all arguments."
1851         (() 0)
1852         ((a) a)
1853         ((a b) (+ a b))
1854         ((a b . rest) (apply plus (+ a b) rest))))
1855     (plus 1 2 3) ⇒ 6
1856
1857   Also, for completeness.  Guile defines ‘case-lambda*’ as well, which
1858is like ‘case-lambda’, except with ‘lambda*’ clauses.  A ‘case-lambda*’
1859clause matches if the arguments fill the required arguments, but are not
1860too many for the optional and/or rest arguments.
1861
1862   Keyword arguments are possible with ‘case-lambda*’ as well, but they
1863do not contribute to the “matching” behavior, and their interactions
1864with required, optional, and rest arguments can be surprising.
1865
1866   For the purposes of ‘case-lambda*’ (and of ‘case-lambda’, as a
1867special case), a clause “matches” if it has enough required arguments,
1868and not too many positional arguments.  The required arguments are any
1869arguments before the ‘#:optional’, ‘#:key’, and ‘#:rest’ arguments.
1870“Positional” arguments are the required arguments, together with the
1871optional arguments.
1872
1873   In the absence of ‘#:key’ or ‘#:rest’ arguments, it’s easy to see how
1874there could be too many positional arguments: you pass 5 arguments to a
1875function that only takes 4 arguments, including optional arguments.  If
1876there is a ‘#:rest’ argument, there can never be too many positional
1877arguments: any application with enough required arguments for a clause
1878will match that clause, even if there are also ‘#:key’ arguments.
1879
1880   Otherwise, for applications to a clause with ‘#:key’ arguments (and
1881without a ‘#:rest’ argument), a clause will match there only if there
1882are enough required arguments and if the next argument after binding
1883required and optional arguments, if any, is a keyword.  For efficiency
1884reasons, Guile is currently unable to include keyword arguments in the
1885matching algorithm.  Clauses match on positional arguments only, not by
1886comparing a given keyword to the available set of keyword arguments that
1887a function has.
1888
1889   Some examples follow.
1890
1891     (define f
1892       (case-lambda*
1893         ((a #:optional b) 'clause-1)
1894         ((a #:optional b #:key c) 'clause-2)
1895         ((a #:key d) 'clause-3)
1896         ((#:key e #:rest f) 'clause-4)))
1897
1898     (f) ⇒ clause-4
1899     (f 1) ⇒ clause-1
1900     (f) ⇒ clause-4
1901     (f #:e 10) clause-1
1902     (f 1 #:foo) clause-1
1903     (f 1 #:c 2) clause-2
1904     (f #:a #:b #:c #:d #:e) clause-4
1905
1906     ;; clause-2 will match anything that clause-3 would match.
1907     (f 1 #:d 2) ⇒ error: bad keyword args in clause 2
1908
1909   Don’t forget that the clauses are matched in order, and the first
1910matching clause will be taken.  This can result in a keyword being bound
1911to a required argument, as in the case of ‘f #:e 10’.
1912
1913
1914File: guile.info,  Node: Higher-Order Functions,  Next: Procedure Properties,  Prev: Case-lambda,  Up: Procedures
1915
19166.7.6 Higher-Order Functions
1917----------------------------
1918
1919As a functional programming language, Scheme allows the definition of
1920“higher-order functions”, i.e., functions that take functions as
1921arguments and/or return functions.  Utilities to derive procedures from
1922other procedures are provided and described below.
1923
1924 -- Scheme Procedure: const value
1925     Return a procedure that accepts any number of arguments and returns
1926     VALUE.
1927
1928          (procedure? (const 3))        ⇒ #t
1929          ((const 'hello))              ⇒ hello
1930          ((const 'hello) 'world)       ⇒ hello
1931
1932 -- Scheme Procedure: negate proc
1933     Return a procedure with the same arity as PROC that returns the
1934     ‘not’ of PROC’s result.
1935
1936          (procedure? (negate number?)) ⇒ #t
1937          ((negate odd?) 2)             ⇒ #t
1938          ((negate real?) 'dream)       ⇒ #t
1939          ((negate string-prefix?) "GNU" "GNU Guile")
1940                                        ⇒ #f
1941          (filter (negate number?) '(a 2 "b"))
1942                                        ⇒ (a "b")
1943
1944 -- Scheme Procedure: compose proc1 proc2 ...
1945     Compose PROC1 with the procedures PROC2 ... such that the last PROC
1946     argument is applied first and PROC1 last, and return the resulting
1947     procedure.  The given procedures must have compatible arity.
1948
1949          (procedure? (compose 1+ 1-)) ⇒ #t
1950          ((compose sqrt 1+ 1+) 2)     ⇒ 2.0
1951          ((compose 1+ sqrt) 3)        ⇒ 2.73205080756888
1952          (eq? (compose 1+) 1+)        ⇒ #t
1953
1954          ((compose zip unzip2) '((1 2) (a b)))
1955                                       ⇒ ((1 2) (a b))
1956
1957 -- Scheme Procedure: identity x
1958     Return X.
1959
1960 -- Scheme Procedure: and=> value proc
1961     When VALUE is ‘#f’, return ‘#f’.  Otherwise, return ‘(PROC VALUE)’.
1962
1963
1964File: guile.info,  Node: Procedure Properties,  Next: Procedures with Setters,  Prev: Higher-Order Functions,  Up: Procedures
1965
19666.7.7 Procedure Properties and Meta-information
1967-----------------------------------------------
1968
1969In addition to the information that is strictly necessary to run,
1970procedures may have other associated information.  For example, the name
1971of a procedure is information not for the procedure, but about the
1972procedure.  This meta-information can be accessed via the procedure
1973properties interface.
1974
1975   The first group of procedures in this meta-interface are predicates
1976to test whether a Scheme object is a procedure, or a special procedure,
1977respectively.  ‘procedure?’ is the most general predicates, it returns
1978‘#t’ for any kind of procedure.
1979
1980 -- Scheme Procedure: procedure? obj
1981 -- C Function: scm_procedure_p (obj)
1982     Return ‘#t’ if OBJ is a procedure.
1983
1984 -- Scheme Procedure: thunk? obj
1985 -- C Function: scm_thunk_p (obj)
1986     Return ‘#t’ if OBJ is a procedure that can be called with zero
1987     arguments.
1988
1989   Procedure properties are general properties associated with
1990procedures.  These can be the name of a procedure or other relevant
1991information, such as debug hints.
1992
1993 -- Scheme Procedure: procedure-name proc
1994 -- C Function: scm_procedure_name (proc)
1995     Return the name of the procedure PROC
1996
1997 -- Scheme Procedure: procedure-source proc
1998 -- C Function: scm_procedure_source (proc)
1999     Return the source of the procedure PROC.  Returns ‘#f’ if the
2000     source code is not available.
2001
2002 -- Scheme Procedure: procedure-properties proc
2003 -- C Function: scm_procedure_properties (proc)
2004     Return the properties associated with PROC, as an association list.
2005
2006 -- Scheme Procedure: procedure-property proc key
2007 -- C Function: scm_procedure_property (proc, key)
2008     Return the property of PROC with name KEY.
2009
2010 -- Scheme Procedure: set-procedure-properties! proc alist
2011 -- C Function: scm_set_procedure_properties_x (proc, alist)
2012     Set PROC’s property list to ALIST.
2013
2014 -- Scheme Procedure: set-procedure-property! proc key value
2015 -- C Function: scm_set_procedure_property_x (proc, key, value)
2016     In PROC’s property list, set the property named KEY to VALUE.
2017
2018   Documentation for a procedure can be accessed with the procedure
2019‘procedure-documentation’.
2020
2021 -- Scheme Procedure: procedure-documentation proc
2022 -- C Function: scm_procedure_documentation (proc)
2023     Return the documentation string associated with ‘proc’.  By
2024     convention, if a procedure contains more than one expression and
2025     the first expression is a string constant, that string is assumed
2026     to contain documentation for that procedure.
2027
2028
2029File: guile.info,  Node: Procedures with Setters,  Next: Inlinable Procedures,  Prev: Procedure Properties,  Up: Procedures
2030
20316.7.8 Procedures with Setters
2032-----------------------------
2033
2034A “procedure with setter” is a special kind of procedure which normally
2035behaves like any accessor procedure, that is a procedure which accesses
2036a data structure.  The difference is that this kind of procedure has a
2037so-called “setter” attached, which is a procedure for storing something
2038into a data structure.
2039
2040   Procedures with setters are treated specially when the procedure
2041appears in the special form ‘set!’ (REFFIXME). How it works is best
2042shown by example.
2043
2044   Suppose we have a procedure called ‘foo-ref’, which accepts two
2045arguments, a value of type ‘foo’ and an integer.  The procedure returns
2046the value stored at the given index in the ‘foo’ object.  Let ‘f’ be a
2047variable containing such a ‘foo’ data structure.(1)
2048
2049     (foo-ref f 0)       ⇒ bar
2050     (foo-ref f 1)       ⇒ braz
2051
2052   Also suppose that a corresponding setter procedure called ‘foo-set!’
2053does exist.
2054
2055     (foo-set! f 0 'bla)
2056     (foo-ref f 0)       ⇒ bla
2057
2058   Now we could create a new procedure called ‘foo’, which is a
2059procedure with setter, by calling ‘make-procedure-with-setter’ with the
2060accessor and setter procedures ‘foo-ref’ and ‘foo-set!’.  Let us call
2061this new procedure ‘foo’.
2062
2063     (define foo (make-procedure-with-setter foo-ref foo-set!))
2064
2065   ‘foo’ can from now on be used to either read from the data structure
2066stored in ‘f’, or to write into the structure.
2067
2068     (set! (foo f 0) 'dum)
2069     (foo f 0)          ⇒ dum
2070
2071 -- Scheme Procedure: make-procedure-with-setter procedure setter
2072 -- C Function: scm_make_procedure_with_setter (procedure, setter)
2073     Create a new procedure which behaves like PROCEDURE, but with the
2074     associated setter SETTER.
2075
2076 -- Scheme Procedure: procedure-with-setter? obj
2077 -- C Function: scm_procedure_with_setter_p (obj)
2078     Return ‘#t’ if OBJ is a procedure with an associated setter
2079     procedure.
2080
2081 -- Scheme Procedure: procedure proc
2082 -- C Function: scm_procedure (proc)
2083     Return the procedure of PROC, which must be an applicable struct.
2084
2085 -- Scheme Procedure: setter proc
2086     Return the setter of PROC, which must be either a procedure with
2087     setter or an operator struct.
2088
2089   ---------- Footnotes ----------
2090
2091   (1) Working definitions would be:
2092     (define foo-ref vector-ref)
2093     (define foo-set! vector-set!)
2094     (define f (make-vector 2 #f))
2095
2096
2097File: guile.info,  Node: Inlinable Procedures,  Prev: Procedures with Setters,  Up: Procedures
2098
20996.7.9 Inlinable Procedures
2100--------------------------
2101
2102You can define an “inlinable procedure” by using ‘define-inlinable’
2103instead of ‘define’.  An inlinable procedure behaves the same as a
2104regular procedure, but direct calls will result in the procedure body
2105being inlined into the caller.
2106
2107   Bear in mind that starting from version 2.0.3, Guile has a partial
2108evaluator that can inline the body of inner procedures when deemed
2109appropriate:
2110
2111     scheme@(guile-user)> ,optimize (define (foo x)
2112                                      (define (bar) (+ x 3))
2113                                      (* (bar) 2))
2114     $1 = (define foo
2115            (lambda (#{x 94}#) (* (+ #{x 94}# 3) 2)))
2116
2117The partial evaluator does not inline top-level bindings, though, so
2118this is a situation where you may find it interesting to use
2119‘define-inlinable’.
2120
2121   Procedures defined with ‘define-inlinable’ are _always_ inlined, at
2122all direct call sites.  This eliminates function call overhead at the
2123expense of an increase in code size.  Additionally, the caller will not
2124transparently use the new definition if the inline procedure is
2125redefined.  It is not possible to trace an inlined procedures or install
2126a breakpoint in it (*note Traps::).  For these reasons, you should not
2127make a procedure inlinable unless it demonstrably improves performance
2128in a crucial way.
2129
2130   In general, only small procedures should be considered for inlining,
2131as making large procedures inlinable will probably result in an increase
2132in code size.  Additionally, the elimination of the call overhead rarely
2133matters for large procedures.
2134
2135 -- Scheme Syntax: define-inlinable (name parameter ...) body1 body2 ...
2136     Define NAME as a procedure with parameters PARAMETERs and bodies
2137     BODY1, BODY2, ....
2138
2139
2140File: guile.info,  Node: Macros,  Next: Utility Functions,  Prev: Procedures,  Up: API Reference
2141
21426.8 Macros
2143==========
2144
2145At its best, programming in Lisp is an iterative process of building up
2146a language appropriate to the problem at hand, and then solving the
2147problem in that language.  Defining new procedures is part of that, but
2148Lisp also allows the user to extend its syntax, with its famous
2149“macros”.
2150
2151   Macros are syntactic extensions which cause the expression that they
2152appear in to be transformed in some way _before_ being evaluated.  In
2153expressions that are intended for macro transformation, the identifier
2154that names the relevant macro must appear as the first element, like
2155this:
2156
2157     (MACRO-NAME MACRO-ARGS ...)
2158
2159   Macro expansion is a separate phase of evaluation, run before code is
2160interpreted or compiled.  A macro is a program that runs on programs,
2161translating an embedded language into core Scheme(1).
2162
2163* Menu:
2164
2165* Defining Macros::             Binding macros, globally and locally.
2166* Syntax Rules::                Pattern-driven macros.
2167* Syntax Case::                 Procedural, hygienic macros.
2168* Syntax Transformer Helpers::  Helpers for use in procedural macros.
2169* Defmacros::                   Lisp-style macros.
2170* Identifier Macros::           Identifier macros.
2171* Syntax Parameters::           Syntax Parameters.
2172* Eval When::                   Affecting the expand-time environment.
2173* Macro Expansion::             Procedurally expanding macros.
2174* Hygiene and the Top-Level::   A hack you might want to know about.
2175* Internal Macros::             Macros as first-class values.
2176
2177   ---------- Footnotes ----------
2178
2179   (1) These days such embedded languages are often referred to as
2180“embedded domain-specific languages”, or EDSLs.
2181
2182
2183File: guile.info,  Node: Defining Macros,  Next: Syntax Rules,  Up: Macros
2184
21856.8.1 Defining Macros
2186---------------------
2187
2188A macro is a binding between a keyword and a syntax transformer.  Since
2189it’s difficult to discuss ‘define-syntax’ without discussing the format
2190of transformers, consider the following example macro definition:
2191
2192     (define-syntax when
2193       (syntax-rules ()
2194         ((when condition exp ...)
2195          (if condition
2196              (begin exp ...)))))
2197
2198     (when #t
2199       (display "hey ho\n")
2200       (display "let's go\n"))
2201     ⊣ hey ho
2202     ⊣ let's go
2203
2204   In this example, the ‘when’ binding is bound with ‘define-syntax’.
2205Syntax transformers are discussed in more depth in *note Syntax Rules::
2206and *note Syntax Case::.
2207
2208 -- Syntax: define-syntax keyword transformer
2209     Bind KEYWORD to the syntax transformer obtained by evaluating
2210     TRANSFORMER.
2211
2212     After a macro has been defined, further instances of KEYWORD in
2213     Scheme source code will invoke the syntax transformer defined by
2214     TRANSFORMER.
2215
2216   One can also establish local syntactic bindings with ‘let-syntax’.
2217
2218 -- Syntax: let-syntax ((keyword transformer) ...) exp1 exp2 ...
2219     Bind each KEYWORD to its corresponding TRANSFORMER while expanding
2220     EXP1 EXP2 ....
2221
2222     A ‘let-syntax’ binding only exists at expansion-time.
2223
2224          (let-syntax ((unless
2225                        (syntax-rules ()
2226                          ((unless condition exp ...)
2227                           (if (not condition)
2228                               (begin exp ...))))))
2229            (unless #t
2230              (primitive-exit 1))
2231            "rock rock rock")
2232          ⇒ "rock rock rock"
2233
2234   A ‘define-syntax’ form is valid anywhere a definition may appear: at
2235the top-level, or locally.  Just as a local ‘define’ expands out to an
2236instance of ‘letrec’, a local ‘define-syntax’ expands out to
2237‘letrec-syntax’.
2238
2239 -- Syntax: letrec-syntax ((keyword transformer) ...) exp1 exp2 ...
2240     Bind each KEYWORD to its corresponding TRANSFORMER while expanding
2241     EXP1 EXP2 ....
2242
2243     In the spirit of ‘letrec’ versus ‘let’, an expansion produced by
2244     TRANSFORMER may reference a KEYWORD bound by the same
2245     LETREC-SYNTAX.
2246
2247          (letrec-syntax ((my-or
2248                           (syntax-rules ()
2249                             ((my-or)
2250                              #t)
2251                             ((my-or exp)
2252                              exp)
2253                             ((my-or exp rest ...)
2254                              (let ((t exp))
2255                                (if t
2256                                    t
2257                                    (my-or rest ...)))))))
2258            (my-or #f "rockaway beach"))
2259          ⇒ "rockaway beach"
2260
2261
2262File: guile.info,  Node: Syntax Rules,  Next: Syntax Case,  Prev: Defining Macros,  Up: Macros
2263
22646.8.2 Syntax-rules Macros
2265-------------------------
2266
2267‘syntax-rules’ macros are simple, pattern-driven syntax transformers,
2268with a beauty worthy of Scheme.
2269
2270 -- Syntax: syntax-rules literals (pattern template) ...
2271     Create a syntax transformer that will rewrite an expression using
2272     the rules embodied in the PATTERN and TEMPLATE clauses.
2273
2274   A ‘syntax-rules’ macro consists of three parts: the literals (if
2275any), the patterns, and as many templates as there are patterns.
2276
2277   When the syntax expander sees the invocation of a ‘syntax-rules’
2278macro, it matches the expression against the patterns, in order, and
2279rewrites the expression using the template from the first matching
2280pattern.  If no pattern matches, a syntax error is signalled.
2281
22826.8.2.1 Patterns
2283................
2284
2285We have already seen some examples of patterns in the previous section:
2286‘(unless condition exp ...)’, ‘(my-or exp)’, and so on.  A pattern is
2287structured like the expression that it is to match.  It can have nested
2288structure as well, like ‘(let ((var val) ...) exp exp* ...)’.  Broadly
2289speaking, patterns are made of lists, improper lists, vectors,
2290identifiers, and datums.  Users can match a sequence of patterns using
2291the ellipsis (‘...’).
2292
2293   Identifiers in a pattern are called “literals” if they are present in
2294the ‘syntax-rules’ literals list, and “pattern variables” otherwise.
2295When building up the macro output, the expander replaces instances of a
2296pattern variable in the template with the matched subexpression.
2297
2298     (define-syntax kwote
2299       (syntax-rules ()
2300         ((kwote exp)
2301          (quote exp))))
2302     (kwote (foo . bar))
2303     ⇒ (foo . bar)
2304
2305   An improper list of patterns matches as rest arguments do:
2306
2307     (define-syntax let1
2308       (syntax-rules ()
2309         ((_ (var val) . exps)
2310          (let ((var val)) . exps))))
2311
2312   However this definition of ‘let1’ probably isn’t what you want, as
2313the tail pattern EXPS will match non-lists, like ‘(let1 (foo 'bar) .
2314baz)’.  So often instead of using improper lists as patterns, ellipsized
2315patterns are better.  Instances of a pattern variable in the template
2316must be followed by an ellipsis.
2317
2318     (define-syntax let1
2319       (syntax-rules ()
2320         ((_ (var val) exp ...)
2321          (let ((var val)) exp ...))))
2322
2323   This ‘let1’ probably still doesn’t do what we want, because the body
2324matches sequences of zero expressions, like ‘(let1 (foo 'bar))’.  In
2325this case we need to assert we have at least one body expression.  A
2326common idiom for this is to name the ellipsized pattern variable with an
2327asterisk:
2328
2329     (define-syntax let1
2330       (syntax-rules ()
2331         ((_ (var val) exp exp* ...)
2332          (let ((var val)) exp exp* ...))))
2333
2334   A vector of patterns matches a vector whose contents match the
2335patterns, including ellipsizing and tail patterns.
2336
2337     (define-syntax letv
2338       (syntax-rules ()
2339         ((_ #((var val) ...) exp exp* ...)
2340          (let ((var val) ...) exp exp* ...))))
2341     (letv #((foo 'bar)) foo)
2342     ⇒ bar
2343
2344   Literals are used to match specific datums in an expression, like the
2345use of ‘=>’ and ‘else’ in ‘cond’ expressions.
2346
2347     (define-syntax cond1
2348       (syntax-rules (=> else)
2349         ((cond1 test => fun)
2350          (let ((exp test))
2351            (if exp (fun exp) #f)))
2352         ((cond1 test exp exp* ...)
2353          (if test (begin exp exp* ...)))
2354         ((cond1 else exp exp* ...)
2355          (begin exp exp* ...))))
2356
2357     (define (square x) (* x x))
2358     (cond1 10 => square)
2359     ⇒ 100
2360     (let ((=> #t))
2361       (cond1 10 => square))
2362     ⇒ #<procedure square (x)>
2363
2364   A literal matches an input expression if the input expression is an
2365identifier with the same name as the literal, and both are unbound(1).
2366
2367   Although literals can be unbound, usually they are bound to allow
2368them to be imported, exported, and renamed.  *Note Modules::, for more
2369information on imports and exports.  In Guile there are a few standard
2370auxiliary syntax definitions, as specified by R6RS and R7RS:
2371
2372 -- Scheme Syntax: else
2373 -- Scheme Syntax: =>
2374 -- Scheme Syntax: _
2375 -- Scheme Syntax: ...
2376     Auxiliary syntax definitions.
2377
2378     These are defined as if with a macro that never matches, e.g.:
2379
2380          (define-syntax else (syntax-rules ()))
2381
2382   If a pattern is not a list, vector, or an identifier, it matches as a
2383literal, with ‘equal?’.
2384
2385     (define-syntax define-matcher-macro
2386       (syntax-rules ()
2387         ((_ name lit)
2388          (define-syntax name
2389            (syntax-rules ()
2390             ((_ lit) #t)
2391             ((_ else) #f))))))
2392
2393     (define-matcher-macro is-literal-foo? "foo")
2394
2395     (is-literal-foo? "foo")
2396     ⇒ #t
2397     (is-literal-foo? "bar")
2398     ⇒ #f
2399     (let ((foo "foo"))
2400       (is-literal-foo? foo))
2401     ⇒ #f
2402
2403   The last example indicates that matching happens at expansion-time,
2404not at run-time.
2405
2406   Syntax-rules macros are always used as ‘(MACRO . ARGS)’, and the
2407MACRO will always be a symbol.  Correspondingly, a ‘syntax-rules’
2408pattern must be a list (proper or improper), and the first pattern in
2409that list must be an identifier.  Incidentally it can be any identifier
2410– it doesn’t have to actually be the name of the macro.  Thus the
2411following three are equivalent:
2412
2413     (define-syntax when
2414       (syntax-rules ()
2415         ((when c e ...)
2416          (if c (begin e ...)))))
2417
2418     (define-syntax when
2419       (syntax-rules ()
2420         ((_ c e ...)
2421          (if c (begin e ...)))))
2422
2423     (define-syntax when
2424       (syntax-rules ()
2425         ((something-else-entirely c e ...)
2426          (if c (begin e ...)))))
2427
2428   For clarity, use one of the first two variants.  Also note that since
2429the pattern variable will always match the macro itself (e.g., ‘cond1’),
2430it is actually left unbound in the template.
2431
24326.8.2.2 Hygiene
2433...............
2434
2435‘syntax-rules’ macros have a magical property: they preserve referential
2436transparency.  When you read a macro definition, any free bindings in
2437that macro are resolved relative to the macro definition; and when you
2438read a macro instantiation, all free bindings in that expression are
2439resolved relative to the expression.
2440
2441   This property is sometimes known as “hygiene”, and it does aid in
2442code cleanliness.  In your macro definitions, you can feel free to
2443introduce temporary variables, without worrying about inadvertently
2444introducing bindings into the macro expansion.
2445
2446   Consider the definition of ‘my-or’ from the previous section:
2447
2448     (define-syntax my-or
2449       (syntax-rules ()
2450         ((my-or)
2451          #t)
2452         ((my-or exp)
2453          exp)
2454         ((my-or exp rest ...)
2455          (let ((t exp))
2456            (if t
2457                t
2458                (my-or rest ...))))))
2459
2460   A naive expansion of ‘(let ((t #t)) (my-or #f t))’ would yield:
2461
2462     (let ((t #t))
2463       (let ((t #f))
2464         (if t t t)))
2465     ⇒ #f
2466
2467Which clearly is not what we want.  Somehow the ‘t’ in the definition is
2468distinct from the ‘t’ at the site of use; and it is indeed this
2469distinction that is maintained by the syntax expander, when expanding
2470hygienic macros.
2471
2472   This discussion is mostly relevant in the context of traditional Lisp
2473macros (*note Defmacros::), which do not preserve referential
2474transparency.  Hygiene adds to the expressive power of Scheme.
2475
24766.8.2.3 Shorthands
2477..................
2478
2479One often ends up writing simple one-clause ‘syntax-rules’ macros.
2480There is a convenient shorthand for this idiom, in the form of
2481‘define-syntax-rule’.
2482
2483 -- Syntax: define-syntax-rule (keyword . pattern) [docstring] template
2484     Define KEYWORD as a new ‘syntax-rules’ macro with one clause.
2485
2486   Cast into this form, our ‘when’ example is significantly shorter:
2487
2488     (define-syntax-rule (when c e ...)
2489       (if c (begin e ...)))
2490
24916.8.2.4 Reporting Syntax Errors in Macros
2492.........................................
2493
2494 -- Syntax: syntax-error message [arg ...]
2495     Report an error at macro-expansion time.  MESSAGE must be a string
2496     literal, and the optional ARG operands can be arbitrary expressions
2497     providing additional information.
2498
2499   ‘syntax-error’ is intended to be used within ‘syntax-rules’
2500templates.  For example:
2501
2502     (define-syntax simple-let
2503       (syntax-rules ()
2504         ((_ (head ... ((x . y) val) . tail)
2505             body1 body2 ...)
2506          (syntax-error
2507           "expected an identifier but got"
2508           (x . y)))
2509         ((_ ((name val) ...) body1 body2 ...)
2510          ((lambda (name ...) body1 body2 ...)
2511           val ...))))
2512
25136.8.2.5 Specifying a Custom Ellipsis Identifier
2514...............................................
2515
2516When writing macros that generate macro definitions, it is convenient to
2517use a different ellipsis identifier at each level.  Guile allows the
2518desired ellipsis identifier to be specified as the first operand to
2519‘syntax-rules’, as specified by SRFI-46 and R7RS. For example:
2520
2521     (define-syntax define-quotation-macros
2522       (syntax-rules ()
2523         ((_ (macro-name head-symbol) ...)
2524          (begin (define-syntax macro-name
2525                   (syntax-rules ::: ()
2526                     ((_ x :::)
2527                      (quote (head-symbol x :::)))))
2528                 ...))))
2529     (define-quotation-macros (quote-a a) (quote-b b) (quote-c c))
2530     (quote-a 1 2 3) ⇒ (a 1 2 3)
2531
25326.8.2.6 Further Information
2533...........................
2534
2535For a formal definition of ‘syntax-rules’ and its pattern language, see
2536*Note Macros: (r5rs)Macros.
2537
2538   ‘syntax-rules’ macros are simple and clean, but do they have
2539limitations.  They do not lend themselves to expressive error messages:
2540patterns either match or they don’t.  Their ability to generate code is
2541limited to template-driven expansion; often one needs to define a number
2542of helper macros to get real work done.  Sometimes one wants to
2543introduce a binding into the lexical context of the generated code; this
2544is impossible with ‘syntax-rules’.  Relatedly, they cannot
2545programmatically generate identifiers.
2546
2547   The solution to all of these problems is to use ‘syntax-case’ if you
2548need its features.  But if for some reason you’re stuck with
2549‘syntax-rules’, you might enjoy Joe Marshall’s ‘syntax-rules’ Primer for
2550the Merely Eccentric
2551(http://sites.google.com/site/evalapply/eccentric.txt).
2552
2553   ---------- Footnotes ----------
2554
2555   (1) Language lawyers probably see the need here for use of
2556‘literal-identifier=?’ rather than ‘free-identifier=?’, and would
2557probably be correct.  Patches accepted.
2558
2559
2560File: guile.info,  Node: Syntax Case,  Next: Syntax Transformer Helpers,  Prev: Syntax Rules,  Up: Macros
2561
25626.8.3 Support for the ‘syntax-case’ System
2563------------------------------------------
2564
2565‘syntax-case’ macros are procedural syntax transformers, with a power
2566worthy of Scheme.
2567
2568 -- Syntax: syntax-case syntax literals (pattern [guard] exp) ...
2569     Match the syntax object SYNTAX against the given patterns, in
2570     order.  If a PATTERN matches, return the result of evaluating the
2571     associated EXP.
2572
2573   Compare the following definitions of ‘when’:
2574
2575     (define-syntax when
2576       (syntax-rules ()
2577         ((_ test e e* ...)
2578          (if test (begin e e* ...)))))
2579
2580     (define-syntax when
2581       (lambda (x)
2582         (syntax-case x ()
2583           ((_ test e e* ...)
2584            #'(if test (begin e e* ...))))))
2585
2586   Clearly, the ‘syntax-case’ definition is similar to its
2587‘syntax-rules’ counterpart, and equally clearly there are some
2588differences.  The ‘syntax-case’ definition is wrapped in a ‘lambda’, a
2589function of one argument; that argument is passed to the ‘syntax-case’
2590invocation; and the “return value” of the macro has a ‘#'’ prefix.
2591
2592   All of these differences stem from the fact that ‘syntax-case’ does
2593not define a syntax transformer itself – instead, ‘syntax-case’
2594expressions provide a way to destructure a “syntax object”, and to
2595rebuild syntax objects as output.
2596
2597   So the ‘lambda’ wrapper is simply a leaky implementation detail, that
2598syntax transformers are just functions that transform syntax to syntax.
2599This should not be surprising, given that we have already described
2600macros as “programs that write programs”.  ‘syntax-case’ is simply a way
2601to take apart and put together program text, and to be a valid syntax
2602transformer it needs to be wrapped in a procedure.
2603
2604   Unlike traditional Lisp macros (*note Defmacros::), ‘syntax-case’
2605macros transform syntax objects, not raw Scheme forms.  Recall the naive
2606expansion of ‘my-or’ given in the previous section:
2607
2608     (let ((t #t))
2609       (my-or #f t))
2610     ;; naive expansion:
2611     (let ((t #t))
2612       (let ((t #f))
2613         (if t t t)))
2614
2615   Raw Scheme forms simply don’t have enough information to distinguish
2616the first two ‘t’ instances in ‘(if t t t)’ from the third ‘t’.  So
2617instead of representing identifiers as symbols, the syntax expander
2618represents identifiers as annotated syntax objects, attaching such
2619information to those syntax objects as is needed to maintain referential
2620transparency.
2621
2622 -- Syntax: syntax form
2623     Create a syntax object wrapping FORM within the current lexical
2624     context.
2625
2626   Syntax objects are typically created internally to the process of
2627expansion, but it is possible to create them outside of syntax
2628expansion:
2629
2630     (syntax (foo bar baz))
2631     ⇒ #<some representation of that syntax>
2632
2633However it is more common, and useful, to create syntax objects when
2634building output from a ‘syntax-case’ expression.
2635
2636     (define-syntax add1
2637       (lambda (x)
2638         (syntax-case x ()
2639           ((_ exp)
2640            (syntax (+ exp 1))))))
2641
2642   It is not strictly necessary for a ‘syntax-case’ expression to return
2643a syntax object, because ‘syntax-case’ expressions can be used in helper
2644functions, or otherwise used outside of syntax expansion itself.
2645However a syntax transformer procedure must return a syntax object, so
2646most uses of ‘syntax-case’ do end up returning syntax objects.
2647
2648   Here in this case, the form that built the return value was ‘(syntax
2649(+ exp 1))’.  The interesting thing about this is that within a ‘syntax’
2650expression, any appearance of a pattern variable is substituted into the
2651resulting syntax object, carrying with it all relevant metadata from the
2652source expression, such as lexical identity and source location.
2653
2654   Indeed, a pattern variable may only be referenced from inside a
2655‘syntax’ form.  The syntax expander would raise an error when defining
2656‘add1’ if it found EXP referenced outside a ‘syntax’ form.
2657
2658   Since ‘syntax’ appears frequently in macro-heavy code, it has a
2659special reader macro: ‘#'’.  ‘#'foo’ is transformed by the reader into
2660‘(syntax foo)’, just as ‘'foo’ is transformed into ‘(quote foo)’.
2661
2662   The pattern language used by ‘syntax-case’ is conveniently the same
2663language used by ‘syntax-rules’.  Given this, Guile actually defines
2664‘syntax-rules’ in terms of ‘syntax-case’:
2665
2666     (define-syntax syntax-rules
2667       (lambda (x)
2668         (syntax-case x ()
2669           ((_ (k ...) ((keyword . pattern) template) ...)
2670            #'(lambda (x)
2671                (syntax-case x (k ...)
2672                  ((dummy . pattern) #'template)
2673                  ...))))))
2674
2675   And that’s that.
2676
26776.8.3.1 Why ‘syntax-case’?
2678..........................
2679
2680The examples we have shown thus far could just as well have been
2681expressed with ‘syntax-rules’, and have just shown that ‘syntax-case’ is
2682more verbose, which is true.  But there is a difference: ‘syntax-case’
2683creates _procedural_ macros, giving the full power of Scheme to the
2684macro expander.  This has many practical applications.
2685
2686   A common desire is to be able to match a form only if it is an
2687identifier.  This is impossible with ‘syntax-rules’, given the datum
2688matching forms.  But with ‘syntax-case’ it is easy:
2689
2690 -- Scheme Procedure: identifier? syntax-object
2691     Returns ‘#t’ if SYNTAX-OBJECT is an identifier, or ‘#f’ otherwise.
2692
2693     ;; relying on previous add1 definition
2694     (define-syntax add1!
2695       (lambda (x)
2696         (syntax-case x ()
2697           ((_ var) (identifier? #'var)
2698            #'(set! var (add1 var))))))
2699
2700     (define foo 0)
2701     (add1! foo)
2702     foo ⇒ 1
2703     (add1! "not-an-identifier") ⇒ error
2704
2705   With ‘syntax-rules’, the error for ‘(add1! "not-an-identifier")’
2706would be something like “invalid ‘set!’”.  With ‘syntax-case’, it will
2707say something like “invalid ‘add1!’”, because we attach the “guard
2708clause” to the pattern: ‘(identifier? #'var)’.  This becomes more
2709important with more complicated macros.  It is necessary to use
2710‘identifier?’, because to the expander, an identifier is more than a
2711bare symbol.
2712
2713   Note that even in the guard clause, we reference the VAR pattern
2714variable within a ‘syntax’ form, via ‘#'var’.
2715
2716   Another common desire is to introduce bindings into the lexical
2717context of the output expression.  One example would be in the so-called
2718“anaphoric macros”, like ‘aif’.  Anaphoric macros bind some expression
2719to a well-known identifier, often ‘it’, within their bodies.  For
2720example, in ‘(aif (foo) (bar it))’, ‘it’ would be bound to the result of
2721‘(foo)’.
2722
2723   To begin with, we should mention a solution that doesn’t work:
2724
2725     ;; doesn't work
2726     (define-syntax aif
2727       (lambda (x)
2728         (syntax-case x ()
2729           ((_ test then else)
2730            #'(let ((it test))
2731                (if it then else))))))
2732
2733   The reason that this doesn’t work is that, by default, the expander
2734will preserve referential transparency; the THEN and ELSE expressions
2735won’t have access to the binding of ‘it’.
2736
2737   But they can, if we explicitly introduce a binding via
2738‘datum->syntax’.
2739
2740 -- Scheme Procedure: datum->syntax template-id datum [#:source=#f]
2741     Create a syntax object that wraps DATUM, within the lexical context
2742     corresponding to the identifier TEMPLATE-ID.  If TEMPLATE-ID is
2743     false, the datum will have no lexical context information.
2744
2745     Syntax objects have an associated source location.  Internally this
2746     is represented as a 3-element vector of filename, line, and column.
2747     Usually this location ultimately is provided by ‘read-syntax’;
2748     *Note Annotated Scheme Read::.
2749
2750     If a syntax object is passed as SOURCE, the resulting syntax object
2751     will have the source location of SOURCE.  Otherwise if SOURCE is a
2752     3-element source location vector, that vector will be the source
2753     location of the resulting syntax object.  If SOURCE is a source
2754     properties alist, those will be parsed and set as the source
2755     location of the resulting syntax object.  Otherwise if SOURCE is
2756     false, the source properties are looked up from ‘(source-properties
2757     DATUM)’.  *Note Source Properties::.
2758
2759   For completeness, we should mention that it is possible to strip the
2760metadata from a syntax object, returning a raw Scheme datum:
2761
2762 -- Scheme Procedure: syntax->datum syntax-object
2763     Strip the metadata from SYNTAX-OBJECT, returning its contents as a
2764     raw Scheme datum.
2765
2766   In this case we want to introduce ‘it’ in the context of the whole
2767expression, so we can create a syntax object as ‘(datum->syntax x 'it)’,
2768where ‘x’ is the whole expression, as passed to the transformer
2769procedure.
2770
2771   Here’s another solution that doesn’t work:
2772
2773     ;; doesn't work either
2774     (define-syntax aif
2775       (lambda (x)
2776         (syntax-case x ()
2777           ((_ test then else)
2778            (let ((it (datum->syntax x 'it)))
2779              #'(let ((it test))
2780                  (if it then else)))))))
2781
2782   The reason that this one doesn’t work is that there are really two
2783environments at work here – the environment of pattern variables, as
2784bound by ‘syntax-case’, and the environment of lexical variables, as
2785bound by normal Scheme.  The outer let form establishes a binding in the
2786environment of lexical variables, but the inner let form is inside a
2787syntax form, where only pattern variables will be substituted.  Here we
2788need to introduce a piece of the lexical environment into the pattern
2789variable environment, and we can do so using ‘syntax-case’ itself:
2790
2791     ;; works, but is obtuse
2792     (define-syntax aif
2793       (lambda (x)
2794         (syntax-case x ()
2795           ((_ test then else)
2796            ;; invoking syntax-case on the generated
2797            ;; syntax object to expose it to `syntax'
2798            (syntax-case (datum->syntax x 'it) ()
2799              (it
2800                #'(let ((it test))
2801                    (if it then else))))))))
2802
2803     (aif (getuid) (display it) (display "none")) (newline)
2804     ⊣ 500
2805
2806   However there are easier ways to write this.  ‘with-syntax’ is often
2807convenient:
2808
2809 -- Syntax: with-syntax ((pat val) ...) exp ...
2810     Bind patterns PAT from their corresponding values VAL, within the
2811     lexical context of EXP ....
2812
2813          ;; better
2814          (define-syntax aif
2815            (lambda (x)
2816              (syntax-case x ()
2817                ((_ test then else)
2818                 (with-syntax ((it (datum->syntax x 'it)))
2819                   #'(let ((it test))
2820                       (if it then else)))))))
2821
2822   As you might imagine, ‘with-syntax’ is defined in terms of
2823‘syntax-case’.  But even that might be off-putting to you if you are an
2824old Lisp macro hacker, used to building macro output with ‘quasiquote’.
2825The issue is that ‘with-syntax’ creates a separation between the point
2826of definition of a value and its point of substitution.
2827
2828   So for cases in which a ‘quasiquote’ style makes more sense,
2829‘syntax-case’ also defines ‘quasisyntax’, and the related ‘unsyntax’ and
2830‘unsyntax-splicing’, abbreviated by the reader as ‘#`’, ‘#,’, and ‘#,@’,
2831respectively.
2832
2833   For example, to define a macro that inserts a compile-time timestamp
2834into a source file, one may write:
2835
2836     (define-syntax display-compile-timestamp
2837       (lambda (x)
2838         (syntax-case x ()
2839           ((_)
2840            #`(begin
2841               (display "The compile timestamp was: ")
2842               (display #,(current-time))
2843               (newline))))))
2844
2845   Readers interested in further information on ‘syntax-case’ macros
2846should see R. Kent Dybvig’s excellent ‘The Scheme Programming Language’,
2847either edition 3 or 4, in the chapter on syntax.  Dybvig was the primary
2848author of the ‘syntax-case’ system.  The book itself is available online
2849at <http://scheme.com/tspl4/>.
2850
28516.8.3.2 Custom Ellipsis Identifiers for syntax-case Macros
2852..........................................................
2853
2854When writing procedural macros that generate macro definitions, it is
2855convenient to use a different ellipsis identifier at each level.  Guile
2856supports this for procedural macros using the ‘with-ellipsis’ special
2857form:
2858
2859 -- Syntax: with-ellipsis ellipsis body ...
2860     ELLIPSIS must be an identifier.  Evaluate BODY in a special lexical
2861     environment such that all macro patterns and templates within BODY
2862     will use ELLIPSIS as the ellipsis identifier instead of the usual
2863     three dots (‘...’).
2864
2865   For example:
2866
2867     (define-syntax define-quotation-macros
2868       (lambda (x)
2869         (syntax-case x ()
2870           ((_ (macro-name head-symbol) ...)
2871            #'(begin (define-syntax macro-name
2872                       (lambda (x)
2873                         (with-ellipsis :::
2874                           (syntax-case x ()
2875                             ((_ x :::)
2876                              #'(quote (head-symbol x :::)))))))
2877                     ...)))))
2878     (define-quotation-macros (quote-a a) (quote-b b) (quote-c c))
2879     (quote-a 1 2 3) ⇒ (a 1 2 3)
2880
2881   Note that ‘with-ellipsis’ does not affect the ellipsis identifier of
2882the generated code, unless ‘with-ellipsis’ is included around the
2883generated code.
2884
28856.8.3.3 Syntax objects can be data too
2886......................................
2887
2888Generally speaking, you want the macro expander to pick apart all syntax
2889objects in a source term.  The source and scope annotations attached to
2890the syntax object are of interest to how the macro expander computes the
2891result, but no syntax object itself should appear in the expanded
2892term—usually.  Sometimes, though, a macro will want a syntax object to
2893appear in the expanded output.  Normally you would just use ‘quote’ to
2894introduce the syntax object as a value, but the expander strips syntax
2895objects from subexpression of ‘quote’.  For this rare use case, Guile
2896has ‘quote-syntax’, which does not strip its subexpression.
2897
2898 -- Syntax: quote-syntax form
2899     Expand to the syntax object ‘form’, as a constant literal.  Like
2900     ‘quote’, but without calling ‘syntax->datum’.
2901
2902
2903File: guile.info,  Node: Syntax Transformer Helpers,  Next: Defmacros,  Prev: Syntax Case,  Up: Macros
2904
29056.8.4 Syntax Transformer Helpers
2906--------------------------------
2907
2908As noted in the previous section, Guile’s syntax expander operates on
2909syntax objects.  Procedural macros consume and produce syntax objects.
2910This section describes some of the auxiliary helpers that procedural
2911macros can use to compare, generate, and query objects of this data
2912type.
2913
2914 -- Scheme Procedure: bound-identifier=? a b
2915     Return ‘#t’ if the syntax objects A and B refer to the same
2916     lexically-bound identifier, or ‘#f’ otherwise.
2917
2918 -- Scheme Procedure: free-identifier=? a b
2919     Return ‘#t’ if the syntax objects A and B refer to the same free
2920     identifier, or ‘#f’ otherwise.
2921
2922 -- Scheme Procedure: generate-temporaries ls
2923     Return a list of temporary identifiers as long as LS is long.
2924
2925 -- Scheme Procedure: syntax-source x
2926     Return the source properties that correspond to the syntax object
2927     X.  *Note Source Properties::, for more information.
2928
2929   Guile also offers some more experimental interfaces in a separate
2930module.  As was the case with the Large Hadron Collider, it is unclear
2931to our senior macrologists whether adding these interfaces will result
2932in awesomeness or in the destruction of Guile via the creation of a
2933singularity.  We will preserve their functionality through the 2.0
2934series, but we reserve the right to modify them in a future stable
2935series, to a more than usual degree.
2936
2937     (use-modules (system syntax))
2938
2939 -- Scheme Procedure: syntax-module id
2940     Return the name of the module whose source contains the identifier
2941     ID.
2942
2943 -- Scheme Procedure: syntax-sourcev stx
2944     Like ‘syntax-source’, but returns its result in a more compact
2945     ‘#(FILENAME LINE COLUMN)’ format.  This format is used as the
2946     internal representation of source locations for syntax objects.
2947
2948 -- Scheme Procedure: syntax-local-binding id
2949          [#:resolve-syntax-parameters?=#t]
2950     Resolve the identifer ID, a syntax object, within the current
2951     lexical environment, and return two values, the binding type and a
2952     binding value.  The binding type is a symbol, which may be one of
2953     the following:
2954
2955     ‘lexical’
2956          A lexically-bound variable.  The value is a unique token (in
2957          the sense of ‘eq?’) identifying this binding.
2958     ‘macro’
2959          A syntax transformer, either local or global.  The value is
2960          the transformer procedure.
2961     ‘syntax-parameter’
2962          A syntax parameter (*note Syntax Parameters::).  By default,
2963          ‘syntax-local-binding’ will resolve syntax parameters, so that
2964          this value will not be returned.  Pass
2965          ‘#:resolve-syntax-parameters? #f’ to indicate that you are
2966          interested in syntax parameters.  The value is the default
2967          transformer procedure, as in ‘macro’.
2968     ‘pattern-variable’
2969          A pattern variable, bound via ‘syntax-case’.  The value is an
2970          opaque object, internal to the expander.
2971     ‘ellipsis’
2972          An internal binding, bound via ‘with-ellipsis’.  The value is
2973          the (anti-marked) local ellipsis identifier.
2974     ‘displaced-lexical’
2975          A lexical variable that has gone out of scope.  This can
2976          happen if a badly-written procedural macro saves a syntax
2977          object, then attempts to introduce it in a context in which it
2978          is unbound.  The value is ‘#f’.
2979     ‘global’
2980          A global binding.  The value is a pair, whose head is the
2981          symbol, and whose tail is the name of the module in which to
2982          resolve the symbol.
2983     ‘other’
2984          Some other binding, like ‘lambda’ or other core bindings.  The
2985          value is ‘#f’.
2986
2987     This is a very low-level procedure, with limited uses.  One case in
2988     which it is useful is to build abstractions that associate
2989     auxiliary information with macros:
2990
2991          (define aux-property (make-object-property))
2992          (define-syntax-rule (with-aux aux value)
2993            (let ((trans value))
2994              (set! (aux-property trans) aux)
2995              trans))
2996          (define-syntax retrieve-aux
2997            (lambda (x)
2998              (syntax-case x ()
2999                ((x id)
3000                 (call-with-values (lambda () (syntax-local-binding #'id))
3001                   (lambda (type val)
3002                     (with-syntax ((aux (datum->syntax #'here
3003                                                       (and (eq? type 'macro)
3004                                                            (aux-property val)))))
3005                       #''aux)))))))
3006          (define-syntax foo
3007            (with-aux 'bar
3008              (syntax-rules () ((_) 'foo))))
3009          (foo)
3010          ⇒ foo
3011          (retrieve-aux foo)
3012          ⇒ bar
3013
3014     ‘syntax-local-binding’ must be called within the dynamic extent of
3015     a syntax transformer; to call it otherwise will signal an error.
3016
3017 -- Scheme Procedure: syntax-locally-bound-identifiers id
3018     Return a list of identifiers that were visible lexically when the
3019     identifier ID was created, in order from outermost to innermost.
3020
3021     This procedure is intended to be used in specialized procedural
3022     macros, to provide a macro with the set of bound identifiers that
3023     the macro can reference.
3024
3025     As a technical implementation detail, the identifiers returned by
3026     ‘syntax-locally-bound-identifiers’ will be anti-marked, like the
3027     syntax object that is given as input to a macro.  This is to signal
3028     to the macro expander that these bindings were present in the
3029     original source, and do not need to be hygienically renamed, as
3030     would be the case with other introduced identifiers.  See the
3031     discussion of hygiene in section 12.1 of the R6RS, for more
3032     information on marks.
3033
3034          (define (local-lexicals id)
3035            (filter (lambda (x)
3036                      (eq? (syntax-local-binding x) 'lexical))
3037                    (syntax-locally-bound-identifiers id)))
3038          (define-syntax lexicals
3039            (lambda (x)
3040              (syntax-case x ()
3041                ((lexicals) #'(lexicals lexicals))
3042                ((lexicals scope)
3043                 (with-syntax (((id ...) (local-lexicals #'scope)))
3044                   #'(list (cons 'id id) ...))))))
3045
3046          (let* ((x 10) (x 20)) (lexicals))
3047          ⇒ ((x . 10) (x . 20))
3048
3049
3050File: guile.info,  Node: Defmacros,  Next: Identifier Macros,  Prev: Syntax Transformer Helpers,  Up: Macros
3051
30526.8.5 Lisp-style Macro Definitions
3053----------------------------------
3054
3055The traditional way to define macros in Lisp is very similar to
3056procedure definitions.  The key differences are that the macro
3057definition body should return a list that describes the transformed
3058expression, and that the definition is marked as a macro definition
3059(rather than a procedure definition) by the use of a different
3060definition keyword: in Lisp, ‘defmacro’ rather than ‘defun’, and in
3061Scheme, ‘define-macro’ rather than ‘define’.
3062
3063   Guile supports this style of macro definition using both ‘defmacro’
3064and ‘define-macro’.  The only difference between them is how the macro
3065name and arguments are grouped together in the definition:
3066
3067     (defmacro NAME (ARGS ...) BODY ...)
3068
3069is the same as
3070
3071     (define-macro (NAME ARGS ...) BODY ...)
3072
3073The difference is analogous to the corresponding difference between
3074Lisp’s ‘defun’ and Scheme’s ‘define’.
3075
3076   Having read the previous section on ‘syntax-case’, it’s probably
3077clear that Guile actually implements defmacros in terms of
3078‘syntax-case’, applying the transformer on the expression between
3079invocations of ‘syntax->datum’ and ‘datum->syntax’.  This realization
3080leads us to the problem with defmacros, that they do not preserve
3081referential transparency.  One can be careful to not introduce bindings
3082into expanded code, via liberal use of ‘gensym’, but there is no getting
3083around the lack of referential transparency for free bindings in the
3084macro itself.
3085
3086   Even a macro as simple as our ‘when’ from before is difficult to get
3087right:
3088
3089     (define-macro (when cond exp . rest)
3090       `(if ,cond
3091            (begin ,exp . ,rest)))
3092
3093     (when #f (display "Launching missiles!\n"))
3094     ⇒ #f
3095
3096     (let ((if list))
3097       (when #f (display "Launching missiles!\n")))
3098     ⊣ Launching missiles!
3099     ⇒ (#f #<unspecified>)
3100
3101   Guile’s perspective is that defmacros have had a good run, but that
3102modern macros should be written with ‘syntax-rules’ or ‘syntax-case’.
3103There are still many uses of defmacros within Guile itself, but we will
3104be phasing them out over time.  Of course we won’t take away ‘defmacro’
3105or ‘define-macro’ themselves, as there is lots of code out there that
3106uses them.
3107
3108
3109File: guile.info,  Node: Identifier Macros,  Next: Syntax Parameters,  Prev: Defmacros,  Up: Macros
3110
31116.8.6 Identifier Macros
3112-----------------------
3113
3114When the syntax expander sees a form in which the first element is a
3115macro, the whole form gets passed to the macro’s syntax transformer.
3116One may visualize this as:
3117
3118     (define-syntax foo foo-transformer)
3119     (foo ARG...)
3120     ;; expands via
3121     (foo-transformer #'(foo ARG...))
3122
3123   If, on the other hand, a macro is referenced in some other part of a
3124form, the syntax transformer is invoked with only the macro reference,
3125not the whole form.
3126
3127     (define-syntax foo foo-transformer)
3128     foo
3129     ;; expands via
3130     (foo-transformer #'foo)
3131
3132   This allows bare identifier references to be replaced
3133programmatically via a macro.  ‘syntax-rules’ provides some syntax to
3134effect this transformation more easily.
3135
3136 -- Syntax: identifier-syntax exp
3137     Returns a macro transformer that will replace occurrences of the
3138     macro with EXP.
3139
3140   For example, if you are importing external code written in terms of
3141‘fx+’, the fixnum addition operator, but Guile doesn’t have ‘fx+’, you
3142may use the following to replace ‘fx+’ with ‘+’:
3143
3144     (define-syntax fx+ (identifier-syntax +))
3145
3146   There is also special support for recognizing identifiers on the
3147left-hand side of a ‘set!’ expression, as in the following:
3148
3149     (define-syntax foo foo-transformer)
3150     (set! foo VAL)
3151     ;; expands via
3152     (foo-transformer #'(set! foo VAL))
3153     ;; if foo-transformer is a "variable transformer"
3154
3155   As the example notes, the transformer procedure must be explicitly
3156marked as being a “variable transformer”, as most macros aren’t written
3157to discriminate on the form in the operator position.
3158
3159 -- Scheme Procedure: make-variable-transformer transformer
3160     Mark the TRANSFORMER procedure as being a “variable transformer”.
3161     In practice this means that, when bound to a syntactic keyword, it
3162     may detect references to that keyword on the left-hand-side of a
3163     ‘set!’.
3164
3165          (define bar 10)
3166          (define-syntax bar-alias
3167            (make-variable-transformer
3168             (lambda (x)
3169               (syntax-case x (set!)
3170                 ((set! var val) #'(set! bar val))
3171                 ((var arg ...) #'(bar arg ...))
3172                 (var (identifier? #'var) #'bar)))))
3173
3174          bar-alias ⇒ 10
3175          (set! bar-alias 20)
3176          bar ⇒ 20
3177          (set! bar 30)
3178          bar-alias ⇒ 30
3179
3180   There is an extension to identifier-syntax which allows it to handle
3181the ‘set!’ case as well:
3182
3183 -- Syntax: identifier-syntax (var exp1) ((set! var val) exp2)
3184     Create a variable transformer.  The first clause is used for
3185     references to the variable in operator or operand position, and the
3186     second for appearances of the variable on the left-hand-side of an
3187     assignment.
3188
3189     For example, the previous ‘bar-alias’ example could be expressed
3190     more succinctly like this:
3191
3192          (define-syntax bar-alias
3193            (identifier-syntax
3194              (var bar)
3195              ((set! var val) (set! bar val))))
3196
3197     As before, the templates in ‘identifier-syntax’ forms do not need
3198     wrapping in ‘#'’ syntax forms.
3199
3200
3201File: guile.info,  Node: Syntax Parameters,  Next: Eval When,  Prev: Identifier Macros,  Up: Macros
3202
32036.8.7 Syntax Parameters
3204-----------------------
3205
3206Syntax parameters(1) are a mechanism for rebinding a macro definition
3207within the dynamic extent of a macro expansion.  This provides a
3208convenient solution to one of the most common types of unhygienic macro:
3209those that introduce a unhygienic binding each time the macro is used.
3210Examples include a ‘lambda’ form with a ‘return’ keyword, or class
3211macros that introduce a special ‘self’ binding.
3212
3213   With syntax parameters, instead of introducing the binding
3214unhygienically each time, we instead create one binding for the keyword,
3215which we can then adjust later when we want the keyword to have a
3216different meaning.  As no new bindings are introduced, hygiene is
3217preserved.  This is similar to the dynamic binding mechanisms we have at
3218run-time (*note parameters: SRFI-39.), except that the dynamic binding
3219only occurs during macro expansion.  The code after macro expansion
3220remains lexically scoped.
3221
3222 -- Syntax: define-syntax-parameter keyword transformer
3223     Binds KEYWORD to the value obtained by evaluating TRANSFORMER.  The
3224     TRANSFORMER provides the default expansion for the syntax
3225     parameter, and in the absence of ‘syntax-parameterize’, is
3226     functionally equivalent to ‘define-syntax’.  Usually, you will just
3227     want to have the TRANSFORMER throw a syntax error indicating that
3228     the KEYWORD is supposed to be used in conjunction with another
3229     macro, for example:
3230          (define-syntax-parameter return
3231            (lambda (stx)
3232              (syntax-violation 'return "return used outside of a lambda^" stx)))
3233
3234 -- Syntax: syntax-parameterize ((keyword transformer) ...) exp ...
3235     Adjusts KEYWORD ... to use the values obtained by evaluating their
3236     TRANSFORMER ..., in the expansion of the EXP ... forms.  Each
3237     KEYWORD must be bound to a syntax-parameter.  ‘syntax-parameterize’
3238     differs from ‘let-syntax’, in that the binding is not shadowed, but
3239     adjusted, and so uses of the keyword in the expansion of EXP ...
3240     use the new transformers.  This is somewhat similar to how
3241     ‘parameterize’ adjusts the values of regular parameters, rather
3242     than creating new bindings.
3243
3244          (define-syntax lambda^
3245            (syntax-rules ()
3246              [(lambda^ argument-list body body* ...)
3247               (lambda argument-list
3248                 (call-with-current-continuation
3249                  (lambda (escape)
3250                    ;; In the body we adjust the 'return' keyword so that calls
3251                    ;; to 'return' are replaced with calls to the escape
3252                    ;; continuation.
3253                    (syntax-parameterize ([return (syntax-rules ()
3254                                                    [(return vals (... ...))
3255                                                     (escape vals (... ...))])])
3256                      body body* ...))))]))
3257
3258          ;; Now we can write functions that return early.  Here, 'product' will
3259          ;; return immediately if it sees any 0 element.
3260          (define product
3261            (lambda^ (list)
3262                     (fold (lambda (n o)
3263                             (if (zero? n)
3264                                 (return 0)
3265                                 (* n o)))
3266                           1
3267                           list)))
3268
3269   ---------- Footnotes ----------
3270
3271   (1) Described in the paper ‘Keeping it Clean with Syntax Parameters’
3272by Barzilay, Culpepper and Flatt.
3273
3274
3275File: guile.info,  Node: Eval When,  Next: Macro Expansion,  Prev: Syntax Parameters,  Up: Macros
3276
32776.8.8 Eval-when
3278---------------
3279
3280As ‘syntax-case’ macros have the whole power of Scheme available to
3281them, they present a problem regarding time: when a macro runs, what
3282parts of the program are available for the macro to use?
3283
3284   The default answer to this question is that when you import a module
3285(via ‘define-module’ or ‘use-modules’), that module will be loaded up at
3286expansion-time, as well as at run-time.  Additionally, top-level
3287syntactic definitions within one compilation unit made by
3288‘define-syntax’ are also evaluated at expansion time, in the order that
3289they appear in the compilation unit (file).
3290
3291   But if a syntactic definition needs to call out to a normal procedure
3292at expansion-time, it might well need need special declarations to
3293indicate that the procedure should be made available at expansion-time.
3294
3295   For example, the following code will work at a REPL, but not in a
3296file:
3297
3298     ;; incorrect
3299     (use-modules (srfi srfi-19))
3300     (define (date) (date->string (current-date)))
3301     (define-syntax %date (identifier-syntax (date)))
3302     (define *compilation-date* %date)
3303
3304   It works at a REPL because the expressions are evaluated one-by-one,
3305in order, but if placed in a file, the expressions are expanded
3306one-by-one, but not evaluated until the compiled file is loaded.
3307
3308   The fix is to use ‘eval-when’.
3309
3310     ;; correct: using eval-when
3311     (use-modules (srfi srfi-19))
3312     (eval-when (expand load eval)
3313       (define (date) (date->string (current-date))))
3314     (define-syntax %date (identifier-syntax (date)))
3315     (define *compilation-date* %date)
3316
3317 -- Syntax: eval-when conditions exp...
3318     Evaluate EXP... under the given CONDITIONS.  Valid conditions
3319     include:
3320
3321     ‘expand’
3322          Evaluate during macro expansion, whether compiling or not.
3323
3324     ‘load’
3325          Evaluate during the evaluation phase of compiled code, e.g.
3326          when loading a compiled module or running compiled code at the
3327          REPL.
3328
3329     ‘eval’
3330          Evaluate during the evaluation phase of non-compiled code.
3331
3332     ‘compile’
3333          Evaluate during macro expansion, but only when compiling.
3334
3335     In other words, when using the primitive evaluator, ‘eval-when’
3336     expressions with ‘expand’ are run during macro expansion, and those
3337     with ‘eval’ are run during the evaluation phase.
3338
3339     When using the compiler, ‘eval-when’ expressions with either
3340     ‘expand’ or ‘compile’ are run during macro expansion, and those
3341     with ‘load’ are run during the evaluation phase.
3342
3343     When in doubt, use the three conditions ‘(expand load eval)’, as in
3344     the example above.  Other uses of ‘eval-when’ may void your
3345     warranty or poison your cat.
3346
3347
3348File: guile.info,  Node: Macro Expansion,  Next: Hygiene and the Top-Level,  Prev: Eval When,  Up: Macros
3349
33506.8.9 Macro Expansion
3351---------------------
3352
3353Usually, macros are expanded on behalf of the user as needed.  Macro
3354expansion is an integral part of ‘eval’ and ‘compile’.  Users can also
3355expand macros at the REPL prompt via the ‘expand’ REPL command; *Note
3356Compile Commands::.
3357
3358   Macros can also be expanded programmatically, via ‘macroexpand’, but
3359the details get a bit hairy for two reasons.
3360
3361   The first complication is that the result of macro-expansion isn’t
3362Scheme: it’s Tree-IL, Guile’s high-level intermediate language.  *Note
3363Tree-IL::.  As “hygienic macros” can produce identifiers that are
3364distinct but have the same name, the output format needs to be able to
3365represent distinctions between variable identities and names.  Again,
3366*Note Tree-IL::, for all the details.  The easiest thing is to just run
3367‘tree-il->scheme’ on the result of macro-expansion:
3368
3369     (macroexpand '(+ 1 2))
33703371     #<tree-il (call (toplevel +) (const 1) (const 2))>
3372
3373     (use-modules (language tree-il))
3374     (tree-il->scheme (macroexpand '(+ 1 2)))
33753376     (+ 1 2)
3377
3378   The second complication involves ‘eval-when’.  As an example, what
3379would it mean to macro-expand the definition of a macro?
3380
3381     (macroexpand '(define-syntax qux (identifier-syntax 'bar)))
33823383     ?
3384
3385   The answer is that it depends who is macro-expanding, and why.  Do
3386you define the macro in the current environment?  Residualize a macro
3387definition?  Both?  Neither?  The default is to expand in “eval” mode,
3388which means an ‘eval-when’ clauses will only proceed when ‘eval’ (or
3389‘expand’) is in its condition set.  Top-level macros will be ‘eval’’d in
3390the top-level environment.
3391
3392   In this way ‘(macroexpand FOO)’ is equivalent to ‘(macroexpand FOO 'e
3393'(eval))’.  The second argument is the mode (‘'e’ for “eval”) and the
3394third is the eval-syntax-expanders-when parameter (only ‘eval’ in this
3395default setting).
3396
3397   But if you are compiling the macro definition, probably you want to
3398reify the macro definition itself.  In that case you pass ‘'c’ as the
3399second argument to ‘macroexpand’.  But probably you want the macro
3400definition to be present at compile time as well, so you pass ‘'(compile
3401load eval)’ as the ESEW parameter.  In fact ‘(compile FOO #:to
3402'tree-il)’ is entirely equivalent to ‘(macroexpand FOO 'c '(compile load
3403eval))’; *Note The Scheme Compiler::.
3404
3405   It’s a terrible interface; we know.  The macroexpander is somewhat
3406tricksy regarding modes, so unless you are building a macro-expanding
3407tool, we suggest to avoid invoking it directly.
3408
3409
3410File: guile.info,  Node: Hygiene and the Top-Level,  Next: Internal Macros,  Prev: Macro Expansion,  Up: Macros
3411
34126.8.10 Hygiene and the Top-Level
3413--------------------------------
3414
3415Consider the following macro.
3416
3417     (define-syntax-rule (defconst name val)
3418       (begin
3419         (define t val)
3420         (define-syntax-rule (name) t)))
3421
3422   If we use it to make a couple of bindings:
3423
3424     (defconst foo 42)
3425     (defconst bar 37)
3426
3427   The expansion would look something like this:
3428
3429     (begin
3430       (define t 42)
3431       (define-syntax-rule (foo) t))
3432     (begin
3433       (define t 37)
3434       (define-syntax-rule (bar) t))
3435
3436   As the two ‘t’ bindings were introduced by the macro, they should be
3437introduced hygienically – and indeed they are, inside a lexical contour
3438(a ‘let’ or some other lexical scope).  The ‘t’ reference in ‘foo’ is
3439distinct to the reference in ‘bar’.
3440
3441   At the top-level things are more complicated.  Before Guile 2.2, a
3442use of ‘defconst’ at the top-level would not introduce a fresh binding
3443for ‘t’.  This was consistent with a weaselly interpretation of the
3444Scheme standard, in which all possible bindings may be assumed to exist,
3445at the top-level, and in which we merely take advantage of toplevel
3446‘define’ of an existing binding being equivalent to ‘set!’.  But it’s
3447not a good reason.
3448
3449   The solution is to create fresh names for all bindings introduced by
3450macros – not just bindings in lexical contours, but also bindings
3451introduced at the top-level.
3452
3453   However, the obvious strategy of just giving random names to
3454introduced toplevel identifiers poses a problem for separate
3455compilation.  Consider without loss of generality a ‘defconst’ of ‘foo’
3456in module ‘a’ that introduces the fresh top-level name ‘t-1’.  If we
3457then compile a module ‘b’ that uses ‘foo’, there is now a reference to
3458‘t-1’ in module ‘b’.  If module ‘a’ is then expanded again, for whatever
3459reason, for example in a simple recompilation, the introduced ‘t’ gets a
3460fresh name; say, ‘t-2’.  Now module ‘b’ has broken because module ‘a’ no
3461longer has a binding for ‘t-1’.
3462
3463   If introduced top-level identifiers “escape” a module, in whatever
3464way, they then form part of the binary interface (ABI) of a module.  It
3465is unacceptable from an engineering point of view to allow the ABI to
3466change randomly.  (It also poses practical problems in meeting the
3467recompilation conditions of the Lesser GPL license, for such modules.)
3468For this reason many people prefer to never use identifier-introducing
3469macros at the top-level, instead making those macros receive the names
3470for their introduced identifiers as part of their arguments, or to
3471construct them programmatically and use ‘datum->syntax’.  But this
3472approach requires omniscience as to the implementation of all macros one
3473might use, and also limits the expressive power of Scheme macros.
3474
3475   There is no perfect solution to this issue.  Guile does a terrible
3476thing here.  When it goes to introduce a top-level identifier, Guile
3477gives the identifier a pseudo-fresh name: a name that depends on the
3478hash of the source expression in which the name occurs.  The result in
3479this case is that the introduced definitions expand as:
3480
3481     (begin
3482       (define t-1dc5e42de7c1050c 42)
3483       (define-syntax-rule (foo) t-1dc5e42de7c1050c))
3484     (begin
3485       (define t-10cb8ce9fdddd6e9 37)
3486       (define-syntax-rule (bar) t-10cb8ce9fdddd6e9))
3487
3488   However, note that as the hash depends solely on the expression
3489introducing the definition, we also have:
3490
3491     (defconst baz 42)
3492     ⇒ (begin
3493         (define t-1dc5e42de7c1050c 42)
3494         (define-syntax-rule (baz) t-1dc5e42de7c1050c))
3495
3496   Note that the introduced binding has the same name!  This is because
3497the source expression, ‘(define t 42)’, was the same.  Probably you will
3498never see an error in this area, but it is important to understand the
3499components of the interface of a module, and that interface may include
3500macro-introduced identifiers.
3501
3502
3503File: guile.info,  Node: Internal Macros,  Prev: Hygiene and the Top-Level,  Up: Macros
3504
35056.8.11 Internal Macros
3506----------------------
3507
3508 -- Scheme Procedure: make-syntax-transformer name type binding
3509     Construct a syntax transformer object.  This is part of Guile’s
3510     low-level support for syntax-case.
3511
3512 -- Scheme Procedure: macro? obj
3513 -- C Function: scm_macro_p (obj)
3514     Return ‘#t’ if OBJ is a syntax transformer, or ‘#f’ otherwise.
3515
3516     Note that it’s a bit difficult to actually get a macro as a
3517     first-class object; simply naming it (like ‘case’) will produce a
3518     syntax error.  But it is possible to get these objects using
3519     ‘module-ref’:
3520
3521          (macro? (module-ref (current-module) 'case))
3522          ⇒ #t
3523
3524 -- Scheme Procedure: macro-type m
3525 -- C Function: scm_macro_type (m)
3526     Return the TYPE that was given when M was constructed, via
3527     ‘make-syntax-transformer’.
3528
3529 -- Scheme Procedure: macro-name m
3530 -- C Function: scm_macro_name (m)
3531     Return the name of the macro M.
3532
3533 -- Scheme Procedure: macro-binding m
3534 -- C Function: scm_macro_binding (m)
3535     Return the binding of the macro M.
3536
3537 -- Scheme Procedure: macro-transformer m
3538 -- C Function: scm_macro_transformer (m)
3539     Return the transformer of the macro M.  This will return a
3540     procedure, for which one may ask the docstring.  That’s the whole
3541     reason this section is documented.  Actually a part of the result
3542     of ‘macro-binding’.
3543
3544
3545File: guile.info,  Node: Utility Functions,  Next: Binding Constructs,  Prev: Macros,  Up: API Reference
3546
35476.9 General Utility Functions
3548=============================
3549
3550This chapter contains information about procedures which are not cleanly
3551tied to a specific data type.  Because of their wide range of
3552applications, they are collected in a “utility” chapter.
3553
3554* Menu:
3555
3556* Equality::                    When are two values ‘the same’?
3557* Object Properties::           A modern interface to object properties.
3558* Sorting::                     Sort utility procedures.
3559* Copying::                     Copying deep structures.
3560* General Conversion::          Converting objects to strings.
3561* Hooks::                       User-customizable event lists.
3562
3563
3564File: guile.info,  Node: Equality,  Next: Object Properties,  Up: Utility Functions
3565
35666.9.1 Equality
3567--------------
3568
3569There are three kinds of core equality predicates in Scheme, described
3570below.  The same kinds of comparisons arise in other functions, like
3571‘memq’ and friends (*note List Searching::).
3572
3573   For all three tests, objects of different types are never equal.  So
3574for instance a list and a vector are not ‘equal?’, even if their
3575contents are the same.  Exact and inexact numbers are considered
3576different types too, and are hence not equal even if their values are
3577the same.
3578
3579   ‘eq?’ tests just for the same object (essentially a pointer
3580comparison).  This is fast, and can be used when searching for a
3581particular object, or when working with symbols or keywords (which are
3582always unique objects).
3583
3584   ‘eqv?’ extends ‘eq?’ to look at the value of numbers and characters.
3585It can for instance be used somewhat like ‘=’ (*note Comparison::) but
3586without an error if one operand isn’t a number.
3587
3588   ‘equal?’ goes further, it looks (recursively) into the contents of
3589lists, vectors, etc.  This is good for instance on lists that have been
3590read or calculated in various places and are the same, just not made up
3591of the same pairs.  Such lists look the same (when printed), and
3592‘equal?’ will consider them the same.
3593
3594
3595 -- Scheme Procedure: eq? x y
3596 -- C Function: scm_eq_p (x, y)
3597     Return ‘#t’ if X and Y are the same object, except for numbers and
3598     characters.  For example,
3599
3600          (define x (vector 1 2 3))
3601          (define y (vector 1 2 3))
3602
3603          (eq? x x)  ⇒ #t
3604          (eq? x y)  ⇒ #f
3605
3606     Numbers and characters are not equal to any other object, but the
3607     problem is they’re not necessarily ‘eq?’ to themselves either.
3608     This is even so when the number comes directly from a variable,
3609
3610          (let ((n (+ 2 3)))
3611            (eq? n n))       ⇒ *unspecified*
3612
3613     Generally ‘eqv?’ below should be used when comparing numbers or
3614     characters.  ‘=’ (*note Comparison::) or ‘char=?’ (*note
3615     Characters::) can be used too.
3616
3617     It’s worth noting that end-of-list ‘()’, ‘#t’, ‘#f’, a symbol of a
3618     given name, and a keyword of a given name, are unique objects.
3619     There’s just one of each, so for instance no matter how ‘()’ arises
3620     in a program, it’s the same object and can be compared with ‘eq?’,
3621
3622          (define x (cdr '(123)))
3623          (define y (cdr '(456)))
3624          (eq? x y) ⇒ #t
3625
3626          (define x (string->symbol "foo"))
3627          (eq? x 'foo) ⇒ #t
3628
3629 -- C Function: int scm_is_eq (SCM x, SCM y)
3630     Return ‘1’ when X and Y are equal in the sense of ‘eq?’, otherwise
3631     return ‘0’.
3632
3633     The ‘==’ operator should not be used on ‘SCM’ values, an ‘SCM’ is a
3634     C type which cannot necessarily be compared using ‘==’ (*note The
3635     SCM Type::).
3636
3637
3638 -- Scheme Procedure: eqv? x y
3639 -- C Function: scm_eqv_p (x, y)
3640     Return ‘#t’ if X and Y are the same object, or for characters and
3641     numbers the same value.
3642
3643     On objects except characters and numbers, ‘eqv?’ is the same as
3644     ‘eq?’ above, it’s true if X and Y are the same object.
3645
3646     If X and Y are numbers or characters, ‘eqv?’ compares their type
3647     and value.  An exact number is not ‘eqv?’ to an inexact number
3648     (even if their value is the same).
3649
3650          (eqv? 3 (+ 1 2)) ⇒ #t
3651          (eqv? 1 1.0)     ⇒ #f
3652
3653
3654 -- Scheme Procedure: equal? x y
3655 -- C Function: scm_equal_p (x, y)
3656     Return ‘#t’ if X and Y are the same type, and their contents or
3657     value are equal.
3658
3659     For a pair, string, vector, array or structure, ‘equal?’ compares
3660     the contents, and does so using the same ‘equal?’ recursively, so a
3661     deep structure can be traversed.
3662
3663          (equal? (list 1 2 3) (list 1 2 3))   ⇒ #t
3664          (equal? (list 1 2 3) (vector 1 2 3)) ⇒ #f
3665
3666     For other objects, ‘equal?’ compares as per ‘eqv?’ above, which
3667     means characters and numbers are compared by type and value (and
3668     like ‘eqv?’, exact and inexact numbers are not ‘equal?’, even if
3669     their value is the same).
3670
3671          (equal? 3 (+ 1 2)) ⇒ #t
3672          (equal? 1 1.0)     ⇒ #f
3673
3674     Hash tables are currently only compared as per ‘eq?’, so two
3675     different tables are not ‘equal?’, even if their contents are the
3676     same.
3677
3678     ‘equal?’ does not support circular data structures, it may go into
3679     an infinite loop if asked to compare two circular lists or similar.
3680
3681     GOOPS object types (*note GOOPS::), including foreign object types
3682     (*note Defining New Foreign Object Types::), can have an ‘equal?’
3683     implementation specialized on two values of the same type.  If
3684     ‘equal?’ is called on two GOOPS objects of the same type, ‘equal?’
3685     will dispatch out to a generic function.  This lets an application
3686     traverse the contents or control what is considered ‘equal?’ for
3687     two objects of such a type.  If there’s no such handler, the
3688     default is to just compare as per ‘eq?’.
3689
3690
3691File: guile.info,  Node: Object Properties,  Next: Sorting,  Prev: Equality,  Up: Utility Functions
3692
36936.9.2 Object Properties
3694-----------------------
3695
3696It’s often useful to associate a piece of additional information with a
3697Scheme object even though that object does not have a dedicated slot
3698available in which the additional information could be stored.  Object
3699properties allow you to do just that.
3700
3701   Guile’s representation of an object property is a
3702procedure-with-setter (*note Procedures with Setters::) that can be used
3703with the generalized form of ‘set!’ (REFFIXME) to set and retrieve that
3704property for any Scheme object.  So, setting a property looks like this:
3705
3706     (set! (my-property obj1) value-for-obj1)
3707     (set! (my-property obj2) value-for-obj2)
3708
3709And retrieving values of the same property looks like this:
3710
3711     (my-property obj1)
37123713     value-for-obj1
3714
3715     (my-property obj2)
37163717     value-for-obj2
3718
3719   To create an object property in the first place, use the
3720‘make-object-property’ procedure:
3721
3722     (define my-property (make-object-property))
3723
3724 -- Scheme Procedure: make-object-property
3725     Create and return an object property.  An object property is a
3726     procedure-with-setter that can be called in two ways.  ‘(set!
3727     (PROPERTY OBJ) VAL)’ sets OBJ’s PROPERTY to VAL.  ‘(PROPERTY OBJ)’
3728     returns the current setting of OBJ’s PROPERTY.
3729
3730   A single object property created by ‘make-object-property’ can
3731associate distinct property values with all Scheme values that are
3732distinguishable by ‘eq?’ (ruling out numeric values).
3733
3734   Internally, object properties are implemented using a weak key hash
3735table.  This means that, as long as a Scheme value with property values
3736is protected from garbage collection, its property values are also
3737protected.  When the Scheme value is collected, its entry in the
3738property table is removed and so the (ex-) property values are no longer
3739protected by the table.
3740
3741   Guile also implements a more traditional Lispy interface to
3742properties, in which each object has an list of key-value pairs
3743associated with it.  Properties in that list are keyed by symbols.  This
3744is a legacy interface; you should use weak hash tables or object
3745properties instead.
3746
3747 -- Scheme Procedure: object-properties obj
3748 -- C Function: scm_object_properties (obj)
3749     Return OBJ’s property list.
3750
3751 -- Scheme Procedure: set-object-properties! obj alist
3752 -- C Function: scm_set_object_properties_x (obj, alist)
3753     Set OBJ’s property list to ALIST.
3754
3755 -- Scheme Procedure: object-property obj key
3756 -- C Function: scm_object_property (obj, key)
3757     Return the property of OBJ with name KEY.
3758
3759 -- Scheme Procedure: set-object-property! obj key value
3760 -- C Function: scm_set_object_property_x (obj, key, value)
3761     In OBJ’s property list, set the property named KEY to VALUE.
3762
3763
3764File: guile.info,  Node: Sorting,  Next: Copying,  Prev: Object Properties,  Up: Utility Functions
3765
37666.9.3 Sorting
3767-------------
3768
3769Sorting is very important in computer programs.  Therefore, Guile comes
3770with several sorting procedures built-in.  As always, procedures with
3771names ending in ‘!’ are side-effecting, that means that they may modify
3772their parameters in order to produce their results.
3773
3774   The first group of procedures can be used to merge two lists (which
3775must be already sorted on their own) and produce sorted lists containing
3776all elements of the input lists.
3777
3778 -- Scheme Procedure: merge alist blist less
3779 -- C Function: scm_merge (alist, blist, less)
3780     Merge two already sorted lists into one.  Given two lists ALIST and
3781     BLIST, such that ‘(sorted? alist less?)’ and ‘(sorted? blist
3782     less?)’, return a new list in which the elements of ALIST and BLIST
3783     have been stably interleaved so that ‘(sorted? (merge alist blist
3784     less?) less?)’.  Note: this does _not_ accept vectors.
3785
3786 -- Scheme Procedure: merge! alist blist less
3787 -- C Function: scm_merge_x (alist, blist, less)
3788     Takes two lists ALIST and BLIST such that ‘(sorted? alist less?)’
3789     and ‘(sorted? blist less?)’ and returns a new list in which the
3790     elements of ALIST and BLIST have been stably interleaved so that
3791     ‘(sorted? (merge alist blist less?) less?)’.  This is the
3792     destructive variant of ‘merge’ Note: this does _not_ accept
3793     vectors.
3794
3795   The following procedures can operate on sequences which are either
3796vectors or list.  According to the given arguments, they return sorted
3797vectors or lists, respectively.  The first of the following procedures
3798determines whether a sequence is already sorted, the other sort a given
3799sequence.  The variants with names starting with ‘stable-’ are special
3800in that they maintain a special property of the input sequences: If two
3801or more elements are the same according to the comparison predicate,
3802they are left in the same order as they appeared in the input.
3803
3804 -- Scheme Procedure: sorted? items less
3805 -- C Function: scm_sorted_p (items, less)
3806     Return ‘#t’ if ITEMS is a list or vector such that, for each
3807     element X and the next element Y of ITEMS, ‘(LESS Y X)’ returns
3808     ‘#f’.  Otherwise return ‘#f’.
3809
3810 -- Scheme Procedure: sort items less
3811 -- C Function: scm_sort (items, less)
3812     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
3813     used for comparing the sequence elements.  This is not a stable
3814     sort.
3815
3816 -- Scheme Procedure: sort! items less
3817 -- C Function: scm_sort_x (items, less)
3818     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
3819     used for comparing the sequence elements.  The sorting is
3820     destructive, that means that the input sequence is modified to
3821     produce the sorted result.  This is not a stable sort.
3822
3823 -- Scheme Procedure: stable-sort items less
3824 -- C Function: scm_stable_sort (items, less)
3825     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
3826     used for comparing the sequence elements.  This is a stable sort.
3827
3828 -- Scheme Procedure: stable-sort! items less
3829 -- C Function: scm_stable_sort_x (items, less)
3830     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
3831     used for comparing the sequence elements.  The sorting is
3832     destructive, that means that the input sequence is modified to
3833     produce the sorted result.  This is a stable sort.
3834
3835   The procedures in the last group only accept lists or vectors as
3836input, as their names indicate.
3837
3838 -- Scheme Procedure: sort-list items less
3839 -- C Function: scm_sort_list (items, less)
3840     Sort the list ITEMS, using LESS for comparing the list elements.
3841     This is a stable sort.
3842
3843 -- Scheme Procedure: sort-list! items less
3844 -- C Function: scm_sort_list_x (items, less)
3845     Sort the list ITEMS, using LESS for comparing the list elements.
3846     The sorting is destructive, that means that the input list is
3847     modified to produce the sorted result.  This is a stable sort.
3848
3849 -- Scheme Procedure: restricted-vector-sort! vec less startpos endpos
3850 -- C Function: scm_restricted_vector_sort_x (vec, less, startpos,
3851          endpos)
3852     Sort the vector VEC, using LESS for comparing the vector elements.
3853     STARTPOS (inclusively) and ENDPOS (exclusively) delimit the range
3854     of the vector which gets sorted.  The return value is not
3855     specified.
3856
3857
3858File: guile.info,  Node: Copying,  Next: General Conversion,  Prev: Sorting,  Up: Utility Functions
3859
38606.9.4 Copying Deep Structures
3861-----------------------------
3862
3863The procedures for copying lists (*note Lists::) only produce a flat
3864copy of the input list, and currently Guile does not even contain
3865procedures for copying vectors.  The ‘(ice-9 copy-tree)’ module contains
3866a ‘copy-tree’ function that can be used for this purpose, as it does not
3867only copy the spine of a list, but also copies any pairs in the cars of
3868the input lists.
3869
3870     (use-modules (ice-9 copy-tree))
3871
3872 -- Scheme Procedure: copy-tree obj
3873 -- C Function: scm_copy_tree (obj)
3874     Recursively copy the data tree that is bound to OBJ, and return the
3875     new data structure.  ‘copy-tree’ recurses down the contents of both
3876     pairs and vectors (since both cons cells and vector cells may point
3877     to arbitrary objects), and stops recursing when it hits any other
3878     object.
3879
3880
3881File: guile.info,  Node: General Conversion,  Next: Hooks,  Prev: Copying,  Up: Utility Functions
3882
38836.9.5 General String Conversion
3884-------------------------------
3885
3886When debugging Scheme programs, but also for providing a human-friendly
3887interface, a procedure for converting any Scheme object into string
3888format is very useful.  Conversion from/to strings can of course be done
3889with specialized procedures when the data type of the object to convert
3890is known, but with this procedure, it is often more comfortable.
3891
3892   ‘object->string’ converts an object by using a print procedure for
3893writing to a string port, and then returning the resulting string.
3894Converting an object back from the string is only possible if the object
3895type has a read syntax and the read syntax is preserved by the printing
3896procedure.
3897
3898 -- Scheme Procedure: object->string obj [printer]
3899 -- C Function: scm_object_to_string (obj, printer)
3900     Return a Scheme string obtained by printing OBJ.  Printing function
3901     can be specified by the optional second argument PRINTER (default:
3902     ‘write’).
3903
3904
3905File: guile.info,  Node: Hooks,  Prev: General Conversion,  Up: Utility Functions
3906
39076.9.6 Hooks
3908-----------
3909
3910A hook is a list of procedures to be called at well defined points in
3911time.  Typically, an application provides a hook H and promises its
3912users that it will call all of the procedures in H at a defined point in
3913the application’s processing.  By adding its own procedure to H, an
3914application user can tap into or even influence the progress of the
3915application.
3916
3917   Guile itself provides several such hooks for debugging and
3918customization purposes: these are listed in a subsection below.
3919
3920   When an application first creates a hook, it needs to know how many
3921arguments will be passed to the hook’s procedures when the hook is run.
3922The chosen number of arguments (which may be none) is declared when the
3923hook is created, and all the procedures that are added to that hook must
3924be capable of accepting that number of arguments.
3925
3926   A hook is created using ‘make-hook’.  A procedure can be added to or
3927removed from a hook using ‘add-hook!’ or ‘remove-hook!’, and all of a
3928hook’s procedures can be removed together using ‘reset-hook!’.  When an
3929application wants to run a hook, it does so using ‘run-hook’.
3930
3931* Menu:
3932
3933* Hook Example::                Hook usage by example.
3934* Hook Reference::              Reference of all hook procedures.
3935* C Hooks::                     Hooks for use from C code.
3936* GC Hooks::                    Garbage collection hooks.
3937* REPL Hooks::                  Hooks into the Guile REPL.
3938
3939
3940File: guile.info,  Node: Hook Example,  Next: Hook Reference,  Up: Hooks
3941
39426.9.6.1 Hook Usage by Example
3943.............................
3944
3945Hook usage is shown by some examples in this section.  First, we will
3946define a hook of arity 2 — that is, the procedures stored in the hook
3947will have to accept two arguments.
3948
3949     (define hook (make-hook 2))
3950     hook
3951     ⇒ #<hook 2 40286c90>
3952
3953   Now we are ready to add some procedures to the newly created hook
3954with ‘add-hook!’.  In the following example, two procedures are added,
3955which print different messages and do different things with their
3956arguments.
3957
3958     (add-hook! hook (lambda (x y)
3959                         (display "Foo: ")
3960                         (display (+ x y))
3961                         (newline)))
3962     (add-hook! hook (lambda (x y)
3963                         (display "Bar: ")
3964                         (display (* x y))
3965                         (newline)))
3966
3967   Once the procedures have been added, we can invoke the hook using
3968‘run-hook’.
3969
3970     (run-hook hook 3 4)
3971     ⊣ Bar: 12
3972     ⊣ Foo: 7
3973
3974   Note that the procedures are called in the reverse of the order with
3975which they were added.  This is because the default behaviour of
3976‘add-hook!’ is to add its procedure to the _front_ of the hook’s
3977procedure list.  You can force ‘add-hook!’ to add its procedure to the
3978_end_ of the list instead by providing a third ‘#t’ argument on the
3979second call to ‘add-hook!’.
3980
3981     (add-hook! hook (lambda (x y)
3982                         (display "Foo: ")
3983                         (display (+ x y))
3984                         (newline)))
3985     (add-hook! hook (lambda (x y)
3986                         (display "Bar: ")
3987                         (display (* x y))
3988                         (newline))
3989                         #t)             ; <- Change here!
3990
3991     (run-hook hook 3 4)
3992     ⊣ Foo: 7
3993     ⊣ Bar: 12
3994
3995
3996File: guile.info,  Node: Hook Reference,  Next: C Hooks,  Prev: Hook Example,  Up: Hooks
3997
39986.9.6.2 Hook Reference
3999......................
4000
4001When you create a hook with ‘make-hook’, you must specify the arity of
4002the procedures which can be added to the hook.  If the arity is not
4003given explicitly as an argument to ‘make-hook’, it defaults to zero.
4004All procedures of a given hook must have the same arity, and when the
4005procedures are invoked using ‘run-hook’, the number of arguments passed
4006must match the arity specified at hook creation time.
4007
4008   The order in which procedures are added to a hook matters.  If the
4009third parameter to ‘add-hook!’ is omitted or is equal to ‘#f’, the
4010procedure is added in front of the procedures which might already be on
4011that hook, otherwise the procedure is added at the end.  The procedures
4012are always called from the front to the end of the list when they are
4013invoked via ‘run-hook’.
4014
4015   The ordering of the list of procedures returned by ‘hook->list’
4016matches the order in which those procedures would be called if the hook
4017was run using ‘run-hook’.
4018
4019   Note that the C functions in the following entries are for handling
4020“Scheme-level” hooks in C. There are also “C-level” hooks which have
4021their own interface (*note C Hooks::).
4022
4023 -- Scheme Procedure: make-hook [n_args]
4024 -- C Function: scm_make_hook (n_args)
4025     Create a hook for storing procedure of arity N_ARGS.  N_ARGS
4026     defaults to zero.  The returned value is a hook object to be used
4027     with the other hook procedures.
4028
4029 -- Scheme Procedure: hook? x
4030 -- C Function: scm_hook_p (x)
4031     Return ‘#t’ if X is a hook, ‘#f’ otherwise.
4032
4033 -- Scheme Procedure: hook-empty? hook
4034 -- C Function: scm_hook_empty_p (hook)
4035     Return ‘#t’ if HOOK is an empty hook, ‘#f’ otherwise.
4036
4037 -- Scheme Procedure: add-hook! hook proc [append_p]
4038 -- C Function: scm_add_hook_x (hook, proc, append_p)
4039     Add the procedure PROC to the hook HOOK.  The procedure is added to
4040     the end if APPEND_P is true, otherwise it is added to the front.
4041     The return value of this procedure is not specified.
4042
4043 -- Scheme Procedure: remove-hook! hook proc
4044 -- C Function: scm_remove_hook_x (hook, proc)
4045     Remove the procedure PROC from the hook HOOK.  The return value of
4046     this procedure is not specified.
4047
4048 -- Scheme Procedure: reset-hook! hook
4049 -- C Function: scm_reset_hook_x (hook)
4050     Remove all procedures from the hook HOOK.  The return value of this
4051     procedure is not specified.
4052
4053 -- Scheme Procedure: hook->list hook
4054 -- C Function: scm_hook_to_list (hook)
4055     Convert the procedure list of HOOK to a list.
4056
4057 -- Scheme Procedure: run-hook hook arg ...
4058 -- C Function: scm_run_hook (hook, args)
4059     Apply all procedures from the hook HOOK to the arguments ARG ....
4060     The order of the procedure application is first to last.  The
4061     return value of this procedure is not specified.
4062
4063   If, in C code, you are certain that you have a hook object and well
4064formed argument list for that hook, you can also use ‘scm_c_run_hook’,
4065which is identical to ‘scm_run_hook’ but does no type checking.
4066
4067 -- C Function: void scm_c_run_hook (SCM hook, SCM args)
4068     The same as ‘scm_run_hook’ but without any type checking to confirm
4069     that HOOK is actually a hook object and that ARGS is a well-formed
4070     list matching the arity of the hook.
4071
4072   For C code, ‘SCM_HOOKP’ is a faster alternative to ‘scm_hook_p’:
4073
4074 -- C Macro: int SCM_HOOKP (x)
4075     Return 1 if X is a Scheme-level hook, 0 otherwise.
4076
4077
4078File: guile.info,  Node: C Hooks,  Next: GC Hooks,  Prev: Hook Reference,  Up: Hooks
4079
40806.9.6.3 Hooks For C Code.
4081.........................
4082
4083The hooks already described are intended to be populated by Scheme-level
4084procedures.  In addition to this, the Guile library provides an
4085independent set of interfaces for the creation and manipulation of hooks
4086that are designed to be populated by functions implemented in C.
4087
4088   The original motivation here was to provide a kind of hook that could
4089safely be invoked at various points during garbage collection.
4090Scheme-level hooks are unsuitable for this purpose as running them could
4091itself require memory allocation, which would then invoke garbage
4092collection recursively ... However, it is also the case that these hooks
4093are easier to work with than the Scheme-level ones if you only want to
4094register C functions with them.  So if that is mainly what your code
4095needs to do, you may prefer to use this interface.
4096
4097   To create a C hook, you should allocate storage for a structure of
4098type ‘scm_t_c_hook’ and then initialize it using ‘scm_c_hook_init’.
4099
4100 -- C Type: scm_t_c_hook
4101     Data type for a C hook.  The internals of this type should be
4102     treated as opaque.
4103
4104 -- C Enum: scm_t_c_hook_type
4105     Enumeration of possible hook types, which are:
4106
4107     ‘SCM_C_HOOK_NORMAL’
4108          Type of hook for which all the registered functions will
4109          always be called.
4110     ‘SCM_C_HOOK_OR’
4111          Type of hook for which the sequence of registered functions
4112          will be called only until one of them returns C true (a
4113          non-NULL pointer).
4114     ‘SCM_C_HOOK_AND’
4115          Type of hook for which the sequence of registered functions
4116          will be called only until one of them returns C false (a NULL
4117          pointer).
4118
4119 -- C Function: void scm_c_hook_init (scm_t_c_hook *hook, void
4120          *hook_data, scm_t_c_hook_type type)
4121     Initialize the C hook at memory pointed to by HOOK.  TYPE should be
4122     one of the values of the ‘scm_t_c_hook_type’ enumeration, and
4123     controls how the hook functions will be called.  HOOK_DATA is a
4124     closure parameter that will be passed to all registered hook
4125     functions when they are called.
4126
4127   To add or remove a C function from a C hook, use ‘scm_c_hook_add’ or
4128‘scm_c_hook_remove’.  A hook function must expect three ‘void *’
4129parameters which are, respectively:
4130
4131HOOK_DATA
4132     The hook closure data that was specified at the time the hook was
4133     initialized by ‘scm_c_hook_init’.
4134
4135FUNC_DATA
4136     The function closure data that was specified at the time that that
4137     function was registered with the hook by ‘scm_c_hook_add’.
4138
4139DATA
4140     The call closure data specified by the ‘scm_c_hook_run’ call that
4141     runs the hook.
4142
4143 -- C Type: scm_t_c_hook_function
4144     Function type for a C hook function: takes three ‘void *’
4145     parameters and returns a ‘void *’ result.
4146
4147 -- C Function: void scm_c_hook_add (scm_t_c_hook *hook,
4148          scm_t_c_hook_function func, void *func_data, int appendp)
4149     Add function FUNC, with function closure data FUNC_DATA, to the C
4150     hook HOOK.  The new function is appended to the hook’s list of
4151     functions if APPENDP is non-zero, otherwise prepended.
4152
4153 -- C Function: void scm_c_hook_remove (scm_t_c_hook *hook,
4154          scm_t_c_hook_function func, void *func_data)
4155     Remove function FUNC, with function closure data FUNC_DATA, from
4156     the C hook HOOK.  ‘scm_c_hook_remove’ checks both FUNC and
4157     FUNC_DATA so as to allow for the same FUNC being registered
4158     multiple times with different closure data.
4159
4160   Finally, to invoke a C hook, call the ‘scm_c_hook_run’ function
4161specifying the hook and the call closure data for this run:
4162
4163 -- C Function: void * scm_c_hook_run (scm_t_c_hook *hook, void *data)
4164     Run the C hook HOOK will call closure data DATA.  Subject to the
4165     variations for hook types ‘SCM_C_HOOK_OR’ and ‘SCM_C_HOOK_AND’,
4166     ‘scm_c_hook_run’ calls HOOK’s registered functions in turn, passing
4167     them the hook’s closure data, each function’s closure data, and the
4168     call closure data.
4169
4170     ‘scm_c_hook_run’’s return value is the return value of the last
4171     function to be called.
4172
4173
4174File: guile.info,  Node: GC Hooks,  Next: REPL Hooks,  Prev: C Hooks,  Up: Hooks
4175
41766.9.6.4 Hooks for Garbage Collection
4177....................................
4178
4179Whenever Guile performs a garbage collection, it calls the following
4180hooks in the order shown.
4181
4182 -- C Hook: scm_before_gc_c_hook
4183     C hook called at the very start of a garbage collection, after
4184     setting ‘scm_gc_running_p’ to 1, but before entering the GC
4185     critical section.
4186
4187     If garbage collection is blocked because ‘scm_block_gc’ is
4188     non-zero, GC exits early soon after calling this hook, and no
4189     further hooks will be called.
4190
4191 -- C Hook: scm_before_mark_c_hook
4192     C hook called before beginning the mark phase of garbage
4193     collection, after the GC thread has entered a critical section.
4194
4195 -- C Hook: scm_before_sweep_c_hook
4196     C hook called before beginning the sweep phase of garbage
4197     collection.  This is the same as at the end of the mark phase,
4198     since nothing else happens between marking and sweeping.
4199
4200 -- C Hook: scm_after_sweep_c_hook
4201     C hook called after the end of the sweep phase of garbage
4202     collection, but while the GC thread is still inside its critical
4203     section.
4204
4205 -- C Hook: scm_after_gc_c_hook
4206     C hook called at the very end of a garbage collection, after the GC
4207     thread has left its critical section.
4208
4209 -- Scheme Hook: after-gc-hook
4210     Scheme hook with arity 0.  This hook is run asynchronously (*note
4211     Asyncs::) soon after the GC has completed and any other events that
4212     were deferred during garbage collection have been processed.  (Also
4213     accessible from C with the name ‘scm_after_gc_hook’.)
4214
4215   All the C hooks listed here have type ‘SCM_C_HOOK_NORMAL’, are
4216initialized with hook closure data NULL, are invoked by ‘scm_c_hook_run’
4217with call closure data NULL.
4218
4219   The Scheme hook ‘after-gc-hook’ is particularly useful in conjunction
4220with guardians (*note Guardians::).  Typically, if you are using a
4221guardian, you want to call the guardian after garbage collection to see
4222if any of the objects added to the guardian have been collected.  By
4223adding a thunk that performs this call to ‘after-gc-hook’, you can
4224ensure that your guardian is tested after every garbage collection
4225cycle.
4226
4227
4228File: guile.info,  Node: REPL Hooks,  Prev: GC Hooks,  Up: Hooks
4229
42306.9.6.5 Hooks into the Guile REPL
4231.................................
4232
4233
4234File: guile.info,  Node: Binding Constructs,  Next: Control Mechanisms,  Prev: Utility Functions,  Up: API Reference
4235
42366.10 Definitions and Variable Bindings
4237======================================
4238
4239Scheme supports the definition of variables in different contexts.
4240Variables can be defined at the top level, so that they are visible in
4241the entire program, and variables can be defined locally to procedures
4242and expressions.  This is important for modularity and data abstraction.
4243
4244* Menu:
4245
4246* Top Level::                   Top level variable definitions.
4247* Local Bindings::              Local variable bindings.
4248* Internal Definitions::        Internal definitions.
4249* Binding Reflection::          Querying variable bindings.
4250* Binding Multiple Values::     Binding multiple return values.
4251
4252
4253File: guile.info,  Node: Top Level,  Next: Local Bindings,  Up: Binding Constructs
4254
42556.10.1 Top Level Variable Definitions
4256-------------------------------------
4257
4258At the top level of a program (i.e., not nested within any other
4259expression), a definition of the form
4260
4261     (define a VALUE)
4262
4263defines a variable called ‘a’ and sets it to the value VALUE.
4264
4265   If the variable already exists in the current module, because it has
4266already been created by a previous ‘define’ expression with the same
4267name, its value is simply changed to the new VALUE.  In this case, then,
4268the above form is completely equivalent to
4269
4270     (set! a VALUE)
4271
4272This equivalence means that ‘define’ can be used interchangeably with
4273‘set!’ to change the value of variables at the top level of the REPL or
4274a Scheme source file.  It is useful during interactive development when
4275reloading a Scheme file that you have modified, because it allows the
4276‘define’ expressions in that file to work as expected both the first
4277time that the file is loaded and on subsequent occasions.
4278
4279   Note, though, that ‘define’ and ‘set!’ are not always equivalent.
4280For example, a ‘set!’ is not allowed if the named variable does not
4281already exist, and the two expressions can behave differently in the
4282case where there are imported variables visible from another module.
4283
4284 -- Scheme Syntax: define name value
4285     Create a top level variable named NAME with value VALUE.  If the
4286     named variable already exists, just change its value.  The return
4287     value of a ‘define’ expression is unspecified.
4288
4289   The C API equivalents of ‘define’ are ‘scm_define’ and
4290‘scm_c_define’, which differ from each other in whether the variable
4291name is specified as a ‘SCM’ symbol or as a null-terminated C string.
4292
4293 -- C Function: scm_define (sym, value)
4294 -- C Function: scm_c_define (const char *name, value)
4295     C equivalents of ‘define’, with variable name specified either by
4296     SYM, a symbol, or by NAME, a null-terminated C string.  Both
4297     variants return the new or preexisting variable object.
4298
4299   ‘define’ (when it occurs at top level), ‘scm_define’ and
4300‘scm_c_define’ all create or set the value of a variable in the top
4301level environment of the current module.  If there was not already a
4302variable with the specified name belonging to the current module, but a
4303similarly named variable from another module was visible through having
4304been imported, the newly created variable in the current module will
4305shadow the imported variable, such that the imported variable is no
4306longer visible.
4307
4308   Attention: Scheme definitions inside local binding constructs (*note
4309Local Bindings::) act differently (*note Internal Definitions::).
4310
4311   Many people end up in a development style of adding and changing
4312definitions at runtime, building out their program without restarting
4313it.  (You can do this using ‘reload-module’, the ‘reload’ REPL command,
4314the ‘load’ procedure, or even just pasting code into a REPL.) If you are
4315one of these people, you will find that sometimes there are some
4316variables that you _don’t_ want to redefine all the time.  For these,
4317use ‘define-once’.
4318
4319 -- Scheme Syntax: define-once name value
4320     Create a top level variable named NAME with value VALUE, but only
4321     if NAME is not already bound in the current module.
4322
4323   Old Lispers probably know ‘define-once’ under its Lisp name,
4324‘defvar’.
4325
4326
4327File: guile.info,  Node: Local Bindings,  Next: Internal Definitions,  Prev: Top Level,  Up: Binding Constructs
4328
43296.10.2 Local Variable Bindings
4330------------------------------
4331
4332As opposed to definitions at the top level, which creates bindings that
4333are visible to all code in a module, it is also possible to define
4334variables which are only visible in a well-defined part of the program.
4335Normally, this part of a program will be a procedure or a subexpression
4336of a procedure.
4337
4338   With the constructs for local binding (‘let’, ‘let*’, ‘letrec’, and
4339‘letrec*’), the Scheme language has a block structure like most other
4340programming languages since the days of ALGOL 60.  Readers familiar to
4341languages like C or Java should already be used to this concept, but the
4342family of ‘let’ expressions has a few properties which are well worth
4343knowing.
4344
4345   The most basic local binding construct is ‘let’.
4346
4347 -- syntax: let bindings body
4348     BINDINGS has the form
4349
4350          ((VARIABLE1 INIT1) ...)
4351
4352     that is zero or more two-element lists of a variable and an
4353     arbitrary expression each.  All VARIABLE names must be distinct.
4354
4355     A ‘let’ expression is evaluated as follows.
4356
4357        • All INIT expressions are evaluated.
4358
4359        • New storage is allocated for the VARIABLES.
4360
4361        • The values of the INIT expressions are stored into the
4362          variables.
4363
4364        • The expressions in BODY are evaluated in order, and the value
4365          of the last expression is returned as the value of the ‘let’
4366          expression.
4367
4368     The INIT expressions are not allowed to refer to any of the
4369     VARIABLES.
4370
4371   The other binding constructs are variations on the same theme: making
4372new values, binding them to variables, and executing a body in that new,
4373extended lexical context.
4374
4375 -- syntax: let* bindings body
4376     Similar to ‘let’, but the variable bindings are performed
4377     sequentially, that means that all INIT expression are allowed to
4378     use the variables defined on their left in the binding list.
4379
4380     A ‘let*’ expression can always be expressed with nested ‘let’
4381     expressions.
4382
4383          (let* ((a 1) (b a))
4384             b)
43854386          (let ((a 1))
4387            (let ((b a))
4388              b))
4389
4390 -- syntax: letrec bindings body
4391     Similar to ‘let’, but it is possible to refer to the VARIABLE from
4392     lambda expression created in any of the INITS.  That is, procedures
4393     created in the INIT expression can recursively refer to the defined
4394     variables.
4395
4396          (letrec ((even? (lambda (n)
4397                            (if (zero? n)
4398                                #t
4399                                (odd? (- n 1)))))
4400                   (odd? (lambda (n)
4401                            (if (zero? n)
4402                                #f
4403                                (even? (- n 1))))))
4404            (even? 88))
44054406          #t
4407
4408     Note that while the INIT expressions may refer to the new
4409     variables, they may not access their values.  For example, making
4410     the ‘even?’ function above creates a closure (*note About
4411     Closure::) referencing the ‘odd?’ variable.  But ‘odd?’ can’t be
4412     called until after execution has entered the body.
4413
4414 -- syntax: letrec* bindings body
4415     Similar to ‘letrec’, except the INIT expressions are bound to their
4416     variables in order.
4417
4418     ‘letrec*’ thus relaxes the letrec restriction, in that later INIT
4419     expressions may refer to the values of previously bound variables.
4420
4421          (letrec ((a 42)
4422                   (b (+ a 10)))  ;; Illegal access
4423            (* a b))
4424          ;; The behavior of the expression above is unspecified
4425
4426          (letrec* ((a 42)
4427                    (b (+ a 10)))
4428            (* a b))
4429          ⇒ 2184
4430
4431   There is also an alternative form of the ‘let’ form, which is used
4432for expressing iteration.  Because of the use as a looping construct,
4433this form (the “named let”) is documented in the section about iteration
4434(*note Iteration: while do.)
4435
4436
4437File: guile.info,  Node: Internal Definitions,  Next: Binding Reflection,  Prev: Local Bindings,  Up: Binding Constructs
4438
44396.10.3 Internal definitions
4440---------------------------
4441
4442A ‘define’ form which appears inside the body of a ‘lambda’, ‘let’,
4443‘let*’, ‘letrec’, ‘letrec*’ or equivalent expression is called an
4444“internal definition”.  An internal definition differs from a top level
4445definition (*note Top Level::), because the definition is only visible
4446inside the complete body of the enclosing form.  Let us examine the
4447following example.
4448
4449     (let ((frumble "froz"))
4450       (define banana (lambda () (apple 'peach)))
4451       (define apple (lambda (x) x))
4452       (banana))
44534454     peach
4455
4456   Here the enclosing form is a ‘let’, so the ‘define’s in the
4457‘let’-body are internal definitions.  Because the scope of the internal
4458definitions is the *complete* body of the ‘let’-expression, the
4459‘lambda’-expression which gets bound to the variable ‘banana’ may refer
4460to the variable ‘apple’, even though its definition appears lexically
4461_after_ the definition of ‘banana’.  This is because a sequence of
4462internal definition acts as if it were a ‘letrec*’ expression.
4463
4464     (let ()
4465       (define a 1)
4466       (define b 2)
4467       (+ a b))
4468
4469is equivalent to
4470
4471     (let ()
4472       (letrec* ((a 1) (b 2))
4473         (+ a b)))
4474
4475   Internal definitions may be mixed with non-definition expressions.
4476If an expression precedes a definition, it is treated as if it were a
4477definition of an unreferenced variable.  So this:
4478
4479     (let ()
4480       (define a 1)
4481       (foo)
4482       (define b 2)
4483       (+ a b))
4484
4485is equivalent to
4486
4487     (let ()
4488       (letrec* ((a 1) (_ (begin (foo) #f)) (b 2))
4489         (+ a b)))
4490
4491   Another noteworthy difference to top level definitions is that within
4492one group of internal definitions all variable names must be distinct.
4493Whereas on the top level a second define for a given variable acts like
4494a ‘set!’, for internal definitions, duplicate bound identifiers signals
4495an error.
4496
4497   As a historical note, it used to be that internal bindings were
4498expanded in terms of ‘letrec’, not ‘letrec*’.  This was the situation
4499for the R5RS report and before.  However with the R6RS, it was
4500recognized that sequential definition was a more intuitive expansion, as
4501in the following case:
4502
4503     (let ()
4504       (define a 1)
4505       (define b (+ a a))
4506       (+ a b))
4507
4508Guile decided to follow the R6RS in this regard, and now expands
4509internal definitions using ‘letrec*’.  Relatedly, it used to be that
4510internal definitions had to precede all expressions in the body; this
4511restriction was relaxed in Guile 3.0.
4512
4513
4514File: guile.info,  Node: Binding Reflection,  Next: Binding Multiple Values,  Prev: Internal Definitions,  Up: Binding Constructs
4515
45166.10.4 Querying variable bindings
4517---------------------------------
4518
4519Guile provides a procedure for checking whether a symbol is bound in the
4520top level environment.
4521
4522 -- Scheme Procedure: defined? sym [module]
4523 -- C Function: scm_defined_p (sym, module)
4524     Return ‘#t’ if SYM is defined in the module MODULE or the current
4525     module when MODULE is not specified; otherwise return ‘#f’.
4526
4527
4528File: guile.info,  Node: Binding Multiple Values,  Prev: Binding Reflection,  Up: Binding Constructs
4529
45306.10.5 Binding multiple return values
4531-------------------------------------
4532
4533 -- Syntax: define-values formals expression
4534     The EXPRESSION is evaluated, and the FORMALS are bound to the
4535     return values in the same way that the formals in a ‘lambda’
4536     expression are matched to the arguments in a procedure call.
4537
4538     (define-values (q r) (floor/ 10 3))
4539     (list q r) ⇒ (3 1)
4540
4541     (define-values (x . y) (values 1 2 3))
4542     x ⇒ 1
4543     y ⇒ (2 3)
4544
4545     (define-values x (values 1 2 3))
4546     x ⇒ (1 2 3)
4547
4548
4549File: guile.info,  Node: Control Mechanisms,  Next: Input and Output,  Prev: Binding Constructs,  Up: API Reference
4550
45516.11 Controlling the Flow of Program Execution
4552==============================================
4553
4554See *note Control Flow:: for a discussion of how the more general
4555control flow of Scheme affects C code.
4556
4557* Menu:
4558
4559* begin::                       Sequencing and splicing.
4560* Conditionals::                If, when, unless, case, and cond.
4561* and or::                      Conditional evaluation of a sequence.
4562* while do::                    Iteration mechanisms.
4563* Prompts::                     Composable, delimited continuations.
4564* Continuations::               Non-composable continuations.
4565* Multiple Values::             Returning and accepting multiple values.
4566* Exceptions::                  Raising and handling exceptions.
4567* Error Reporting::             Procedures for signaling errors.
4568* Dynamic Wind::                Dealing with non-local entrance/exit.
4569* Fluids and Dynamic States::   Dynamic scope building blocks.
4570* Parameters::                  A dynamic scope facility.
4571* Handling Errors::             How to handle errors in C code.
4572* Continuation Barriers::       Protection from non-local control flow.
4573
4574
4575File: guile.info,  Node: begin,  Next: Conditionals,  Up: Control Mechanisms
4576
45776.11.1 Sequencing and Splicing
4578------------------------------
4579
4580As an expression, the ‘begin’ syntax is used to evaluate a sequence of
4581sub-expressions in order.  Consider the conditional expression below:
4582
4583     (if (> x 0)
4584         (begin (display "greater") (newline)))
4585
4586   If the test is true, we want to display “greater” to the current
4587output port, then display a newline.  We use ‘begin’ to form a compound
4588expression out of this sequence of sub-expressions.
4589
4590 -- syntax: begin expr ...
4591     The expression(s) are evaluated in left-to-right order and the
4592     value of the last expression is returned as the value of the
4593     ‘begin’-expression.  This expression type is used when the
4594     expressions before the last one are evaluated for their side
4595     effects.
4596
4597   The ‘begin’ syntax has another role in definition context (*note
4598Internal Definitions::).  A ‘begin’ form in a definition context
4599“splices” its subforms into its place.  For example, consider the
4600following procedure:
4601
4602     (define (make-seal)
4603       (define-sealant seal open)
4604       (values seal open))
4605
4606   Let us assume the existence of a ‘define-sealant’ macro that expands
4607out to some definitions wrapped in a ‘begin’, like so:
4608
4609     (define (make-seal)
4610       (begin
4611         (define seal-tag
4612           (list 'seal))
4613         (define (seal x)
4614           (cons seal-tag x))
4615         (define (sealed? x)
4616           (and (pair? x) (eq? (car x) seal-tag)))
4617         (define (open x)
4618           (if (sealed? x)
4619               (cdr x)
4620               (error "Expected a sealed value:" x))))
4621       (values seal open))
4622
4623   Here, because the ‘begin’ is in definition context, its subforms are
4624“spliced” into the place of the ‘begin’.  This allows the definitions
4625created by the macro to be visible to the following expression, the
4626‘values’ form.
4627
4628   It is a fine point, but splicing and sequencing are different.  It
4629can make sense to splice zero forms, because it can make sense to have
4630zero internal definitions before the expressions in a procedure or
4631lexical binding form.  However it does not make sense to have a sequence
4632of zero expressions, because in that case it would not be clear what the
4633value of the sequence would be, because in a sequence of zero
4634expressions, there can be no last value.  Sequencing zero expressions is
4635an error.
4636
4637   It would be more elegant in some ways to eliminate splicing from the
4638Scheme language, and without macros (*note Macros::), that would be a
4639good idea.  But it is useful to be able to write macros that expand out
4640to multiple definitions, as in ‘define-sealant’ above, so Scheme abuses
4641the ‘begin’ form for these two tasks.
4642
4643
4644File: guile.info,  Node: Conditionals,  Next: and or,  Prev: begin,  Up: Control Mechanisms
4645
46466.11.2 Simple Conditional Evaluation
4647------------------------------------
4648
4649Guile provides three syntactic constructs for conditional evaluation.
4650‘if’ is the normal if-then-else expression (with an optional else
4651branch), ‘cond’ is a conditional expression with multiple branches and
4652‘case’ branches if an expression has one of a set of constant values.
4653
4654 -- syntax: if test consequent [alternate]
4655     All arguments may be arbitrary expressions.  First, TEST is
4656     evaluated.  If it returns a true value, the expression CONSEQUENT
4657     is evaluated and ALTERNATE is ignored.  If TEST evaluates to ‘#f’,
4658     ALTERNATE is evaluated instead.  The values of the evaluated branch
4659     (CONSEQUENT or ALTERNATE) are returned as the values of the ‘if’
4660     expression.
4661
4662     When ALTERNATE is omitted and the TEST evaluates to ‘#f’, the value
4663     of the expression is not specified.
4664
4665   When you go to write an ‘if’ without an alternate (a “one-armed
4666‘if’”), part of what you are expressing is that you don’t care about the
4667return value (or values) of the expression.  As such, you are more
4668interested in the _effect_ of evaluating the consequent expression.  (By
4669convention, we use the word “statement” to refer to an expression that
4670is evaluated for effect, not for value).
4671
4672   In such a case, it is considered more clear to express these
4673intentions with these special forms, ‘when’ and ‘unless’.  As an added
4674bonus, these forms accept multiple statements to evaluate, which are
4675implicitly wrapped in a ‘begin’.
4676
4677 -- Scheme Syntax: when test statement1 statement2 ...
4678 -- Scheme Syntax: unless test statement1 statement2 ...
4679     The actual definitions of these forms are in many ways their most
4680     clear documentation:
4681
4682          (define-syntax-rule (when test stmt stmt* ...)
4683            (if test (begin stmt stmt* ...)))
4684
4685          (define-syntax-rule (unless condition stmt stmt* ...)
4686            (if (not test) (begin stmt stmt* ...)))
4687
4688     That is to say, ‘when’ evaluates its consequent statements in order
4689     if TEST is true.  ‘unless’ is the opposite: it evaluates the
4690     statements if TEST is false.
4691
4692 -- syntax: cond clause1 clause2 ...
4693     Each ‘cond’-clause must look like this:
4694
4695          (TEST EXPRESSION ...)
4696
4697     where TEST and EXPRESSION are arbitrary expressions, or like this
4698
4699          (TEST => EXPRESSION)
4700
4701     where EXPRESSION must evaluate to a procedure.
4702
4703     The TESTs of the clauses are evaluated in order and as soon as one
4704     of them evaluates to a true value, the corresponding EXPRESSIONs
4705     are evaluated in order and the last value is returned as the value
4706     of the ‘cond’-expression.  For the ‘=>’ clause type, EXPRESSION is
4707     evaluated and the resulting procedure is applied to the value of
4708     TEST.  The result of this procedure application is then the result
4709     of the ‘cond’-expression.
4710
4711     One additional ‘cond’-clause is available as an extension to
4712     standard Scheme:
4713
4714          (TEST GUARD => EXPRESSION)
4715
4716     where GUARD and EXPRESSION must evaluate to procedures.  For this
4717     clause type, TEST may return multiple values, and ‘cond’ ignores
4718     its boolean state; instead, ‘cond’ evaluates GUARD and applies the
4719     resulting procedure to the value(s) of TEST, as if GUARD were the
4720     CONSUMER argument of ‘call-with-values’.  If the result of that
4721     procedure call is a true value, it evaluates EXPRESSION and applies
4722     the resulting procedure to the value(s) of TEST, in the same manner
4723     as the GUARD was called.
4724
4725     The TEST of the last CLAUSE may be the symbol ‘else’.  Then, if
4726     none of the preceding TESTs is true, the EXPRESSIONs following the
4727     ‘else’ are evaluated to produce the result of the
4728     ‘cond’-expression.
4729
4730 -- syntax: case key clause1 clause2 ...
4731     KEY may be any expression, and the CLAUSEs must have the form
4732
4733          ((DATUM1 ...) EXPR1 EXPR2 ...)
4734
4735     or
4736
4737          ((DATUM1 ...) => EXPRESSION)
4738
4739     and the last CLAUSE may have the form
4740
4741          (else EXPR1 EXPR2 ...)
4742
4743     or
4744
4745          (else => EXPRESSION)
4746
4747     All DATUMs must be distinct.  First, KEY is evaluated.  The result
4748     of this evaluation is compared against all DATUM values using
4749     ‘eqv?’.  When this comparison succeeds, the expression(s) following
4750     the DATUM are evaluated from left to right, returning the value of
4751     the last expression as the result of the ‘case’ expression.
4752
4753     If the KEY matches no DATUM and there is an ‘else’-clause, the
4754     expressions following the ‘else’ are evaluated.  If there is no
4755     such clause, the result of the expression is unspecified.
4756
4757     For the ‘=>’ clause types, EXPRESSION is evaluated and the
4758     resulting procedure is applied to the value of KEY.  The result of
4759     this procedure application is then the result of the
4760     ‘case’-expression.
4761
4762
4763File: guile.info,  Node: and or,  Next: while do,  Prev: Conditionals,  Up: Control Mechanisms
4764
47656.11.3 Conditional Evaluation of a Sequence of Expressions
4766----------------------------------------------------------
4767
4768‘and’ and ‘or’ evaluate all their arguments in order, similar to
4769‘begin’, but evaluation stops as soon as one of the expressions
4770evaluates to false or true, respectively.
4771
4772 -- syntax: and expr ...
4773     Evaluate the EXPRs from left to right and stop evaluation as soon
4774     as one expression evaluates to ‘#f’; the remaining expressions are
4775     not evaluated.  The value of the last evaluated expression is
4776     returned.  If no expression evaluates to ‘#f’, the value of the
4777     last expression is returned.
4778
4779     If used without expressions, ‘#t’ is returned.
4780
4781 -- syntax: or expr ...
4782     Evaluate the EXPRs from left to right and stop evaluation as soon
4783     as one expression evaluates to a true value (that is, a value
4784     different from ‘#f’); the remaining expressions are not evaluated.
4785     The value of the last evaluated expression is returned.  If all
4786     expressions evaluate to ‘#f’, ‘#f’ is returned.
4787
4788     If used without expressions, ‘#f’ is returned.
4789
4790
4791File: guile.info,  Node: while do,  Next: Prompts,  Prev: and or,  Up: Control Mechanisms
4792
47936.11.4 Iteration mechanisms
4794---------------------------
4795
4796Scheme has only few iteration mechanisms, mainly because iteration in
4797Scheme programs is normally expressed using recursion.  Nevertheless,
4798R5RS defines a construct for programming loops, calling ‘do’.  In
4799addition, Guile has an explicit looping syntax called ‘while’.
4800
4801 -- syntax: do ((variable init [step]) ...) (test expr ...) body ...
4802     Bind VARIABLEs and evaluate BODY until TEST is true.  The return
4803     value is the last EXPR after TEST, if given.  A simple example will
4804     illustrate the basic form,
4805
4806          (do ((i 1 (1+ i)))
4807              ((> i 4))
4808            (display i))
4809          ⊣ 1234
4810
4811     Or with two variables and a final return value,
4812
4813          (do ((i 1 (1+ i))
4814               (p 3 (* 3 p)))
4815              ((> i 4)
4816               p)
4817            (format #t "3**~s is ~s\n" i p))
48184819          3**1 is 3
4820          3**2 is 9
4821          3**3 is 27
4822          3**4 is 81
48234824          789
4825
4826     The VARIABLE bindings are established like a ‘let’, in that the
4827     expressions are all evaluated and then all bindings made.  When
4828     iterating, the optional STEP expressions are evaluated with the
4829     previous bindings in scope, then new bindings all made.
4830
4831     The TEST expression is a termination condition.  Looping stops when
4832     the TEST is true.  It’s evaluated before running the BODY each
4833     time, so if it’s true the first time then BODY is not run at all.
4834
4835     The optional EXPRs after the TEST are evaluated at the end of
4836     looping, with the final VARIABLE bindings available.  The last EXPR
4837     gives the return value, or if there are no EXPRs the return value
4838     is unspecified.
4839
4840     Each iteration establishes bindings to fresh locations for the
4841     VARIABLEs, like a new ‘let’ for each iteration.  This is done for
4842     VARIABLEs without STEP expressions too.  The following illustrates
4843     this, showing how a new ‘i’ is captured by the ‘lambda’ in each
4844     iteration (*note The Concept of Closure: About Closure.).
4845
4846          (define lst '())
4847          (do ((i 1 (1+ i)))
4848              ((> i 4))
4849            (set! lst (cons (lambda () i) lst)))
4850          (map (lambda (proc) (proc)) lst)
48514852          (4 3 2 1)
4853
4854 -- syntax: while cond body ...
4855     Run a loop executing the BODY forms while COND is true.  COND is
4856     tested at the start of each iteration, so if it’s ‘#f’ the first
4857     time then BODY is not executed at all.
4858
4859     Within ‘while’, two extra bindings are provided, they can be used
4860     from both COND and BODY.
4861
4862      -- Scheme Procedure: break break-arg ...
4863          Break out of the ‘while’ form.
4864
4865      -- Scheme Procedure: continue
4866          Abandon the current iteration, go back to the start and test
4867          COND again, etc.
4868
4869     If the loop terminates normally, by the COND evaluating to ‘#f’,
4870     then the ‘while’ expression as a whole evaluates to ‘#f’.  If it
4871     terminates by a call to ‘break’ with some number of arguments,
4872     those arguments are returned from the ‘while’ expression, as
4873     multiple values.  Otherwise if it terminates by a call to ‘break’
4874     with no arguments, then return value is ‘#t’.
4875
4876          (while #f (error "not reached")) ⇒ #f
4877          (while #t (break)) ⇒ #t
4878          (while #t (break 1 2 3)) ⇒ 1 2 3
4879
4880     Each ‘while’ form gets its own ‘break’ and ‘continue’ procedures,
4881     operating on that ‘while’.  This means when loops are nested the
4882     outer ‘break’ can be used to escape all the way out.  For example,
4883
4884          (while (test1)
4885            (let ((outer-break break))
4886              (while (test2)
4887                (if (something)
4888                  (outer-break #f))
4889                ...)))
4890
4891     Note that each ‘break’ and ‘continue’ procedure can only be used
4892     within the dynamic extent of its ‘while’.  Outside the ‘while’
4893     their behaviour is unspecified.
4894
4895   Another very common way of expressing iteration in Scheme programs is
4896the use of the so-called “named let”.
4897
4898   Named let is a variant of ‘let’ which creates a procedure and calls
4899it in one step.  Because of the newly created procedure, named let is
4900more powerful than ‘do’–it can be used for iteration, but also for
4901arbitrary recursion.
4902
4903 -- syntax: let variable bindings body
4904     For the definition of BINDINGS see the documentation about ‘let’
4905     (*note Local Bindings::).
4906
4907     Named ‘let’ works as follows:
4908
4909        • A new procedure which accepts as many arguments as are in
4910          BINDINGS is created and bound locally (using ‘let’) to
4911          VARIABLE.  The new procedure’s formal argument names are the
4912          name of the VARIABLES.
4913
4914        • The BODY expressions are inserted into the newly created
4915          procedure.
4916
4917        • The procedure is called with the INIT expressions as the
4918          formal arguments.
4919
4920     The next example implements a loop which iterates (by recursion)
4921     1000 times.
4922
4923          (let lp ((x 1000))
4924            (if (positive? x)
4925                (lp (- x 1))
4926                x))
49274928          0
4929
4930
4931File: guile.info,  Node: Prompts,  Next: Continuations,  Prev: while do,  Up: Control Mechanisms
4932
49336.11.5 Prompts
4934--------------
4935
4936Prompts are control-flow barriers between different parts of a program.
4937In the same way that a user sees a shell prompt (e.g., the Bash prompt)
4938as a barrier between the operating system and her programs, Scheme
4939prompts allow the Scheme programmer to treat parts of programs as if
4940they were running in different operating systems.
4941
4942   We use this roundabout explanation because, unless you’re a
4943functional programming junkie, you probably haven’t heard the term,
4944“delimited, composable continuation”.  That’s OK; it’s a relatively
4945recent topic, but a very useful one to know about.
4946
4947* Menu:
4948
4949* Prompt Primitives::           Call-with-prompt and abort-to-prompt.
4950* Shift and Reset::             The zoo of delimited control operators.
4951
4952
4953File: guile.info,  Node: Prompt Primitives,  Next: Shift and Reset,  Up: Prompts
4954
49556.11.5.1 Prompt Primitives
4956..........................
4957
4958Guile’s primitive delimited control operators are ‘call-with-prompt’ and
4959‘abort-to-prompt’.
4960
4961 -- Scheme Procedure: call-with-prompt tag thunk handler
4962     Set up a prompt, and call THUNK within that prompt.
4963
4964     During the dynamic extent of the call to THUNK, a prompt named TAG
4965     will be present in the dynamic context, such that if a user calls
4966     ‘abort-to-prompt’ (see below) with that tag, control rewinds back
4967     to the prompt, and the HANDLER is run.
4968
4969     HANDLER must be a procedure.  The first argument to HANDLER will be
4970     the state of the computation begun when THUNK was called, and
4971     ending with the call to ‘abort-to-prompt’.  The remaining arguments
4972     to HANDLER are those passed to ‘abort-to-prompt’.
4973
4974 -- Scheme Procedure: make-prompt-tag [stem]
4975     Make a new prompt tag.  A prompt tag is simply a unique object.
4976     Currently, a prompt tag is a fresh pair.  This may change in some
4977     future Guile version.
4978
4979 -- Scheme Procedure: default-prompt-tag
4980     Return the default prompt tag.  Having a distinguished default
4981     prompt tag allows some useful prompt and abort idioms, discussed in
4982     the next section.  Note that ‘default-prompt-tag’ is actually a
4983     parameter, and so may be dynamically rebound using ‘parameterize’.
4984     *Note Parameters::.
4985
4986 -- Scheme Procedure: abort-to-prompt tag val1 val2 ...
4987     Unwind the dynamic and control context to the nearest prompt named
4988     TAG, also passing the given values.
4989
4990   C programmers may recognize ‘call-with-prompt’ and ‘abort-to-prompt’
4991as a fancy kind of ‘setjmp’ and ‘longjmp’, respectively.  Prompts are
4992indeed quite useful as non-local escape mechanisms.  Guile’s
4993‘with-exception-handler’ and ‘raise-exception’ are implemented in terms
4994of prompts.  Prompts are more convenient than ‘longjmp’, in that one has
4995the opportunity to pass multiple values to the jump target.
4996
4997   Also unlike ‘longjmp’, the prompt handler is given the full state of
4998the process that was aborted, as the first argument to the prompt’s
4999handler.  That state is the “continuation” of the computation wrapped by
5000the prompt.  It is a “delimited continuation”, because it is not the
5001whole continuation of the program; rather, just the computation
5002initiated by the call to ‘call-with-prompt’.
5003
5004   The continuation is a procedure, and may be reinstated simply by
5005invoking it, with any number of values.  Here’s where things get
5006interesting, and complicated as well.  Besides being described as
5007delimited, continuations reified by prompts are also “composable”,
5008because invoking a prompt-saved continuation composes that continuation
5009with the current one.
5010
5011   Imagine you have saved a continuation via call-with-prompt:
5012
5013     (define cont
5014       (call-with-prompt
5015        ;; tag
5016        'foo
5017        ;; thunk
5018        (lambda ()
5019          (+ 34 (abort-to-prompt 'foo)))
5020        ;; handler
5021        (lambda (k) k)))
5022
5023   The resulting continuation is the addition of 34.  It’s as if you had
5024written:
5025
5026     (define cont
5027       (lambda (x)
5028         (+ 34 x)))
5029
5030   So, if we call ‘cont’ with one numeric value, we get that number,
5031incremented by 34:
5032
5033     (cont 8)
5034     ⇒ 42
5035     (* 2 (cont 8))
5036     ⇒ 84
5037
5038   The last example illustrates what we mean when we say, "composes with
5039the current continuation".  We mean that there is a current continuation
5040– some remaining things to compute, like ‘(lambda (x) (* x 2))’ – and
5041that calling the saved continuation doesn’t wipe out the current
5042continuation, it composes the saved continuation with the current one.
5043
5044   We’re belaboring the point here because traditional Scheme
5045continuations, as discussed in the next section, aren’t composable, and
5046are actually less expressive than continuations captured by prompts.
5047But there’s a place for them both.
5048
5049   Before moving on, we should mention that if the handler of a prompt
5050is a ‘lambda’ expression, and the first argument isn’t referenced, an
5051abort to that prompt will not cause a continuation to be reified.  This
5052can be an important efficiency consideration to keep in mind.
5053
5054   One example where this optimization matters is “escape
5055continuations”.  Escape continuations are delimited continuations whose
5056only use is to make a non-local exit—i.e., to escape from the current
5057continuation.  A common use of escape continuations is when handling an
5058exception (*note Exceptions::).
5059
5060   The constructs below are syntactic sugar atop prompts to simplify the
5061use of escape continuations.
5062
5063 -- Scheme Procedure: call-with-escape-continuation proc
5064 -- Scheme Procedure: call/ec proc
5065     Call PROC with an escape continuation.
5066
5067     In the example below, the RETURN continuation is used to escape the
5068     continuation of the call to ‘fold’.
5069
5070          (use-modules (ice-9 control)
5071                       (srfi srfi-1))
5072
5073          (define (prefix x lst)
5074            ;; Return all the elements before the first occurrence
5075            ;; of X in LST.
5076            (call/ec
5077              (lambda (return)
5078                (fold (lambda (element prefix)
5079                        (if (equal? element x)
5080                            (return (reverse prefix))  ; escape `fold'
5081                            (cons element prefix)))
5082                      '()
5083                      lst))))
5084
5085          (prefix 'a '(0 1 2 a 3 4 5))
5086          ⇒ (0 1 2)
5087
5088 -- Scheme Syntax: let-escape-continuation k body ...
5089 -- Scheme Syntax: let/ec k body ...
5090     Bind K within BODY to an escape continuation.
5091
5092     This is equivalent to ‘(call/ec (lambda (K) BODY ...))’.
5093
5094   Additionally there is another helper primitive exported by ‘(ice-9
5095control)’, so load up that module for ‘suspendable-continuation?’:
5096
5097     (use-modules (ice-9 control))
5098
5099 -- Scheme Procedure: suspendable-continuation? tag
5100     Return ‘#t’ if a call to ‘abort-to-prompt’ with the prompt tag TAG
5101     would produce a delimited continuation that could be resumed later.
5102
5103     Almost all continuations have this property.  The exception is
5104     where some code between the ‘call-with-prompt’ and the
5105     ‘abort-to-prompt’ recursed through C for some reason, the
5106     ‘abort-to-prompt’ will succeed but any attempt to resume the
5107     continuation (by calling it) would fail.  This is because composing
5108     a saved continuation with the current continuation involves
5109     relocating the stack frames that were saved from the old stack onto
5110     a (possibly) new position on the new stack, and Guile can only do
5111     this for stack frames that it created for Scheme code, not stack
5112     frames created by the C compiler.  It’s a bit gnarly but if you
5113     stick with Scheme, you won’t have any problem.
5114
5115     If no prompt is found with the given tag, this procedure just
5116     returns ‘#f’.
5117
5118
5119File: guile.info,  Node: Shift and Reset,  Prev: Prompt Primitives,  Up: Prompts
5120
51216.11.5.2 Shift, Reset, and All That
5122...................................
5123
5124There is a whole zoo of delimited control operators, and as it does not
5125seem to be a bounded set, Guile implements support for them in a
5126separate module:
5127
5128     (use-modules (ice-9 control))
5129
5130   Firstly, we have a helpful abbreviation for the ‘call-with-prompt’
5131operator.
5132
5133 -- Scheme Syntax: % expr
5134 -- Scheme Syntax: % expr handler
5135 -- Scheme Syntax: % tag expr handler
5136     Evaluate EXPR in a prompt, optionally specifying a tag and a
5137     handler.  If no tag is given, the default prompt tag is used.
5138
5139     If no handler is given, a default handler is installed.  The
5140     default handler accepts a procedure of one argument, which will be
5141     called on the captured continuation, within a prompt.
5142
5143     Sometimes it’s easier just to show code, as in this case:
5144
5145          (define (default-prompt-handler k proc)
5146            (% (default-prompt-tag)
5147               (proc k)
5148               default-prompt-handler))
5149
5150     The ‘%’ symbol is chosen because it looks like a prompt.
5151
5152   Likewise there is an abbreviation for ‘abort-to-prompt’, which
5153assumes the default prompt tag:
5154
5155 -- Scheme Procedure: abort val1 val2 ...
5156     Abort to the default prompt tag, passing VAL1 VAL2 ... to the
5157     handler.
5158
5159   As mentioned before, ‘(ice-9 control)’ also provides other delimited
5160control operators.  This section is a bit technical, and first-time
5161users of delimited continuations should probably come back to it after
5162some practice with ‘%’.
5163
5164   Still here?  So, when one implements a delimited control operator
5165like ‘call-with-prompt’, one needs to make two decisions.  Firstly, does
5166the handler run within or outside the prompt?  Having the handler run
5167within the prompt allows an abort inside the handler to return to the
5168same prompt handler, which is often useful.  However it prevents tail
5169calls from the handler, so it is less general.
5170
5171   Similarly, does invoking a captured continuation reinstate a prompt?
5172Again we have the tradeoff of convenience versus proper tail calls.
5173
5174   These decisions are captured in the Felleisen “F” operator.  If
5175neither the continuations nor the handlers implicitly add a prompt, the
5176operator is known as “–F–”.  This is the case for Guile’s
5177‘call-with-prompt’ and ‘abort-to-prompt’.
5178
5179   If both continuation and handler implicitly add prompts, then the
5180operator is “+F+”.  ‘shift’ and ‘reset’ are such operators.
5181
5182 -- Scheme Syntax: reset body1 body2 ...
5183     Establish a prompt, and evaluate BODY1 BODY2 ... within that
5184     prompt.
5185
5186     The prompt handler is designed to work with ‘shift’, described
5187     below.
5188
5189 -- Scheme Syntax: shift cont body1 body2 ...
5190     Abort to the nearest ‘reset’, and evaluate BODY1 BODY2 ... in a
5191     context in which the captured continuation is bound to CONT.
5192
5193     As mentioned above, taken together, the BODY1 BODY2 ... expressions
5194     and the invocations of CONT implicitly establish a prompt.
5195
5196   Interested readers are invited to explore Oleg Kiselyov’s wonderful
5197web site at <http://okmij.org/ftp/>, for more information on these
5198operators.
5199
5200
5201File: guile.info,  Node: Continuations,  Next: Multiple Values,  Prev: Prompts,  Up: Control Mechanisms
5202
52036.11.6 Continuations
5204--------------------
5205
5206A “continuation” is the code that will execute when a given function or
5207expression returns.  For example, consider
5208
5209     (define (foo)
5210       (display "hello\n")
5211       (display (bar)) (newline)
5212       (exit))
5213
5214   The continuation from the call to ‘bar’ comprises a ‘display’ of the
5215value returned, a ‘newline’ and an ‘exit’.  This can be expressed as a
5216function of one argument.
5217
5218     (lambda (r)
5219       (display r) (newline)
5220       (exit))
5221
5222   In Scheme, continuations are represented as special procedures just
5223like this.  The special property is that when a continuation is called
5224it abandons the current program location and jumps directly to that
5225represented by the continuation.
5226
5227   A continuation is like a dynamic label, capturing at run-time a point
5228in program execution, including all the nested calls that have lead to
5229it (or rather the code that will execute when those calls return).
5230
5231   Continuations are created with the following functions.
5232
5233 -- Scheme Procedure: call-with-current-continuation proc
5234 -- Scheme Procedure: call/cc proc
5235     Capture the current continuation and call ‘(PROC CONT)’ with it.
5236     The return value is the value returned by PROC, or when ‘(CONT
5237     VALUE)’ is later invoked, the return is the VALUE passed.
5238
5239     Normally CONT should be called with one argument, but when the
5240     location resumed is expecting multiple values (*note Multiple
5241     Values::) then they should be passed as multiple arguments, for
5242     instance ‘(CONT X Y Z)’.
5243
5244     CONT may only be used from the same side of a continuation barrier
5245     as it was created (*note Continuation Barriers::), and in a
5246     multi-threaded program only from the thread in which it was
5247     created.
5248
5249     The call to PROC is not part of the continuation captured, it runs
5250     only when the continuation is created.  Often a program will want
5251     to store CONT somewhere for later use; this can be done in PROC.
5252
5253     The ‘call’ in the name ‘call-with-current-continuation’ refers to
5254     the way a call to PROC gives the newly created continuation.  It’s
5255     not related to the way a call is used later to invoke that
5256     continuation.
5257
5258call/cc’ is an alias for ‘call-with-current-continuation’.  This
5259     is in common use since the latter is rather long.
5260
5261
5262Here is a simple example,
5263
5264     (define kont #f)
5265     (format #t "the return is ~a\n"
5266             (call/cc (lambda (k)
5267                        (set! kont k)
5268                        1)))
5269     ⇒ the return is 1
5270
5271     (kont 2)
5272     ⇒ the return is 2
5273
5274call/cc’ captures a continuation in which the value returned is
5275going to be displayed by ‘format’.  The ‘lambda’ stores this in ‘kont’
5276and gives an initial return ‘1’ which is displayed.  The later
5277invocation of ‘kont’ resumes the captured point, but this time returning
5278‘2’, which is displayed.
5279
5280   When Guile is run interactively, a call to ‘format’ like this has an
5281implicit return back to the read-eval-print loop.  ‘call/cc’ captures
5282that like any other return, which is why interactively ‘kont’ will come
5283back to read more input.
5284
5285
5286   C programmers may note that ‘call/cc’ is like ‘setjmp’ in the way it
5287records at runtime a point in program execution.  A call to a
5288continuation is like a ‘longjmp’ in that it abandons the present
5289location and goes to the recorded one.  Like ‘longjmp’, the value passed
5290to the continuation is the value returned by ‘call/cc’ on resuming
5291there.  However ‘longjmp’ can only go up the program stack, but the
5292continuation mechanism can go anywhere.
5293
5294   When a continuation is invoked, ‘call/cc’ and subsequent code
5295effectively “returns” a second time.  It can be confusing to imagine a
5296function returning more times than it was called.  It may help instead
5297to think of it being stealthily re-entered and then program flow going
5298on as normal.
5299
5300   ‘dynamic-wind’ (*note Dynamic Wind::) can be used to ensure setup and
5301cleanup code is run when a program locus is resumed or abandoned through
5302the continuation mechanism.
5303
5304
5305   Continuations are a powerful mechanism, and can be used to implement
5306almost any sort of control structure, such as loops, coroutines, or
5307exception handlers.
5308
5309   However the implementation of continuations in Guile is not as
5310efficient as one might hope, because Guile is designed to cooperate with
5311programs written in other languages, such as C, which do not know about
5312continuations.  Basically continuations are captured by a block copy of
5313the stack, and resumed by copying back.
5314
5315   For this reason, continuations captured by ‘call/cc’ should be used
5316only when there is no other simple way to achieve the desired result, or
5317when the elegance of the continuation mechanism outweighs the need for
5318performance.
5319
5320   Escapes upwards from loops or nested functions are generally best
5321handled with prompts (*note Prompts::).  Coroutines can be efficiently
5322implemented with cooperating threads (a thread holds a full program
5323stack but doesn’t copy it around the way continuations do).
5324
5325
5326File: guile.info,  Node: Multiple Values,  Next: Exceptions,  Prev: Continuations,  Up: Control Mechanisms
5327
53286.11.7 Returning and Accepting Multiple Values
5329----------------------------------------------
5330
5331Scheme allows a procedure to return more than one value to its caller.
5332This is quite different to other languages which only allow single-value
5333returns.  Returning multiple values is different from returning a list
5334(or pair or vector) of values to the caller, because conceptually not
5335_one_ compound object is returned, but several distinct values.
5336
5337   The primitive procedures for handling multiple values are ‘values’
5338and ‘call-with-values’.  ‘values’ is used for returning multiple values
5339from a procedure.  This is done by placing a call to ‘values’ with zero
5340or more arguments in tail position in a procedure body.
5341‘call-with-values’ combines a procedure returning multiple values with a
5342procedure which accepts these values as parameters.
5343
5344 -- Scheme Procedure: values arg ...
5345 -- C Function: scm_values (args)
5346     Delivers all of its arguments to its continuation.  Except for
5347     continuations created by the ‘call-with-values’ procedure, all
5348     continuations take exactly one value.  The effect of passing no
5349     value or more than one value to continuations that were not created
5350     by ‘call-with-values’ is unspecified.
5351
5352     For ‘scm_values’, ARGS is a list of arguments and the return is a
5353     multiple-values object which the caller can return.  In the current
5354     implementation that object shares structure with ARGS, so ARGS
5355     should not be modified subsequently.
5356
5357 -- C Function: SCM scm_c_values (SCM *base, size_t n)
5358     ‘scm_c_values’ is an alternative to ‘scm_values’.  It creates a new
5359     values object, and copies into it the N values starting from BASE.
5360
5361     Currently this creates a list and passes it to ‘scm_values’, but we
5362     expect that in the future we will be able to use a more efficient
5363     representation.
5364
5365 -- C Function: size_t scm_c_nvalues (SCM obj)
5366     If OBJ is a multiple-values object, returns the number of values it
5367     contains.  Otherwise returns 1.
5368
5369 -- C Function: SCM scm_c_value_ref (SCM obj, size_t idx)
5370     Returns the value at the position specified by IDX in OBJ.  Note
5371     that OBJ will ordinarily be a multiple-values object, but it need
5372     not be.  Any other object represents a single value (itself), and
5373     is handled appropriately.
5374
5375 -- Scheme Procedure: call-with-values producer consumer
5376     Calls its PRODUCER argument with no values and a continuation that,
5377     when passed some values, calls the CONSUMER procedure with those
5378     values as arguments.  The continuation for the call to CONSUMER is
5379     the continuation of the call to ‘call-with-values’.
5380
5381          (call-with-values (lambda () (values 4 5))
5382                            (lambda (a b) b))
5383          ⇒ 5
5384
5385          (call-with-values * -)
5386          ⇒ -1
5387
5388   In addition to the fundamental procedures described above, Guile has
5389a module which exports a syntax called ‘receive’, which is much more
5390convenient.  This is in the ‘(ice-9 receive)’ and is the same as
5391specified by SRFI-8 (*note SRFI-8::).
5392
5393     (use-modules (ice-9 receive))
5394
5395 -- library syntax: receive formals expr body ...
5396     Evaluate the expression EXPR, and bind the result values (zero or
5397     more) to the formal arguments in FORMALS.  FORMALS is a list of
5398     symbols, like the argument list in a ‘lambda’ (*note Lambda::).
5399     After binding the variables, the expressions in BODY ... are
5400     evaluated in order, the return value is the result from the last
5401     expression.
5402
5403     For example getting results from ‘partition’ in SRFI-1 (*note
5404     SRFI-1::),
5405
5406          (receive (odds evens)
5407              (partition odd? '(7 4 2 8 3))
5408            (display odds)
5409            (display " and ")
5410            (display evens))
5411          ⊣ (7 3) and (4 2 8)
5412
5413
5414File: guile.info,  Node: Exceptions,  Next: Error Reporting,  Prev: Multiple Values,  Up: Control Mechanisms
5415
54166.11.8 Exceptions
5417-----------------
5418
5419What happens when things go wrong?  Guile’s exception facility exists to
5420help answer this question, allowing programs to describe the problem and
5421to handle the situation in a flexible way.
5422
5423   When a program runs into a problem, such as division by zero, it will
5424raise an exception.  Sometimes exceptions get raised by Guile on a
5425program’s behalf.  Sometimes a program will want to raise exceptions of
5426its own.  Raising an exception stops the current computation and instead
5427invokes the current exception handler, passing it an exception object
5428describing the unexpected situation.
5429
5430   Usually an exception handler will unwind the computation back to some
5431kind of safe point.  For example, typical logic for a key press driven
5432application might look something like this:
5433
5434     main-loop:
5435       read the next key press and call dispatch-key
5436
5437     dispatch-key:
5438       lookup the key in a keymap and call an appropriate procedure,
5439       say find-file
5440
5441     find-file:
5442       interactively read the required file name, then call
5443       find-specified-file
5444
5445     find-specified-file:
5446       check whether file exists; if not, raise an exception
5447       ...
5448
5449   In this case, ‘main-loop’ can install an exception handler that would
5450cause any exception raised inside ‘dispatch-key’ to print a warning and
5451jump back to the main loop.
5452
5453   The following subsections go into more detail about exception
5454objects, raising exceptions, and handling exceptions.  It also presents
5455a historical interface that was used in Guile’s first 25 years and which
5456won’t be going away any time soon.
5457
5458* Menu:
5459
5460* Exception Objects::           What went wrong?
5461* Raising and Handling Exceptions::  What to do when something goes wrong.
5462* Throw and Catch::             An older approach to exceptions.
5463* Exceptions and C::            Specialized interfaces for C.
5464
5465
5466File: guile.info,  Node: Exception Objects,  Next: Raising and Handling Exceptions,  Up: Exceptions
5467
54686.11.8.1 Exception Objects
5469..........................
5470
5471When Guile encounters an exceptional situation, it raises an exception,
5472where the exception is an object that describes the exceptional
5473situation.  Exception objects are structured data, built on the record
5474facility (*note Records::).
5475
5476 -- Exception Type: &exception
5477     The base exception type.  All exception objects are composed of
5478     instances of subtypes of ‘&exception’.
5479
5480 -- Scheme Procedure: exception-type? obj
5481     Return true if OBJ is an exception type.
5482
5483   Exception types exist in a hierarchy.  New exception types can be
5484defined using ‘make-exception-type’.
5485
5486 -- Scheme Procedure: make-exception-type id parent field-names
5487     Return a new exception type named ID, inheriting from PARENT, and
5488     with the fields whose names are listed in FIELD-NAMES.  FIELD-NAMES
5489     must be a list of symbols and must not contain names already used
5490     by PARENT or one of its supertypes.
5491
5492   Exception type objects are record type objects, and as such, one can
5493use ‘record-constructor’ on an exception type to get its constructor.
5494The constructor will take as many arguments as the exception has fields
5495(including supertypes).  *Note Records::.
5496
5497   However, ‘record-predicate’ and ‘record-accessor’ aren’t usually what
5498you want to use as exception type predicates and field accessors.  The
5499reason is, instances of exception types can be composed into “compound
5500exceptions”.  Exception accessors should pick out the specific component
5501of a compound exception, and then access the field on that specific
5502component.
5503
5504 -- Scheme Procedure: make-exception exceptions ...
5505     Return an exception object composed of EXCEPTIONS.
5506
5507 -- Scheme Procedure: exception? obj
5508     Return true if OBJ is an exception object.
5509
5510 -- Scheme Procedure: exception-predicate type
5511     Return a procedure that will return true if its argument is a
5512     simple exception that is an instance of TYPE, or a compound
5513     exception composed of such an instance.
5514
5515 -- Scheme Procedure: exception-accessor rtd proc
5516     Return a procedure that will tail-call PROC on an instance of the
5517     exception type RTD, or on the component of a compound exception
5518     that is an instance of RTD.
5519
5520   Compound exceptions are useful to separately express the different
5521aspects of a situation.  For example, compound exceptions allow a
5522programmer to say that “this situation is a programming error, and also
5523here’s a useful message to show to the user, and here are some relevant
5524objects that can give more information about the error”.  This error
5525could be composed of instances of the ‘&programming-error’, ‘&message’,
5526and ‘&irritants’ exception types.
5527
5528   The subtyping relationship in exceptions is useful to let
5529different-but-similar situations to be treated the same; for example
5530there are many varieties of programming errors (for example,
5531divide-by-zero or type mismatches), but perhaps there are common ways
5532that the user would like to handle them all, and that common way might
5533be different than how one might handle an error originating outside the
5534program (for example, a file-not-found error).
5535
5536   The standard exception hierarchy in Guile takes its cues from R6RS,
5537though the names of some of the types are different.  *Note rnrs
5538exceptions::, for more details.
5539
5540   To have access to Guile’s exception type hierarchy, import the
5541‘(ice-9 exceptions)’ module:
5542
5543     (use-modules (ice-9 exceptions))
5544
5545   The following diagram gives an overview of the standard exception
5546type hierarchy.
5547
5548     &exception
5549     |- &warning
5550     |- &message
5551     |- &irritants
5552     |- &origin
5553     \- &error
5554        |- &external-error
5555        \- &programming-error
5556           |- &assertion-failure
5557           |- &non-continuable
5558           |- &implementation-restriction
5559           |- &lexical
5560           |- &syntax
5561           \- &undefined-variable
5562
5563 -- Exception Type: &warning
5564     An exception type denoting warnings.  These are usually raised
5565     using ‘#:continuable? #t’; see the ‘raise-exception’ documentation
5566     for more.
5567 -- Scheme Procedure: make-warning
5568 -- Scheme Procedure: warning? obj
5569     Constructor and predicate for ‘&warning’ exception objects.
5570
5571 -- Exception Type: &message message
5572     An exception type that provides a message to display to the user.
5573     Usually used as a component of a compound exception.
5574 -- Scheme Procedure: make-exception-with-message message
5575 -- Scheme Procedure: exception-with-message? obj
5576 -- Scheme Procedure: exception-message exn
5577     Constructor, predicate, and accessor for ‘&message’ exception
5578     objects.
5579
5580 -- Exception Type: &irritants irritants
5581     An exception type that provides a list of objects that were
5582     unexpected in some way.  Usually used as a component of a compound
5583     exception.
5584 -- Scheme Procedure: make-exception-with-irritants irritants
5585 -- Scheme Procedure: exception-with-irritants? obj
5586 -- Scheme Procedure: exception-irritants exn
5587     Constructor, predicate, and accessor for ‘&irritants’ exception
5588     objects.
5589
5590 -- Exception Type: &origin origin
5591     An exception type that indicates the origin of an exception,
5592     typically expressed as a procedure name, as a symbol.  Usually used
5593     as a component of a compound exception.
5594 -- Scheme Procedure: make-exception-with-origin origin
5595 -- Scheme Procedure: exception-with-origin? obj
5596 -- Scheme Procedure: exception-origin exn
5597     Constructor, predicate, and accessor for ‘&origin’ exception
5598     objects.
5599
5600 -- Exception Type: &error
5601     An exception type denoting errors: situations that are not just
5602     exceptional, but wrong.
5603 -- Scheme Procedure: make-error
5604 -- Scheme Procedure: error? obj
5605     Constructor and predicate for ‘&error’ exception objects.
5606
5607 -- Exception Type: &external-error
5608     An exception type denoting errors that proceed from the interaction
5609     of the program with the world, for example a “file not found”
5610     error.
5611 -- Scheme Procedure: make-external-error
5612 -- Scheme Procedure: external-error? obj
5613     Constructor and predicate for ‘&external-error’ exception objects.
5614
5615 -- Exception Type: &programming-error
5616     An exception type denoting errors that proceed from inside a
5617     program: type mismatches and so on.
5618 -- Scheme Procedure: make-programming-error
5619 -- Scheme Procedure: programming-error? obj
5620     Constructor and predicate for ‘&programming-error’ exception
5621     objects.
5622
5623 -- Exception Type: &non-continuable
5624     An exception type denoting errors that proceed from inside a
5625     program: type mismatches and so on.
5626 -- Scheme Procedure: make-non-continuable-error
5627 -- Scheme Procedure: non-continuable-error? obj
5628     Constructor and predicate for ‘&non-continuable’ exception objects.
5629
5630 -- Exception Type: &lexical
5631     An exception type denoting lexical errors, for example unbalanced
5632     parentheses.
5633 -- Scheme Procedure: make-lexical-error
5634 -- Scheme Procedure: lexical-error? obj
5635     Constructor and predicate for ‘&lexical’ exception objects.
5636
5637 -- Exception Type: &syntax form subform
5638     An exception type denoting syntax errors, for example a ‘cond’
5639     expression with invalid syntax.  The FORM field indicates the form
5640     containing the error, and SUBFORM indicates the unexpected
5641     subcomponent, or ‘#f’ if unavailable.
5642 -- Scheme Procedure: make-syntax-error form subform
5643 -- Scheme Procedure: syntax-error? obj
5644 -- Scheme Procedure: syntax-error-form exn
5645 -- Scheme Procedure: syntax-error-subform exn
5646     Constructor, predicate, and accessors for ‘&syntax’ exception
5647     objects.
5648
5649 -- Exception Type: &undefined-variable
5650     An exception type denoting undefined variables.
5651 -- Scheme Procedure: make-undefine-variable-error
5652 -- Scheme Procedure: undefined-variable-error? obj
5653     Constructor and predicate for ‘&undefined-variable’ exception
5654     objects.
5655
5656   Incidentally, the ‘(ice-9 exceptions)’ module also includes a
5657‘define-exception-type’ macro that can be used to conveniently add new
5658exception types to the hierarchy.
5659
5660 -- Syntax: define-exception-type name parent constructor predicate
5661          (field accessor) ...
5662     Define NAME to be a new exception type, inheriting from PARENT.
5663     Define CONSTRUCTOR and PREDICATE to be the exception constructor
5664     and predicate, respectively, and define an ACCESSOR for each FIELD.
5665
5666
5667File: guile.info,  Node: Raising and Handling Exceptions,  Next: Throw and Catch,  Prev: Exception Objects,  Up: Exceptions
5668
56696.11.8.2 Raising and Handling Exceptions
5670........................................
5671
5672An exception object describes an exceptional situation.  To bring that
5673description to the attention of the user or to handle the situation
5674programmatically, the first step is to “raise” the exception.
5675
5676 -- Scheme Procedure: raise-exception obj [#:continuable=#f]
5677     Raise an exception by invoking the current exception handler on
5678     OBJ.  The handler is called with a continuation whose dynamic
5679     environment is that of the call to ‘raise’, except that the current
5680     exception handler is the one that was in place when the handler
5681     being called was installed.
5682
5683     If CONTINUABLE? is true, the handler is invoked in tail position
5684     relative to the ‘raise-exception’ call.  Otherwise if the handler
5685     returns, a non-continuable exception of type ‘&non-continuable’ is
5686     raised in the same dynamic environment as the handler.
5687
5688   As the above description notes, Guile has a notion of a “current
5689exception handler”.  At the REPL, this exception handler may enter a
5690recursive debugger; in a standalone program, it may simply print a
5691representation of the error and exit.
5692
5693   To establish an exception handler within the dynamic extent of a
5694call, use ‘with-exception-handler’.
5695
5696 -- Scheme Procedure: with-exception-handler handler thunk
5697          [#:unwind?=#f] [#:unwind-for-type=#t]
5698     Establish HANDLER, a procedure of one argument, as the current
5699     exception handler during the dynamic extent of invoking THUNK.
5700
5701     If ‘raise-exception’ is called during the dynamic extent of
5702     invoking THUNK, HANDLER will be invoked on the argument of
5703     ‘raise-exception’.
5704
5705   There are two kinds of exception handlers: unwinding and
5706non-unwinding.
5707
5708   By default, exception handlers are non-unwinding.  Unless
5709‘with-exception-handler’ was invoked with ‘#:unwind? #t’, exception
5710handlers are invoked within the continuation of the error, without
5711unwinding the stack.  The dynamic environment of the handler call will
5712be that of the ‘raise-exception’ call, with the difference that the
5713current exception handler will be “unwound” to the \"outer\" handler
5714(the one that was in place when the corresponding
5715‘with-exception-handler’ was called).
5716
5717   However, it’s often the case that one would like to handle an
5718exception by unwinding the computation to an earlier state and running
5719the error handler there.  After all, unless the ‘raise-exception’ call
5720is continuable, the exception handler needs to abort the continuation.
5721To support this use case, if ‘with-exception-handler’ was invoked with
5722‘#:unwind? #t’ is true, ‘raise-exception’ will first unwind the stack by
5723invoking an “escape continuation” (*note ‘call/ec’: Prompt Primitives.),
5724and then invoke the handler with the continuation of the
5725‘with-exception-handler’ call.
5726
5727   Finally, one more wrinkle: for unwinding exception handlers, it can
5728be useful to Guile if it can determine whether an exception handler
5729would indeed handle a particular exception or not.  This is especially
5730the case for exceptions raised in resource-exhaustion scenarios like
5731‘stack-overflow’ or ‘out-of-memory’, where you want to immediately
5732shrink resource use before recovering.  *Note Stack Overflow::.  For
5733this purpose, the ‘#:unwind-for-type’ keyword argument allows users to
5734specify the kind of exception handled by an exception handler; if ‘#t’,
5735all exceptions will be handled; if an exception type object, only
5736exceptions of that type will be handled; otherwise if a symbol, only
5737that exceptions with the given ‘exception-kind’ will be handled.
5738
5739
5740File: guile.info,  Node: Throw and Catch,  Next: Exceptions and C,  Prev: Raising and Handling Exceptions,  Up: Exceptions
5741
57426.11.8.3 Throw and Catch
5743........................
5744
5745Guile only adopted ‘with-exception-handler’ and ‘raise-exception’ as its
5746primary exception-handling facility in 2019.  Before then, exception
5747handling was fundamentally based on three other primitives with a
5748somewhat more complex interface: ‘catch’, ‘with-throw-handler’, and
5749‘throw’.
5750
5751 -- Scheme Procedure: catch key thunk handler [pre-unwind-handler]
5752 -- C Function: scm_catch_with_pre_unwind_handler (key, thunk, handler,
5753          pre_unwind_handler)
5754 -- C Function: scm_catch (key, thunk, handler)
5755     Establish an exception handler during the dynamic extent of the
5756     call to THUNK.  KEY is either ‘#t’, indicating that all exceptions
5757     should be handled, or a symbol, restricting the exceptions handled
5758     to those having the KEY as their ‘exception-kind’.
5759
5760     If THUNK executes normally, meaning without throwing any
5761     exceptions, the handler procedures are not called at all and the
5762     result of the ‘thunk’ call is the result of the ‘catch’.  Otherwise
5763     if an exception is thrown that matches KEY, HANDLER is called with
5764     the continuation of the ‘catch’ call.
5765
5766   Given the discussion from the previous section, it is most precise
5767and concise to specify what ‘catch’ does by expressing it in terms of
5768‘with-exception-handler’.  Calling ‘catch’ with the three arguments is
5769the same as:
5770
5771     (define (catch key thunk handler)
5772       (with-exception-handler
5773        (lambda (exn)
5774          (apply handler (exception-kind exn) (exception-args exn)))
5775        thunk
5776        #:unwind? #t
5777        #:unwind-for-type key))
5778
5779   By invoking ‘with-exception-handler’ with ‘#:unwind? #t’, ‘catch’
5780sets up an escape continuation that will be invoked in an exceptional
5781situation before the handler is called.
5782
5783   If ‘catch’ is called with four arguments, then the use of THUNK
5784should be replaced with:
5785
5786        (lambda ()
5787          (with-throw-handler key thunk pre-unwind-handler))
5788
5789   As can be seen above, if a pre-unwind-handler is passed to ‘catch’,
5790it’s like calling ‘with-throw-handler’ inside the body thunk.
5791
5792   ‘with-throw-handler’ is the second of the older primitives, and is
5793used to be able to intercept an exception that is being thrown before
5794the stack is unwound.  This could be to clean up some related state, to
5795print a backtrace, or to pass information about the exception to a
5796debugger, for example.
5797
5798 -- Scheme Procedure: with-throw-handler key thunk handler
5799 -- C Function: scm_with_throw_handler (key, thunk, handler)
5800     Add HANDLER to the dynamic context as a throw handler for key KEY,
5801     then invoke THUNK.
5802
5803   It’s not possible to exactly express ‘with-throw-handler’ in terms of
5804‘with-exception-handler’, but we can get close.
5805
5806     (define (with-throw-handler key thunk handler)
5807       (with-exception-handler
5808        (lambda (exn)
5809          (when (or (eq? key #t) (eq? key (exception-kind exn)))
5810            (apply handler (exception-kind exn) (exception-args exn)))
5811          (raise-exception exn))
5812        thunk))
5813
5814   As you can see, unlike in the case of ‘catch’, the handler for
5815‘with-throw-handler’ is invoked within the continuation of
5816‘raise-exception’, before unwinding the stack.  If the throw handler
5817returns normally, the exception will be re-raised, to be handled by the
5818next exception handler.
5819
5820   The special wrinkle of ‘with-throw-handler’ that can’t be shown above
5821is that if invoking the handler causes a ‘raise-exception’ instead of
5822completing normally, the exception is thrown in the _original_ dynamic
5823environment of the ‘raise-exception’.  Any inner exception handler will
5824get another shot at handling the exception.  Here is an example to
5825illustrate this behavior:
5826
5827     (catch 'a
5828       (lambda ()
5829         (with-throw-handler 'b
5830           (lambda ()
5831             (catch 'a
5832               (lambda ()
5833                 (throw 'b))
5834               inner-handler))
5835           (lambda (key . args)
5836             (throw 'a))))
5837       outer-handler)
5838
5839This code will call ‘inner-handler’ and then continue with the
5840continuation of the inner ‘catch’.
5841
5842   Finally, we get to ‘throw’, which is the older equivalent to
5843‘raise-exception’.
5844
5845 -- Scheme Procedure: throw key arg ...
5846 -- C Function: scm_throw (key, args)
5847     Raise an exception with kind KEY and arguments ARGS.  KEY is a
5848     symbol, denoting the “kind” of the exception.
5849
5850   Again, we can specify what ‘throw’ does by expressing it in terms of
5851‘raise-exception’.
5852
5853     (define (throw key . args)
5854       (raise-exception (make-exception-from-throw key args)))
5855
5856   At this point, we should mention the primitive that manage the
5857relationship between structured exception objects ‘throw’.
5858
5859 -- Scheme Procedure: make-exception-from-throw key args
5860     Create an exception object for the given KEY and ARGS passed to
5861     ‘throw’.  This may be a specific type of exception, for example
5862     ‘&programming-error’; Guile maintains a set of custom transformers
5863     for the various KEY values that have been used historically.
5864
5865 -- Scheme Procedure: exception-kind exn
5866     If EXN is an exception created via ‘make-exception-from-throw’,
5867     return the corresponding KEY for the exception.  Otherwise, unless
5868     EXN is an exception of a type with a known mapping to ‘throw’,
5869     return the symbol ‘%exception’.
5870
5871 -- Scheme Procedure: exception-args exn
5872     If EXN is an exception created via ‘make-exception-from-throw’,
5873     return the corresponding ARGS for the exception.  Otherwise, unless
5874     EXN is an exception of a type with a known mapping to ‘throw’,
5875     return ‘(list EXN)’.
5876
5877
5878File: guile.info,  Node: Exceptions and C,  Prev: Throw and Catch,  Up: Exceptions
5879
58806.11.8.4 Exceptions and C
5881.........................
5882
5883There are some specific versions of Guile’s original ‘catch’ and
5884‘with-throw-handler’ exception-handling primitives that are still widely
5885used in C code.
5886
5887 -- C Function: SCM scm_c_catch (SCM tag, scm_t_catch_body body, void
5888          *body_data, scm_t_catch_handler handler, void *handler_data,
5889          scm_t_catch_handler pre_unwind_handler, void
5890          *pre_unwind_handler_data)
5891 -- C Function: SCM scm_internal_catch (SCM tag, scm_t_catch_body body,
5892          void *body_data, scm_t_catch_handler handler, void
5893          *handler_data)
5894     The above ‘scm_catch_with_pre_unwind_handler’ and ‘scm_catch’ take
5895     Scheme procedures as body and handler arguments.  ‘scm_c_catch’ and
5896     ‘scm_internal_catch’ are equivalents taking C functions.
5897
5898     BODY is called as ‘BODY (BODY_DATA)’ with a catch on exceptions of
5899     the given TAG type.  If an exception is caught, PRE_UNWIND_HANDLER
5900     and HANDLER are called as ‘HANDLER (HANDLER_DATA, KEY, ARGS)’.  KEY
5901     and ARGS are the ‘SCM’ key and argument list from the ‘throw’.
5902
5903     BODY and HANDLER should have the following prototypes.
5904     ‘scm_t_catch_body’ and ‘scm_t_catch_handler’ are pointer typedefs
5905     for these.
5906
5907          SCM body (void *data);
5908          SCM handler (void *data, SCM key, SCM args);
5909
5910     The BODY_DATA and HANDLER_DATA parameters are passed to the
5911     respective calls so an application can communicate extra
5912     information to those functions.
5913
5914     If the data consists of an ‘SCM’ object, care should be taken that
5915     it isn’t garbage collected while still required.  If the ‘SCM’ is a
5916     local C variable, one way to protect it is to pass a pointer to
5917     that variable as the data parameter, since the C compiler will then
5918     know the value must be held on the stack.  Another way is to use
5919     ‘scm_remember_upto_here_1’ (*note Foreign Object Memory
5920     Management::).
5921
5922 -- C Function: SCM scm_c_with_throw_handler (SCM tag, scm_t_catch_body
5923          body, void *body_data, scm_t_catch_handler handler, void
5924          *handler_data, int lazy_catch_p)
5925     The above ‘scm_with_throw_handler’ takes Scheme procedures as body
5926     (thunk) and handler arguments.  ‘scm_c_with_throw_handler’ is an
5927     equivalent taking C functions.  See ‘scm_c_catch’ (*note Exceptions
5928     and C::) for a description of the parameters, the behaviour however
5929     of course follows ‘with-throw-handler’.
5930
5931
5932File: guile.info,  Node: Error Reporting,  Next: Dynamic Wind,  Prev: Exceptions,  Up: Control Mechanisms
5933
59346.11.9 Procedures for Signaling Errors
5935--------------------------------------
5936
5937Guile provides a set of convenience procedures for signaling error
5938conditions that are implemented on top of the exception primitives just
5939described.
5940
5941 -- Scheme Procedure: error msg arg ...
5942     Raise an error with key ‘misc-error’ and a message constructed by
5943     displaying MSG and writing ARG ....
5944
5945 -- Scheme Procedure: scm-error key subr message args data
5946 -- C Function: scm_error_scm (key, subr, message, args, data)
5947     Raise an error with key KEY.  SUBR can be a string naming the
5948     procedure associated with the error, or ‘#f’.  MESSAGE is the error
5949     message string, possibly containing ‘~S’ and ‘~A’ escapes.  When an
5950     error is reported, these are replaced by formatting the
5951     corresponding members of ARGS: ‘~A’ (was ‘%s’ in older versions of
5952     Guile) formats using ‘display’ and ‘~S’ (was ‘%S’) formats using
5953     ‘write’.  DATA is a list or ‘#f’ depending on KEY: if KEY is
5954     ‘system-error’ then it should be a list containing the Unix ‘errno’
5955     value; If KEY is ‘signal’ then it should be a list containing the
5956     Unix signal number; If KEY is ‘out-of-range’, ‘wrong-type-arg’, or
5957     ‘keyword-argument-error’, it is a list containing the bad value;
5958     otherwise it will usually be ‘#f’.
5959
5960 -- Scheme Procedure: strerror err
5961 -- C Function: scm_strerror (err)
5962     Return the Unix error message corresponding to ERR, an integer
5963     ‘errno’ value.
5964
5965     When ‘setlocale’ has been called (*note Locales::), the message is
5966     in the language and charset of ‘LC_MESSAGES’.  (This is done by the
5967     C library.)
5968
5969 -- syntax: false-if-exception expr
5970     Returns the result of evaluating its argument; however if an
5971     exception occurs then ‘#f’ is returned instead.
5972
5973
5974File: guile.info,  Node: Dynamic Wind,  Next: Fluids and Dynamic States,  Prev: Error Reporting,  Up: Control Mechanisms
5975
59766.11.10 Dynamic Wind
5977--------------------
5978
5979For Scheme code, the fundamental procedure to react to non-local entry
5980and exits of dynamic contexts is ‘dynamic-wind’.  C code could use
5981‘scm_internal_dynamic_wind’, but since C does not allow the convenient
5982construction of anonymous procedures that close over lexical variables,
5983this will be, well, inconvenient.
5984
5985   Therefore, Guile offers the functions ‘scm_dynwind_begin’ and
5986‘scm_dynwind_end’ to delimit a dynamic extent.  Within this dynamic
5987extent, which is called a “dynwind context”, you can perform various
5988“dynwind actions” that control what happens when the dynwind context is
5989entered or left.  For example, you can register a cleanup routine with
5990‘scm_dynwind_unwind_handler’ that is executed when the context is left.
5991There are several other more specialized dynwind actions as well, for
5992example to temporarily block the execution of asyncs or to temporarily
5993change the current output port.  They are described elsewhere in this
5994manual.
5995
5996   Here is an example that shows how to prevent memory leaks.
5997
5998
5999     /* Suppose there is a function called FOO in some library that you
6000        would like to make available to Scheme code (or to C code that
6001        follows the Scheme conventions).
6002
6003        FOO takes two C strings and returns a new string.  When an error has
6004        occurred in FOO, it returns NULL.
6005     */
6006
6007     char *foo (char *s1, char *s2);
6008
6009     /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
6010        It takes care to free up all temporary strings in the case of
6011        non-local exits.
6012      */
6013
6014     SCM
6015     scm_foo (SCM s1, SCM s2)
6016     {
6017       char *c_s1, *c_s2, *c_res;
6018
6019       scm_dynwind_begin (0);
6020
6021       c_s1 = scm_to_locale_string (s1);
6022
6023       /* Call 'free (c_s1)' when the dynwind context is left.
6024       */
6025       scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
6026
6027       c_s2 = scm_to_locale_string (s2);
6028
6029       /* Same as above, but more concisely.
6030       */
6031       scm_dynwind_free (c_s2);
6032
6033       c_res = foo (c_s1, c_s2);
6034       if (c_res == NULL)
6035         scm_report_out_of_memory ();
6036
6037       scm_dynwind_end ();
6038
6039       return scm_take_locale_string (res);
6040     }
6041
6042 -- Scheme Procedure: dynamic-wind in_guard thunk out_guard
6043 -- C Function: scm_dynamic_wind (in_guard, thunk, out_guard)
6044     All three arguments must be 0-argument procedures.  IN_GUARD is
6045     called, then THUNK, then OUT_GUARD.
6046
6047     If, any time during the execution of THUNK, the dynamic extent of
6048     the ‘dynamic-wind’ expression is escaped non-locally, OUT_GUARD is
6049     called.  If the dynamic extent of the dynamic-wind is re-entered,
6050     IN_GUARD is called.  Thus IN_GUARD and OUT_GUARD may be called any
6051     number of times.
6052
6053          (define x 'normal-binding)
6054          ⇒ x
6055          (define a-cont
6056            (call-with-current-continuation
6057             (lambda (escape)
6058               (let ((old-x x))
6059                 (dynamic-wind
6060                     ;; in-guard:
6061                     ;;
6062                     (lambda () (set! x 'special-binding))
6063
6064                     ;; thunk
6065                     ;;
6066                     (lambda () (display x) (newline)
6067                                (call-with-current-continuation escape)
6068                                (display x) (newline)
6069                                x)
6070
6071                     ;; out-guard:
6072                     ;;
6073                     (lambda () (set! x old-x)))))))
6074          ;; Prints:
6075          special-binding
6076          ;; Evaluates to:
6077          ⇒ a-cont
6078          x
6079          ⇒ normal-binding
6080          (a-cont #f)
6081          ;; Prints:
6082          special-binding
6083          ;; Evaluates to:
6084          ⇒ a-cont  ;; the value of the (define a-cont...)
6085          x
6086          ⇒ normal-binding
6087          a-cont
6088          ⇒ special-binding
6089
6090 -- C Type: scm_t_dynwind_flags
6091     This is an enumeration of several flags that modify the behavior of
6092     ‘scm_dynwind_begin’.  The flags are listed in the following table.
6093
6094     ‘SCM_F_DYNWIND_REWINDABLE’
6095          The dynamic context is “rewindable”.  This means that it can
6096          be reentered non-locally (via the invocation of a
6097          continuation).  The default is that a dynwind context can not
6098          be reentered non-locally.
6099
6100 -- C Function: void scm_dynwind_begin (scm_t_dynwind_flags flags)
6101     The function ‘scm_dynwind_begin’ starts a new dynamic context and
6102     makes it the ‘current’ one.
6103
6104     The FLAGS argument determines the default behavior of the context.
6105     Normally, use 0.  This will result in a context that can not be
6106     reentered with a captured continuation.  When you are prepared to
6107     handle reentries, include ‘SCM_F_DYNWIND_REWINDABLE’ in FLAGS.
6108
6109     Being prepared for reentry means that the effects of unwind
6110     handlers can be undone on reentry.  In the example above, we want
6111     to prevent a memory leak on non-local exit and thus register an
6112     unwind handler that frees the memory.  But once the memory is
6113     freed, we can not get it back on reentry.  Thus reentry can not be
6114     allowed.
6115
6116     The consequence is that continuations become less useful when
6117     non-reentrant contexts are captured, but you don’t need to worry
6118     about that too much.
6119
6120     The context is ended either implicitly when a non-local exit
6121     happens, or explicitly with ‘scm_dynwind_end’.  You must make sure
6122     that a dynwind context is indeed ended properly.  If you fail to
6123     call ‘scm_dynwind_end’ for each ‘scm_dynwind_begin’, the behavior
6124     is undefined.
6125
6126 -- C Function: void scm_dynwind_end ()
6127     End the current dynamic context explicitly and make the previous
6128     one current.
6129
6130 -- C Type: scm_t_wind_flags
6131     This is an enumeration of several flags that modify the behavior of
6132     ‘scm_dynwind_unwind_handler’ and ‘scm_dynwind_rewind_handler’.  The
6133     flags are listed in the following table.
6134
6135     ‘SCM_F_WIND_EXPLICITLY’
6136          The registered action is also carried out when the dynwind
6137          context is entered or left locally.
6138
6139 -- C Function: void scm_dynwind_unwind_handler (void (*func)(void *),
6140          void *data, scm_t_wind_flags flags)
6141 -- C Function: void scm_dynwind_unwind_handler_with_scm (void
6142          (*func)(SCM), SCM data, scm_t_wind_flags flags)
6143     Arranges for FUNC to be called with DATA as its arguments when the
6144     current context ends implicitly.  If FLAGS contains
6145     ‘SCM_F_WIND_EXPLICITLY’, FUNC is also called when the context ends
6146     explicitly with ‘scm_dynwind_end’.
6147
6148     The function ‘scm_dynwind_unwind_handler_with_scm’ takes care that
6149     DATA is protected from garbage collection.
6150
6151 -- C Function: void scm_dynwind_rewind_handler (void (*func)(void *),
6152          void *data, scm_t_wind_flags flags)
6153 -- C Function: void scm_dynwind_rewind_handler_with_scm (void
6154          (*func)(SCM), SCM data, scm_t_wind_flags flags)
6155     Arrange for FUNC to be called with DATA as its argument when the
6156     current context is restarted by rewinding the stack.  When FLAGS
6157     contains ‘SCM_F_WIND_EXPLICITLY’, FUNC is called immediately as
6158     well.
6159
6160     The function ‘scm_dynwind_rewind_handler_with_scm’ takes care that
6161     DATA is protected from garbage collection.
6162
6163 -- C Function: void scm_dynwind_free (void *mem)
6164     Arrange for MEM to be freed automatically whenever the current
6165     context is exited, whether normally or non-locally.
6166     ‘scm_dynwind_free (mem)’ is an equivalent shorthand for
6167     ‘scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)’.
6168
6169
6170File: guile.info,  Node: Fluids and Dynamic States,  Next: Parameters,  Prev: Dynamic Wind,  Up: Control Mechanisms
6171
61726.11.11 Fluids and Dynamic States
6173---------------------------------
6174
6175A _fluid_ is a variable whose value is associated with the dynamic
6176extent of a function call.  In the same way that an operating system
6177runs a process with a given set of current input and output ports (or
6178file descriptors), in Guile you can arrange to call a function while
6179binding a fluid to a particular value.  That association between fluid
6180and value will exist during the dynamic extent of the function call.
6181
6182   Fluids are therefore a building block for implementing dynamically
6183scoped variables.  Dynamically scoped variables are useful when you want
6184to set a variable to a value during some dynamic extent in the execution
6185of your program and have them revert to their original value when the
6186control flow is outside of this dynamic extent.  See the description of
6187‘with-fluids’ below for details.  This association between fluids,
6188values, and dynamic extents is robust to multiple entries (as when a
6189captured continuation is invoked more than once) and early exits (for
6190example, when throwing exceptions).
6191
6192   Guile uses fluids to implement parameters (*note Parameters::).
6193Usually you just want to use parameters directly.  However it can be
6194useful to know what a fluid is and how it works, so that’s what this
6195section is about.
6196
6197   The current set of fluid-value associations can be captured in a
6198_dynamic state_ object.  A dynamic extent is simply that: a snapshot of
6199the current fluid-value associations.  Guile users can capture the
6200current dynamic state with ‘current-dynamic-state’ and restore it later
6201via ‘with-dynamic-state’ or similar procedures.  This facility is
6202especially useful when implementing lightweight thread-like
6203abstractions.
6204
6205   New fluids are created with ‘make-fluid’ and ‘fluid?’ is used for
6206testing whether an object is actually a fluid.  The values stored in a
6207fluid can be accessed with ‘fluid-ref’ and ‘fluid-set!’.
6208
6209   *Note Thread Local Variables::, for further notes on fluids, threads,
6210parameters, and dynamic states.
6211
6212 -- Scheme Procedure: make-fluid [dflt]
6213 -- C Function: scm_make_fluid ()
6214 -- C Function: scm_make_fluid_with_default (dflt)
6215     Return a newly created fluid, whose initial value is DFLT, or ‘#f’
6216     if DFLT is not given.  Fluids are objects that can hold one value
6217     per dynamic state.  That is, modifications to this value are only
6218     visible to code that executes with the same dynamic state as the
6219     modifying code.  When a new dynamic state is constructed, it
6220     inherits the values from its parent.  Because each thread normally
6221     executes with its own dynamic state, you can use fluids for thread
6222     local storage.
6223
6224 -- Scheme Procedure: make-unbound-fluid
6225 -- C Function: scm_make_unbound_fluid ()
6226     Return a new fluid that is initially unbound (instead of being
6227     implicitly bound to some definite value).
6228
6229 -- Scheme Procedure: fluid? obj
6230 -- C Function: scm_fluid_p (obj)
6231     Return ‘#t’ if OBJ is a fluid; otherwise, return ‘#f’.
6232
6233 -- Scheme Procedure: fluid-ref fluid
6234 -- C Function: scm_fluid_ref (fluid)
6235     Return the value associated with FLUID in the current dynamic root.
6236     If FLUID has not been set, then return its default value.  Calling
6237     ‘fluid-ref’ on an unbound fluid produces a runtime error.
6238
6239 -- Scheme Procedure: fluid-set! fluid value
6240 -- C Function: scm_fluid_set_x (fluid, value)
6241     Set the value associated with FLUID in the current dynamic root.
6242
6243 -- Scheme Procedure: fluid-ref* fluid depth
6244 -- C Function: scm_fluid_ref_star (fluid, depth)
6245     Return the DEPTHth oldest value associated with FLUID in the
6246     current thread.  If DEPTH equals or exceeds the number of values
6247     that have been assigned to FLUID, return the default value of the
6248     fluid.  ‘(fluid-ref* f 0)’ is equivalent to ‘(fluid-ref f)’.
6249
6250     ‘fluid-ref*’ is useful when you want to maintain a stack-like
6251     structure in a fluid, such as the stack of current exception
6252     handlers.  Using ‘fluid-ref*’ instead of an explicit stack allows
6253     any partial continuation captured by ‘call-with-prompt’ to only
6254     capture the bindings made within the limits of the prompt instead
6255     of the entire continuation.  *Note Prompts::, for more on delimited
6256     continuations.
6257
6258 -- Scheme Procedure: fluid-unset! fluid
6259 -- C Function: scm_fluid_unset_x (fluid)
6260     Disassociate the given fluid from any value, making it unbound.
6261
6262 -- Scheme Procedure: fluid-bound? fluid
6263 -- C Function: scm_fluid_bound_p (fluid)
6264     Returns ‘#t’ if the given fluid is bound to a value, otherwise
6265     ‘#f’.
6266
6267   ‘with-fluids*’ temporarily changes the values of one or more fluids,
6268so that the given procedure and each procedure called by it access the
6269given values.  After the procedure returns, the old values are restored.
6270
6271 -- Scheme Procedure: with-fluid* fluid value thunk
6272 -- C Function: scm_with_fluid (fluid, value, thunk)
6273     Set FLUID to VALUE temporarily, and call THUNK.  THUNK must be a
6274     procedure with no argument.
6275
6276 -- Scheme Procedure: with-fluids* fluids values thunk
6277 -- C Function: scm_with_fluids (fluids, values, thunk)
6278     Set FLUIDS to VALUES temporary, and call THUNK.  FLUIDS must be a
6279     list of fluids and VALUES must be the same number of their values
6280     to be applied.  Each substitution is done in the order given.
6281     THUNK must be a procedure with no argument.  It is called inside a
6282     ‘dynamic-wind’ and the fluids are set/restored when control enter
6283     or leaves the established dynamic extent.
6284
6285 -- Scheme Macro: with-fluids ((fluid value) ...) body1 body2 ...
6286     Execute body BODY1 BODY2 ... while each FLUID is set to the
6287     corresponding VALUE.  Both FLUID and VALUE are evaluated and FLUID
6288     must yield a fluid.  The body is executed inside a ‘dynamic-wind’
6289     and the fluids are set/restored when control enter or leaves the
6290     established dynamic extent.
6291
6292 -- C Function: SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM
6293          (*cproc)(void *), void *data)
6294 -- C Function: SCM scm_c_with_fluid (SCM fluid, SCM val, SCM
6295          (*cproc)(void *), void *data)
6296     The function ‘scm_c_with_fluids’ is like ‘scm_with_fluids’ except
6297     that it takes a C function to call instead of a Scheme thunk.
6298
6299     The function ‘scm_c_with_fluid’ is similar but only allows one
6300     fluid to be set instead of a list.
6301
6302 -- C Function: void scm_dynwind_fluid (SCM fluid, SCM val)
6303     This function must be used inside a pair of calls to
6304     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
6305     During the dynwind context, the fluid FLUID is set to VAL.
6306
6307     More precisely, the value of the fluid is swapped with a ‘backup’
6308     value whenever the dynwind context is entered or left.  The backup
6309     value is initialized with the VAL argument.
6310
6311 -- Scheme Procedure: dynamic-state? obj
6312 -- C Function: scm_dynamic_state_p (obj)
6313     Return ‘#t’ if OBJ is a dynamic state object; return ‘#f’
6314     otherwise.
6315
6316 -- C Procedure: int scm_is_dynamic_state (SCM obj)
6317     Return non-zero if OBJ is a dynamic state object; return zero
6318     otherwise.
6319
6320 -- Scheme Procedure: current-dynamic-state
6321 -- C Function: scm_current_dynamic_state ()
6322     Return a snapshot of the current fluid-value associations as a
6323     fresh dynamic state object.
6324
6325 -- Scheme Procedure: set-current-dynamic-state state
6326 -- C Function: scm_set_current_dynamic_state (state)
6327     Restore the saved fluid-value associations from STATE, replacing
6328     the current fluid-value associations.  Return the current
6329     fluid-value associatoins as a dynamic state object, as in
6330     ‘current-dynamic-state’.
6331
6332 -- Scheme Procedure: with-dynamic-state state proc
6333 -- C Function: scm_with_dynamic_state (state, proc)
6334     Call PROC while the fluid bindings from STATE have been made
6335     current, saving the current fluid bindings.  When control leaves
6336     the invocation of PROC, restore the saved bindings, saving instead
6337     the fluid bindings from inside the call.  If control later
6338     re-enters PROC, restore those saved bindings, saving the current
6339     bindings, and so on.
6340
6341 -- C Procedure: void scm_dynwind_current_dynamic_state (SCM state)
6342     Set the current dynamic state to STATE for the current dynwind
6343     context.  Like ‘with-dynamic-state’, but in terms of Guile’s
6344     “dynwind” C API.
6345
6346 -- C Procedure: void * scm_c_with_dynamic_state (SCM state, void
6347          *(*func)(void *), void *data)
6348     Like ‘scm_with_dynamic_state’, but call FUNC with DATA.
6349
6350
6351File: guile.info,  Node: Parameters,  Next: Handling Errors,  Prev: Fluids and Dynamic States,  Up: Control Mechanisms
6352
63536.11.12 Parameters
6354------------------
6355
6356Parameters are Guile’s facility for dynamically bound variables.
6357
6358   On the most basic level, a parameter object is a procedure.  Calling
6359it with no arguments returns its value.  Calling it with one argument
6360sets the value.
6361
6362     (define my-param (make-parameter 123))
6363     (my-param) ⇒ 123
6364     (my-param 456)
6365     (my-param) ⇒ 456
6366
6367   The ‘parameterize’ special form establishes new locations for
6368parameters, those new locations having effect within the dynamic extent
6369of the ‘parameterize’ body.  Leaving restores the previous locations.
6370Re-entering (through a saved continuation) will again use the new
6371locations.
6372
6373     (parameterize ((my-param 789))
6374       (my-param)) ⇒ 789
6375     (my-param) ⇒ 456
6376
6377   Parameters are like dynamically bound variables in other Lisp
6378dialects.  They allow an application to establish parameter settings (as
6379the name suggests) just for the execution of a particular bit of code,
6380restoring when done.  Examples of such parameters might be
6381case-sensitivity for a search, or a prompt for user input.
6382
6383   Global variables are not as good as parameter objects for this sort
6384of thing.  Changes to them are visible to all threads, but in Guile
6385parameter object locations are per-thread, thereby truly limiting the
6386effect of ‘parameterize’ to just its dynamic execution.
6387
6388   Passing arguments to functions is thread-safe, but that soon becomes
6389tedious when there’s more than a few or when they need to pass down
6390through several layers of calls before reaching the point they should
6391affect.  Introducing a new setting to existing code is often easier with
6392a parameter object than adding arguments.
6393
6394 -- Scheme Procedure: make-parameter init [converter]
6395     Return a new parameter object, with initial value INIT.
6396
6397     If a CONVERTER is given, then a call ‘(CONVERTER val)’ is made for
6398     each value set, its return is the value stored.  Such a call is
6399     made for the INIT initial value too.
6400
6401     A CONVERTER allows values to be validated, or put into a canonical
6402     form.  For example,
6403
6404          (define my-param (make-parameter 123
6405                             (lambda (val)
6406                               (if (not (number? val))
6407                                   (error "must be a number"))
6408                               (inexact->exact val))))
6409          (my-param 0.75)
6410          (my-param) ⇒ 3/4
6411
6412 -- library syntax: parameterize ((param value) ...) body1 body2 ...
6413     Establish a new dynamic scope with the given PARAMs bound to new
6414     locations and set to the given VALUEs.  BODY1 BODY2 ... is
6415     evaluated in that environment.  The value returned is that of last
6416     body form.
6417
6418     Each PARAM is an expression which is evaluated to get the parameter
6419     object.  Often this will just be the name of a variable holding the
6420     object, but it can be anything that evaluates to a parameter.
6421
6422     The PARAM expressions and VALUE expressions are all evaluated
6423     before establishing the new dynamic bindings, and they’re evaluated
6424     in an unspecified order.
6425
6426     For example,
6427
6428          (define prompt (make-parameter "Type something: "))
6429          (define (get-input)
6430            (display (prompt))
6431            ...)
6432
6433          (parameterize ((prompt "Type a number: "))
6434            (get-input)
6435            ...)
6436
6437   Parameter objects are implemented using fluids (*note Fluids and
6438Dynamic States::), so each dynamic state has its own parameter
6439locations.  That includes the separate locations when outside any
6440‘parameterize’ form.  When a parameter is created it gets a separate
6441initial location in each dynamic state, all initialized to the given
6442INIT value.
6443
6444   New code should probably just use parameters instead of fluids,
6445because the interface is better.  But for migrating old code or
6446otherwise providing interoperability, Guile provides the
6447‘fluid->parameter’ procedure:
6448
6449 -- Scheme Procedure: fluid->parameter fluid [conv]
6450     Make a parameter that wraps a fluid.
6451
6452     The value of the parameter will be the same as the value of the
6453     fluid.  If the parameter is rebound in some dynamic extent, perhaps
6454     via ‘parameterize’, the new value will be run through the optional
6455     CONV procedure, as with any parameter.  Note that unlike
6456     ‘make-parameter’, CONV is not applied to the initial value.
6457
6458   As alluded to above, because each thread usually has a separate
6459dynamic state, each thread has its own locations behind parameter
6460objects, and changes in one thread are not visible to any other.  When a
6461new dynamic state or thread is created, the values of parameters in the
6462originating context are copied, into new locations.
6463
6464   Guile’s parameters conform to SRFI-39 (*note SRFI-39::).
6465
6466
6467File: guile.info,  Node: Handling Errors,  Next: Continuation Barriers,  Prev: Parameters,  Up: Control Mechanisms
6468
64696.11.13 How to Handle Errors
6470----------------------------
6471
6472Guile is currently in a transition from its historical ‘catch’ and
6473‘throw’ error handling and signaling operators to the new structured
6474exception facility; *Note Exceptions::.  However in the meantime, here
6475is some documentation on errors and the older ‘catch’ and ‘throw’
6476interface.
6477
6478   Errors are always thrown with a KEY and four arguments:
6479
6480   • KEY: a symbol which indicates the type of error.  The symbols used
6481     by libguile are listed below.
6482
6483   • SUBR: the name of the procedure from which the error is thrown, or
6484     ‘#f’.
6485
6486   • MESSAGE: a string (possibly language and system dependent)
6487     describing the error.  The tokens ‘~A’ and ‘~S’ can be embedded
6488     within the message: they will be replaced with members of the ARGS
6489     list when the message is printed.  ‘~A’ indicates an argument
6490     printed using ‘display’, while ‘~S’ indicates an argument printed
6491     using ‘write’.  MESSAGE can also be ‘#f’, to allow it to be derived
6492     from the KEY by the error handler (may be useful if the KEY is to
6493     be thrown from both C and Scheme).
6494
6495   • ARGS: a list of arguments to be used to expand ‘~A’ and ‘~S’ tokens
6496     in MESSAGE.  Can also be ‘#f’ if no arguments are required.
6497
6498   • REST: a list of any additional objects required.  e.g., when the
6499     key is ‘'system-error’, this contains the C errno value.  Can also
6500     be ‘#f’ if no additional objects are required.
6501
6502   In addition to ‘catch’ and ‘throw’, the following Scheme facilities
6503are available:
6504
6505 -- Scheme Procedure: display-error frame port subr message args rest
6506 -- C Function: scm_display_error (frame, port, subr, message, args,
6507          rest)
6508     Display an error message to the output port PORT.  FRAME is the
6509     frame in which the error occurred, SUBR is the name of the
6510     procedure in which the error occurred and MESSAGE is the actual
6511     error message, which may contain formatting instructions.  These
6512     will format the arguments in the list ARGS accordingly.  REST is
6513     currently ignored.
6514
6515   The following are the error keys defined by libguile and the
6516situations in which they are used:
6517
6518   • ‘error-signal’: thrown after receiving an unhandled fatal signal
6519     such as SIGSEGV, SIGBUS, SIGFPE etc.  The REST argument in the
6520     throw contains the coded signal number (at present this is not the
6521     same as the usual Unix signal number).
6522
6523   • ‘system-error’: thrown after the operating system indicates an
6524     error condition.  The REST argument in the throw contains the errno
6525     value.
6526
6527   • ‘numerical-overflow’: numerical overflow.
6528
6529   • ‘out-of-range’: the arguments to a procedure do not fall within the
6530     accepted domain.
6531
6532   • ‘wrong-type-arg’: an argument to a procedure has the wrong type.
6533
6534   • ‘wrong-number-of-args’: a procedure was called with the wrong
6535     number of arguments.
6536
6537   • ‘memory-allocation-error’: memory allocation error.
6538
6539   • ‘stack-overflow’: stack overflow error.
6540
6541   • ‘regular-expression-syntax’: errors generated by the regular
6542     expression library.
6543
6544   • ‘misc-error’: other errors.
6545
65466.11.13.1 C Support
6547...................
6548
6549In the following C functions, SUBR and MESSAGE parameters can be ‘NULL’
6550to give the effect of ‘#f’ described above.
6551
6552 -- C Function: SCM scm_error (SCM KEY, char *SUBR, char *MESSAGE, SCM
6553          ARGS, SCM REST)
6554     Throw an error, as per ‘scm-error’ (*note Error Reporting::).
6555
6556 -- C Function: void scm_syserror (char *SUBR)
6557 -- C Function: void scm_syserror_msg (char *SUBR, char *MESSAGE, SCM
6558          ARGS)
6559     Throw an error with key ‘system-error’ and supply ‘errno’ in the
6560     REST argument.  For ‘scm_syserror’ the message is generated using
6561     ‘strerror’.
6562
6563     Care should be taken that any code in between the failing operation
6564     and the call to these routines doesn’t change ‘errno’.
6565
6566 -- C Function: void scm_num_overflow (char *SUBR)
6567 -- C Function: void scm_out_of_range (char *SUBR, SCM BAD_VALUE)
6568 -- C Function: void scm_wrong_num_args (SCM PROC)
6569 -- C Function: void scm_wrong_type_arg (char *SUBR, int ARGNUM, SCM
6570          BAD_VALUE)
6571 -- C Function: void scm_wrong_type_arg_msg (char *SUBR, int ARGNUM, SCM
6572          BAD_VALUE, const char *EXPECTED)
6573 -- C Function: void scm_misc_error (const char *SUBR, const char
6574          *MESSAGE, SCM ARGS)
6575     Throw an error with the various keys described above.
6576
6577     In ‘scm_wrong_num_args’, PROC should be a Scheme symbol which is
6578     the name of the procedure incorrectly invoked.  The other routines
6579     take the name of the invoked procedure as a C string.
6580
6581     In ‘scm_wrong_type_arg_msg’, EXPECTED is a C string describing the
6582     type of argument that was expected.
6583
6584     In ‘scm_misc_error’, MESSAGE is the error message string, possibly
6585     containing ‘simple-format’ escapes (*note Simple Output::), and the
6586     corresponding arguments in the ARGS list.
6587
65886.11.13.2 Signalling Type Errors
6589................................
6590
6591Every function visible at the Scheme level should aggressively check the
6592types of its arguments, to avoid misinterpreting a value, and perhaps
6593causing a segmentation fault.  Guile provides some macros to make this
6594easier.
6595
6596 -- Macro: void SCM_ASSERT (int TEST, SCM OBJ, unsigned int POSITION,
6597          const char *SUBR)
6598 -- Macro: void SCM_ASSERT_TYPE (int TEST, SCM OBJ, unsigned int
6599          POSITION, const char *SUBR, const char *EXPECTED)
6600     If TEST is zero, signal a “wrong type argument” error, attributed
6601     to the subroutine named SUBR, operating on the value OBJ, which is
6602     the POSITION’th argument of SUBR.
6603
6604     In ‘SCM_ASSERT_TYPE’, EXPECTED is a C string describing the type of
6605     argument that was expected.
6606
6607 -- Macro: int SCM_ARG1
6608 -- Macro: int SCM_ARG2
6609 -- Macro: int SCM_ARG3
6610 -- Macro: int SCM_ARG4
6611 -- Macro: int SCM_ARG5
6612 -- Macro: int SCM_ARG6
6613 -- Macro: int SCM_ARG7
6614     One of the above values can be used for POSITION to indicate the
6615     number of the argument of SUBR which is being checked.
6616     Alternatively, a positive integer number can be used, which allows
6617     to check arguments after the seventh.  However, for parameter
6618     numbers up to seven it is preferable to use ‘SCM_ARGN’ instead of
6619     the corresponding raw number, since it will make the code easier to
6620     understand.
6621
6622 -- Macro: int SCM_ARGn
6623     Passing a value of zero or ‘SCM_ARGn’ for POSITION allows to leave
6624     it unspecified which argument’s type is incorrect.  Again,
6625     ‘SCM_ARGn’ should be preferred over a raw zero constant.
6626
6627
6628File: guile.info,  Node: Continuation Barriers,  Prev: Handling Errors,  Up: Control Mechanisms
6629
66306.11.14 Continuation Barriers
6631-----------------------------
6632
6633The non-local flow of control caused by continuations might sometimes
6634not be wanted.  You can use ‘with-continuation-barrier’ to erect fences
6635that continuations can not pass.
6636
6637 -- Scheme Procedure: with-continuation-barrier proc
6638 -- C Function: scm_with_continuation_barrier (proc)
6639     Call PROC and return its result.  Do not allow the invocation of
6640     continuations that would leave or enter the dynamic extent of the
6641     call to ‘with-continuation-barrier’.  Such an attempt causes an
6642     error to be signaled.
6643
6644     Throws (such as errors) that are not caught from within PROC are
6645     caught by ‘with-continuation-barrier’.  In that case, a short
6646     message is printed to the current error port and ‘#f’ is returned.
6647
6648     Thus, ‘with-continuation-barrier’ returns exactly once.
6649
6650 -- C Function: void * scm_c_with_continuation_barrier (void *(*func)
6651          (void *), void *data)
6652     Like ‘scm_with_continuation_barrier’ but call FUNC on DATA.  When
6653     an error is caught, ‘NULL’ is returned.
6654
6655
6656File: guile.info,  Node: Input and Output,  Next: Regular Expressions,  Prev: Control Mechanisms,  Up: API Reference
6657
66586.12 Input and Output
6659=====================
6660
6661* Menu:
6662
6663* Ports::                       What’s a port?
6664* Binary I/O::                  Reading and writing bytes.
6665* Encoding::                    Characters as bytes.
6666* Textual I/O::                 Reading and writing characters.
6667* Simple Output::               Simple syntactic sugar solution.
6668* Buffering::                   Controlling when data is written to ports.
6669* Random Access::               Moving around a random access port.
6670* Line/Delimited::              Read and write lines or delimited text.
6671* Default Ports::               Defaults for input, output and errors.
6672* Port Types::                  Types of port and how to make them.
6673* Venerable Port Interfaces::   Procedures from the last millenium.
6674* Using Ports from C::          Nice interfaces for C.
6675* I/O Extensions::              Implementing new port types in C.
6676* Non-Blocking I/O::            How Guile deals with EWOULDBLOCK.
6677* BOM Handling::                Handling of Unicode byte order marks.
6678
6679
6680File: guile.info,  Node: Ports,  Next: Binary I/O,  Up: Input and Output
6681
66826.12.1 Ports
6683------------
6684
6685Ports are the way that Guile performs input and output.  Guile can read
6686in characters or bytes from an “input port”, or write them out to an
6687“output port”.  Some ports support both interfaces.
6688
6689   There are a number of different port types implemented in Guile.
6690File ports provide input and output over files, as you might imagine.
6691For example, we might display a string to a file like this:
6692
6693     (let ((port (open-output-file "foo.txt")))
6694       (display "Hello, world!\n" port)
6695       (close-port port))
6696
6697   There are also string ports, for taking input from a string, or
6698collecting output to a string; bytevector ports, for doing the same but
6699using a bytevector as a source or sink of data; and soft ports, for
6700arranging to call Scheme functions to provide input or handle output.
6701*Note Port Types::.
6702
6703   Ports should be “closed” when they are not needed by calling
6704‘close-port’ on them, as in the example above.  This will make sure that
6705any pending output is successfully written out to disk, in the case of a
6706file port, or otherwise to whatever mutable store is backed by the port.
6707Any error that occurs while writing out that buffered data would also be
6708raised promptly at the ‘close-port’, and not later when the port is
6709closed by the garbage collector.  *Note Buffering::, for more on
6710buffered output.
6711
6712   Closing a port also releases any precious resource the file might
6713have.  Usually in Scheme a programmer doesn’t have to clean up after
6714their data structures (*note Memory Management::), but most systems have
6715strict limits on how many files can be open, both on a per-process and a
6716system-wide basis.  A program that uses many files should take care not
6717to hit those limits.  The same applies to similar system resources such
6718as pipes and sockets.
6719
6720   Indeed for these reasons the above example is not the most idiomatic
6721way to use ports.  It is more common to acquire ports via procedures
6722like ‘call-with-output-file’, which handle the ‘close-port’
6723automatically:
6724
6725     (call-with-output-file "foo.txt"
6726       (lambda (port)
6727         (display "Hello, world!\n" port)))
6728
6729   Finally, all ports have associated input and output buffers, as
6730appropriate.  Buffering is a common strategy to limit the overhead of
6731small reads and writes: without buffering, each character fetched from a
6732file would involve at least one call into the kernel, and maybe more
6733depending on the character and the encoding.  Instead, Guile will batch
6734reads and writes into internal buffers.  However, sometimes you want to
6735make output on a port show up immediately.  *Note Buffering::, for more
6736on interfaces to control port buffering.
6737
6738 -- Scheme Procedure: port? x
6739 -- C Function: scm_port_p (x)
6740     Return a boolean indicating whether X is a port.
6741
6742 -- Scheme Procedure: input-port? x
6743 -- C Function: scm_input_port_p (x)
6744     Return ‘#t’ if X is an input port, otherwise return ‘#f’.  Any
6745     object satisfying this predicate also satisfies ‘port?’.
6746
6747 -- Scheme Procedure: output-port? x
6748 -- C Function: scm_output_port_p (x)
6749     Return ‘#t’ if X is an output port, otherwise return ‘#f’.  Any
6750     object satisfying this predicate also satisfies ‘port?’.
6751
6752 -- Scheme Procedure: close-port port
6753 -- C Function: scm_close_port (port)
6754     Close the specified port object.  Return ‘#t’ if it successfully
6755     closes a port or ‘#f’ if it was already closed.  An exception may
6756     be raised if an error occurs, for example when flushing buffered
6757     output.  *Note Buffering::, for more on buffered output.  *Note
6758     close: Ports and File Descriptors, for a procedure which can close
6759     file descriptors.
6760
6761 -- Scheme Procedure: port-closed? port
6762 -- C Function: scm_port_closed_p (port)
6763     Return ‘#t’ if PORT is closed or ‘#f’ if it is open.
6764
6765 -- Scheme Procedure: call-with-port port proc
6766     Call PROC, passing it PORT and closing PORT upon exit of PROC.
6767     Return the return values of PROC.
6768
6769
6770File: guile.info,  Node: Binary I/O,  Next: Encoding,  Prev: Ports,  Up: Input and Output
6771
67726.12.2 Binary I/O
6773-----------------
6774
6775Guile’s ports are fundamentally binary in nature: at the lowest level,
6776they work on bytes.  This section describes Guile’s core binary I/O
6777operations.  *Note Textual I/O::, for input and output of strings and
6778characters.
6779
6780   To use these routines, first include the binary I/O module:
6781
6782     (use-modules (ice-9 binary-ports))
6783
6784   Note that although this module’s name suggests that binary ports are
6785some different kind of port, that’s not the case: all ports in Guile are
6786both binary and textual ports.
6787
6788 -- Scheme Procedure: get-u8 port
6789 -- C Function: scm_get_u8 (port)
6790     Return an octet read from PORT, an input port, blocking as
6791     necessary, or the end-of-file object.
6792
6793 -- Scheme Procedure: lookahead-u8 port
6794 -- C Function: scm_lookahead_u8 (port)
6795     Like ‘get-u8’ but does not update PORT’s position to point past the
6796     octet.
6797
6798   The end-of-file object is unlike any other kind of object: it’s not a
6799pair, a symbol, or anything else.  To check if a value is the
6800end-of-file object, use the ‘eof-object?’ predicate.
6801
6802 -- Scheme Procedure: eof-object? x
6803 -- C Function: scm_eof_object_p (x)
6804     Return ‘#t’ if X is an end-of-file object, or ‘#f’ otherwise.
6805
6806   Note that unlike other procedures in this module, ‘eof-object?’ is
6807defined in the default environment.
6808
6809 -- Scheme Procedure: get-bytevector-n port count
6810 -- C Function: scm_get_bytevector_n (port, count)
6811     Read COUNT octets from PORT, blocking as necessary and return a
6812     bytevector containing the octets read.  If fewer bytes are
6813     available, a bytevector smaller than COUNT is returned.
6814
6815 -- Scheme Procedure: get-bytevector-n! port bv start count
6816 -- C Function: scm_get_bytevector_n_x (port, bv, start, count)
6817     Read COUNT bytes from PORT and store them in BV starting at index
6818     START.  Return either the number of bytes actually read or the
6819     end-of-file object.
6820
6821 -- Scheme Procedure: get-bytevector-some port
6822 -- C Function: scm_get_bytevector_some (port)
6823     Read from PORT, blocking as necessary, until bytes are available or
6824     an end-of-file is reached.  Return either the end-of-file object or
6825     a new bytevector containing some of the available bytes (at least
6826     one), and update the port position to point just past these bytes.
6827
6828 -- Scheme Procedure: get-bytevector-some! port bv start count
6829 -- C Function: scm_get_bytevector_some_x (port, bv, start, count)
6830     Read up to COUNT bytes from PORT, blocking as necessary until at
6831     least one byte is available or an end-of-file is reached.  Store
6832     them in BV starting at index START.  Return the number of bytes
6833     actually read, or an end-of-file object.
6834
6835 -- Scheme Procedure: get-bytevector-all port
6836 -- C Function: scm_get_bytevector_all (port)
6837     Read from PORT, blocking as necessary, until the end-of-file is
6838     reached.  Return either a new bytevector containing the data read
6839     or the end-of-file object (if no data were available).
6840
6841 -- Scheme Procedure: unget-bytevector port bv [start [count]]
6842 -- C Function: scm_unget_bytevector (port, bv, start, count)
6843     Place the contents of BV in PORT, optionally starting at index
6844     START and limiting to COUNT octets, so that its bytes will be read
6845     from left-to-right as the next bytes from PORT during subsequent
6846     read operations.  If called multiple times, the unread bytes will
6847     be read again in last-in first-out order.
6848
6849   To perform binary output on a port, use ‘put-u8’ or ‘put-bytevector’.
6850
6851 -- Scheme Procedure: put-u8 port octet
6852 -- C Function: scm_put_u8 (port, octet)
6853     Write OCTET, an integer in the 0–255 range, to PORT, a binary
6854     output port.
6855
6856 -- Scheme Procedure: put-bytevector port bv [start [count]]
6857 -- C Function: scm_put_bytevector (port, bv, start, count)
6858     Write the contents of BV to PORT, optionally starting at index
6859     START and limiting to COUNT octets.
6860
6861
6862File: guile.info,  Node: Encoding,  Next: Textual I/O,  Prev: Binary I/O,  Up: Input and Output
6863
68646.12.3 Encoding
6865---------------
6866
6867Textual input and output on Guile ports is layered on top of binary
6868operations.  To this end, each port has an associated character encoding
6869that controls how bytes read from the port are converted to characters,
6870and how characters written to the port are converted to bytes.
6871
6872 -- Scheme Procedure: port-encoding port
6873 -- C Function: scm_port_encoding (port)
6874     Returns, as a string, the character encoding that PORT uses to
6875     interpret its input and output.
6876
6877 -- Scheme Procedure: set-port-encoding! port enc
6878 -- C Function: scm_set_port_encoding_x (port, enc)
6879     Sets the character encoding that will be used to interpret I/O to
6880     PORT.  ENC is a string containing the name of an encoding.  Valid
6881     encoding names are those defined by IANA
6882     (http://www.iana.org/assignments/character-sets), for example
6883     ‘"UTF-8"’ or ‘"ISO-8859-1"’.
6884
6885   When ports are created, they are assigned an encoding.  The usual
6886process to determine the initial encoding for a port is to take the
6887value of the ‘%default-port-encoding’ fluid.
6888
6889 -- Scheme Variable: %default-port-encoding
6890     A fluid containing name of the encoding to be used by default for
6891     newly created ports (*note Fluids and Dynamic States::).  As a
6892     special case, the value ‘#f’ is equivalent to ‘"ISO-8859-1"’.
6893
6894   The ‘%default-port-encoding’ itself defaults to the encoding
6895appropriate for the current locale, if ‘setlocale’ has been called.
6896*Note Locales::, for more on locales and when you might need to call
6897‘setlocale’ explicitly.
6898
6899   Some port types have other ways of determining their initial locales.
6900String ports, for example, default to the UTF-8 encoding, in order to be
6901able to represent all characters regardless of the current locale.  File
6902ports can optionally sniff their file for a ‘coding:’ declaration; *Note
6903File Ports::.  Binary ports might be initialized to the ISO-8859-1
6904encoding in which each codepoint between 0 and 255 corresponds to a byte
6905with that value.
6906
6907   Currently, the ports only work with _non-modal_ encodings.  Most
6908encodings are non-modal, meaning that the conversion of bytes to a
6909string doesn’t depend on its context: the same byte sequence will always
6910return the same string.  A couple of modal encodings are in common use,
6911like ISO-2022-JP and ISO-2022-KR, and they are not yet supported.
6912
6913   Each port also has an associated conversion strategy, which
6914determines what to do when a Guile character can’t be converted to the
6915port’s encoded character representation for output.  There are three
6916possible strategies: to raise an error, to replace the character with a
6917hex escape, or to replace the character with a substitute character.
6918Port conversion strategies are also used when decoding characters from
6919an input port.
6920
6921 -- Scheme Procedure: port-conversion-strategy port
6922 -- C Function: scm_port_conversion_strategy (port)
6923     Returns the behavior of the port when outputting a character that
6924     is not representable in the port’s current encoding.
6925
6926     If PORT is ‘#f’, then the current default behavior will be
6927     returned.  New ports will have this default behavior when they are
6928     created.
6929
6930 -- Scheme Procedure: set-port-conversion-strategy! port sym
6931 -- C Function: scm_set_port_conversion_strategy_x (port, sym)
6932     Sets the behavior of Guile when outputting a character that is not
6933     representable in the port’s current encoding, or when Guile
6934     encounters a decoding error when trying to read a character.  SYM
6935     can be either ‘error’, ‘substitute’, or ‘escape’.
6936
6937     If PORT is an open port, the conversion error behavior is set for
6938     that port.  If it is ‘#f’, it is set as the default behavior for
6939     any future ports that get created in this thread.
6940
6941   As with port encodings, there is a fluid which determines the initial
6942conversion strategy for a port.
6943
6944 -- Scheme Variable: %default-port-conversion-strategy
6945     The fluid that defines the conversion strategy for newly created
6946     ports, and also for other conversion routines such as
6947     ‘scm_to_stringn’, ‘scm_from_stringn’, ‘string->pointer’, and
6948     ‘pointer->string’.
6949
6950     Its value must be one of the symbols described above, with the same
6951     semantics: ‘error’, ‘substitute’, or ‘escape’.
6952
6953     When Guile starts, its value is ‘substitute’.
6954
6955     Note that ‘(set-port-conversion-strategy! #f SYM)’ is equivalent to
6956     ‘(fluid-set! %default-port-conversion-strategy SYM)’.
6957
6958   As mentioned above, for an output port there are three possible port
6959conversion strategies.  The ‘error’ strategy will throw an error when a
6960nonconvertible character is encountered.  The ‘substitute’ strategy will
6961replace nonconvertible characters with a question mark (‘?’).  Finally
6962the ‘escape’ strategy will print nonconvertible characters as a hex
6963escape, using the escaping that is recognized by Guile’s string syntax.
6964Note that if the port’s encoding is a Unicode encoding, like ‘UTF-8’,
6965then encoding errors are impossible.
6966
6967   For an input port, the ‘error’ strategy will cause Guile to throw an
6968error if it encounters an invalid encoding, such as might happen if you
6969tried to read ‘ISO-8859-1’ as ‘UTF-8’.  The error is thrown before
6970advancing the read position.  The ‘substitute’ strategy will replace the
6971bad bytes with a U+FFFD replacement character, in accordance with
6972Unicode recommendations.  When reading from an input port, the ‘escape’
6973strategy is treated as if it were ‘error’.
6974
6975
6976File: guile.info,  Node: Textual I/O,  Next: Simple Output,  Prev: Encoding,  Up: Input and Output
6977
69786.12.4 Textual I/O
6979------------------
6980
6981This section describes Guile’s core textual I/O operations on characters
6982and strings.  *Note Binary I/O::, for input and output of bytes and
6983bytevectors.  *Note Encoding::, for more on how characters relate to
6984bytes.  To read general S-expressions from ports, *Note Scheme Read::.
6985*Note Scheme Write::, for interfaces that write generic Scheme datums.
6986
6987   To use these routines, first include the textual I/O module:
6988
6989     (use-modules (ice-9 textual-ports))
6990
6991   Note that although this module’s name suggests that textual ports are
6992some different kind of port, that’s not the case: all ports in Guile are
6993both binary and textual ports.
6994
6995 -- Scheme Procedure: get-char input-port
6996     Reads from INPUT-PORT, blocking as necessary, until a complete
6997     character is available from INPUT-PORT, or until an end of file is
6998     reached.
6999
7000     If a complete character is available before the next end of file,
7001     ‘get-char’ returns that character and updates the input port to
7002     point past the character.  If an end of file is reached before any
7003     character is read, ‘get-char’ returns the end-of-file object.
7004
7005 -- Scheme Procedure: lookahead-char input-port
7006     The ‘lookahead-char’ procedure is like ‘get-char’, but it does not
7007     update INPUT-PORT to point past the character.
7008
7009   In the same way that it’s possible to "unget" a byte or bytes, it’s
7010possible to "unget" the bytes corresponding to an encoded character.
7011
7012 -- Scheme Procedure: unget-char port char
7013     Place character CHAR in PORT so that it will be read by the next
7014     read operation.  If called multiple times, the unread characters
7015     will be read again in last-in first-out order.
7016
7017 -- Scheme Procedure: unget-string port str
7018     Place the string STR in PORT so that its characters will be read
7019     from left-to-right as the next characters from PORT during
7020     subsequent read operations.  If called multiple times, the unread
7021     characters will be read again in last-in first-out order.
7022
7023   Reading in a character at a time can be inefficient.  If it’s
7024possible to perform I/O over multiple characters at a time, via strings,
7025that might be faster.
7026
7027 -- Scheme Procedure: get-string-n input-port count
7028     The ‘get-string-n’ procedure reads from INPUT-PORT, blocking as
7029     necessary, until COUNT characters are available, or until an end of
7030     file is reached.  COUNT must be an exact, non-negative integer,
7031     representing the number of characters to be read.
7032
7033     If COUNT characters are available before end of file,
7034     ‘get-string-n’ returns a string consisting of those COUNT
7035     characters.  If fewer characters are available before an end of
7036     file, but one or more characters can be read, ‘get-string-n’
7037     returns a string containing those characters.  In either case, the
7038     input port is updated to point just past the characters read.  If
7039     no characters can be read before an end of file, the end-of-file
7040     object is returned.
7041
7042 -- Scheme Procedure: get-string-n! input-port string start count
7043     The ‘get-string-n!’ procedure reads from INPUT-PORT in the same
7044     manner as ‘get-string-n’.  START and COUNT must be exact,
7045     non-negative integer objects, with COUNT representing the number of
7046     characters to be read.  STRING must be a string with at least
7047     $START + COUNT$ characters.
7048
7049     If COUNT characters are available before an end of file, they are
7050     written into STRING starting at index START, and COUNT is returned.
7051     If fewer characters are available before an end of file, but one or
7052     more can be read, those characters are written into STRING starting
7053     at index START and the number of characters actually read is
7054     returned as an exact integer object.  If no characters can be read
7055     before an end of file, the end-of-file object is returned.
7056
7057 -- Scheme Procedure: get-string-all input-port
7058     Reads from INPUT-PORT until an end of file, decoding characters in
7059     the same manner as ‘get-string-n’ and ‘get-string-n!’.
7060
7061     If characters are available before the end of file, a string
7062     containing all the characters decoded from that data are returned.
7063     If no character precedes the end of file, the end-of-file object is
7064     returned.
7065
7066 -- Scheme Procedure: get-line input-port
7067     Reads from INPUT-PORT up to and including the linefeed character or
7068     end of file, decoding characters in the same manner as
7069     ‘get-string-n’ and ‘get-string-n!’.
7070
7071     If a linefeed character is read, a string containing all of the
7072     text up to (but not including) the linefeed character is returned,
7073     and the port is updated to point just past the linefeed character.
7074     If an end of file is encountered before any linefeed character is
7075     read, but some characters have been read and decoded as characters,
7076     a string containing those characters is returned.  If an end of
7077     file is encountered before any characters are read, the end-of-file
7078     object is returned.
7079
7080   Finally, there are just two core procedures to write characters to a
7081port.
7082
7083 -- Scheme Procedure: put-char port char
7084     Writes CHAR to the port.  The ‘put-char’ procedure returns an
7085     unspecified value.
7086
7087 -- Scheme Procedure: put-string port string
7088 -- Scheme Procedure: put-string port string start
7089 -- Scheme Procedure: put-string port string start count
7090     Write the COUNT characters of STRING starting at index START to the
7091     port.
7092
7093     START and COUNT must be non-negative exact integer objects.  STRING
7094     must have a length of at least START + COUNT.  START defaults to 0.
7095     COUNT defaults to ‘(string-length STRING)’ - START$.
7096
7097     Calling ‘put-string’ is equivalent in all respects to calling
7098     ‘put-char’ on the relevant sequence of characters, except that it
7099     will attempt to write multiple characters to the port at a time,
7100     even if the port is unbuffered.
7101
7102     The ‘put-string’ procedure returns an unspecified value.
7103
7104   Textual ports have a textual position associated with them: a line
7105and a column.  Reading in characters or writing them out advances the
7106line and the column appropriately.
7107
7108 -- Scheme Procedure: port-column port
7109 -- Scheme Procedure: port-line port
7110 -- C Function: scm_port_column (port)
7111 -- C Function: scm_port_line (port)
7112     Return the current column number or line number of PORT.
7113
7114   Port lines and positions are represented as 0-origin integers, which
7115is to say that the the first character of the first line is line 0,
7116column 0.  However, when you display a line number, for example in an
7117error message, we recommend you add 1 to get 1-origin integers.  This is
7118because lines numbers traditionally start with 1, and that is what
7119non-programmers will find most natural.
7120
7121 -- Scheme Procedure: set-port-column! port column
7122 -- Scheme Procedure: set-port-line! port line
7123 -- C Function: scm_set_port_column_x (port, column)
7124 -- C Function: scm_set_port_line_x (port, line)
7125     Set the current column or line number of PORT.
7126
7127
7128File: guile.info,  Node: Simple Output,  Next: Buffering,  Prev: Textual I/O,  Up: Input and Output
7129
71306.12.5 Simple Textual Output
7131----------------------------
7132
7133Guile exports a simple formatted output function, ‘simple-format’.  For
7134a more capable formatted output facility, *Note Formatted Output::.
7135
7136 -- Scheme Procedure: simple-format destination message . args
7137 -- C Function: scm_simple_format (destination, message, args)
7138     Write MESSAGE to DESTINATION, defaulting to the current output
7139     port.  MESSAGE can contain ‘~A’ and ‘~S’ escapes.  When printed,
7140     the escapes are replaced with corresponding members of ARGS: ‘~A’
7141     formats using ‘display’ and ‘~S’ formats using ‘write’.  If
7142     DESTINATION is ‘#t’, then use the current output port, if
7143     DESTINATION is ‘#f’, then return a string containing the formatted
7144     text.  Does not add a trailing newline.
7145
7146   Somewhat confusingly, Guile binds the ‘format’ identifier to
7147‘simple-format’ at startup.  Once ‘(ice-9 format)’ loads, it actually
7148replaces the core ‘format’ binding, so depending on whether you or a
7149module you use has loaded ‘(ice-9 format)’, you may be using the simple
7150or the more capable version.
7151
7152
7153File: guile.info,  Node: Buffering,  Next: Random Access,  Prev: Simple Output,  Up: Input and Output
7154
71556.12.6 Buffering
7156----------------
7157
7158Every port has associated input and output buffers.  You can think of
7159ports as being backed by some mutable store, and that store might be far
7160away.  For example, ports backed by file descriptors have to go all the
7161way to the kernel to read and write their data.  To avoid this
7162round-trip cost, Guile usually reads in data from the mutable store in
7163chunks, and then services small requests like ‘get-char’ out of that
7164intermediate buffer.  Similarly, small writes like ‘write-char’ first go
7165to a buffer, and are sent to the store when the buffer is full (or when
7166port is flushed).  Buffered ports speed up your program by reducing the
7167number of round-trips to the mutable store, and they do so in a way that
7168is mostly transparent to the user.
7169
7170   There are two major ways, however, in which buffering affects program
7171semantics.  Building correct, performant programs requires understanding
7172these situations.
7173
7174   The first case is in random-access read/write ports (*note Random
7175Access::).  These ports, usually backed by a file, logically operate
7176over the same mutable store when both reading and writing.  So, if you
7177read a character, causing the buffer to fill, then write a character,
7178the bytes you filled in your read buffer are now invalid.  Every time
7179you switch between reading and writing, Guile has to flush any pending
7180buffer.  If this happens frequently, the cost can be high.  In that case
7181you should reduce the amount that you buffer, in both directions.
7182Similarly, Guile has to flush buffers before seeking.  None of these
7183considerations apply to sockets, which don’t logically read from and
7184write to the same mutable store, and are not seekable.  Note also that
7185sockets are unbuffered by default.  *Note Network Sockets and
7186Communication::.
7187
7188   The second case is the more pernicious one.  If you write data to a
7189buffered port, it probably doesn’t go out to the mutable store directly.
7190(This “probably” introduces some indeterminism in your program: what
7191goes to the store, and when, depends on how full the buffer is.  It is
7192something that the user needs to explicitly be aware of.)  The data is
7193written to the store later – when the buffer fills up due to another
7194write, or when ‘force-output’ is called, or when ‘close-port’ is called,
7195or when the program exits, or even when the garbage collector runs.  The
7196salient point is, _the errors are signalled then too_.  Buffered writes
7197defer error detection (and defer the side effects to the mutable store),
7198perhaps indefinitely if the port type does not need to be closed at GC.
7199
7200   One common heuristic that works well for textual ports is to flush
7201output when a newline (‘\n’) is written.  This “line buffering” mode is
7202on by default for TTY ports.  Most other ports are “block buffered”,
7203meaning that once the output buffer reaches the block size, which
7204depends on the port and its configuration, the output is flushed as a
7205block, without regard to what is in the block.  Likewise reads are read
7206in at the block size, though if there are fewer bytes available to read,
7207the buffer may not be entirely filled.
7208
7209   Note that binary reads or writes that are larger than the buffer size
7210go directly to the mutable store without passing through the buffers.
7211If your access pattern involves many big reads or writes, buffering
7212might not matter so much to you.
7213
7214   To control the buffering behavior of a port, use ‘setvbuf’.
7215
7216 -- Scheme Procedure: setvbuf port mode [size]
7217 -- C Function: scm_setvbuf (port, mode, size)
7218     Set the buffering mode for PORT.  MODE can be one of the following
7219     symbols:
7220
7221     ‘none’
7222          non-buffered
7223     ‘line’
7224          line buffered
7225     ‘block’
7226          block buffered, using a newly allocated buffer of SIZE bytes.
7227          If SIZE is omitted, a default size will be used.
7228
7229   Another way to set the buffering, for file ports, is to open the file
7230with ‘0’ or ‘l’ as part of the mode string, for unbuffered or
7231line-buffered ports, respectively.  *Note File Ports::, for more.
7232
7233   Any buffered output data will be written out when the port is closed.
7234To make sure to flush it at specific points in your program, use
7235‘force-otput’.
7236
7237 -- Scheme Procedure: force-output [port]
7238 -- C Function: scm_force_output (port)
7239     Flush the specified output port, or the current output port if PORT
7240     is omitted.  The current output buffer contents, if any, are passed
7241     to the underlying port implementation.
7242
7243     The return value is unspecified.
7244
7245 -- Scheme Procedure: flush-all-ports
7246 -- C Function: scm_flush_all_ports ()
7247     Equivalent to calling ‘force-output’ on all open output ports.  The
7248     return value is unspecified.
7249
7250   Similarly, sometimes you might want to switch from using Guile’s
7251ports to working directly on file descriptors.  In that case, for input
7252ports use ‘drain-input’ to get any buffered input from that port.
7253
7254 -- Scheme Procedure: drain-input port
7255 -- C Function: scm_drain_input (port)
7256     This procedure clears a port’s input buffers, similar to the way
7257     that force-output clears the output buffer.  The contents of the
7258     buffers are returned as a single string, e.g.,
7259
7260          (define p (open-input-file ...))
7261          (drain-input p) => empty string, nothing buffered yet.
7262          (unread-char (read-char p) p)
7263          (drain-input p) => initial chars from p, up to the buffer size.
7264
7265   All of these considerations are very similar to those of streams in
7266the C library, although Guile’s ports are not built on top of C streams.
7267Still, it is useful to read what other systems do.  *Note
7268(libc)Streams::, for more discussion on C streams.
7269
7270