add env script
[bpt/guile.git] / module / slib / slib.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename slib.info
4 @settitle SLIB
5 @include version.txi
6 @setchapternewpage on
7 @c Choices for setchapternewpage are {on,off,odd}.
8 @paragraphindent 2
9 @defcodeindex ft
10 @syncodeindex ft cp
11 @syncodeindex tp cp
12 @c %**end of header
13
14 @dircategory The Algorithmic Language Scheme
15 @direntry
16 * SLIB: (slib). Scheme Library
17 @end direntry
18
19 @iftex
20 @finalout
21 @c DL: lose the egregious vertical whitespace, esp. around examples
22 @c but paras in @defun-like things don't have parindent
23 @parskip 4pt plus 1pt
24 @end iftex
25
26 @ifinfo
27 This file documents SLIB, the portable Scheme library.
28
29 Copyright (C) 1993 Todd R. Eigenschink@*
30 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000 Aubrey Jaffer
31
32 Permission is granted to make and distribute verbatim copies of
33 this manual provided the copyright notice and this permission notice
34 are preserved on all copies.
35
36 @ignore
37 Permission is granted to process this file through TeX and print the
38 results, provided the printed document carries copying permission
39 notice identical to this one except for the removal of this paragraph
40 (this paragraph not being relevant to the printed manual).
41
42 @end ignore
43 Permission is granted to copy and distribute modified versions of this
44 manual under the conditions for verbatim copying, provided that the entire
45 resulting derived work is distributed under the terms of a permission
46 notice identical to this one.
47
48 Permission is granted to copy and distribute translations of this manual
49 into another language, under the above conditions for modified versions,
50 except that this permission notice may be stated in a translation approved
51 by the author.
52 @end ifinfo
53
54 @node Top, The Library System, (dir), (dir)
55
56 @titlepage
57 @title SLIB
58 @subtitle The Portable Scheme Library
59 @subtitle Version @value{SLIBVERSION}
60 @author by Aubrey Jaffer
61 @page
62
63 @noindent
64 @dfn{SLIB} is a portable library for the programming language
65 @dfn{Scheme}. It provides a platform independent framework for using
66 @dfn{packages} of Scheme procedures and syntax. As distributed, SLIB
67 contains useful packages for all Scheme implementations. Its catalog
68 can be transparently extended to accomodate packages specific to a site,
69 implementation, user, or directory.
70
71 @noindent
72 More people than I can name have contributed to SLIB. Thanks to all of
73 you!
74 @sp 1
75 @quotation
76 SLIB @value{SLIBVERSION}, released @value{SLIBDATE}.@*
77 Aubrey Jaffer <jaffer @@ ai.mit.edu>@*
78 @ifset html
79 <A HREF="http://swissnet.ai.mit.edu/~jaffer/SLIB.html">
80 @end ifset
81 @url{http://swissnet.ai.mit.edu/~jaffer/SLIB.html}
82 @ifset html
83 </A>
84 @end ifset
85 @end quotation
86
87 @ifclear html
88 @vskip 0pt plus 1filll
89 Copyright @copyright{} 1993 Todd R. Eigenschink@*
90 Copyright @copyright{} 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000 Aubrey Jaffer
91
92 Permission is granted to make and distribute verbatim copies of
93 this manual provided the copyright notice and this permission notice
94 are preserved on all copies.
95
96 Permission is granted to copy and distribute modified versions of this
97 manual under the conditions for verbatim copying, provided that the entire
98 resulting derived work is distributed under the terms of a permission
99 notice identical to this one.
100
101 Permission is granted to copy and distribute translations of this manual
102 into another language, under the above conditions for modified versions,
103 except that this permission notice may be stated in a translation approved
104 by the author.
105 @end ifclear
106 @end titlepage
107
108 @ifinfo
109 @noindent
110 @dfn{SLIB} is a portable library for the programming language
111 @dfn{Scheme}. It provides a platform independent framework for using
112 @dfn{packages} of Scheme procedures and syntax. As distributed, SLIB
113 contains useful packages for all Scheme implementations. Its catalog
114 can be transparently extended to accomodate packages specific to a site,
115 implementation, user, or directory.
116 @end ifinfo
117
118 @menu
119 * The Library System:: How to use and customize.
120 * Scheme Syntax Extension Packages::
121 * Textual Conversion Packages::
122 * Mathematical Packages::
123 * Database Packages::
124 * Other Packages::
125 * About SLIB:: Install, etc.
126 * Index::
127 @end menu
128
129 @node The Library System, Scheme Syntax Extension Packages, Top, Top
130 @chapter The Library System
131
132 @menu
133 * Feature:: SLIB names.
134 * Requesting Features::
135 * Library Catalogs::
136 * Catalog Compilation::
137 * Built-in Support::
138 * About this manual::
139 @end menu
140
141
142 @node Feature, Requesting Features, The Library System, The Library System
143 @section Feature
144
145 @noindent
146 @cindex feature
147 SLIB denotes @dfn{features} by symbols. SLIB maintains a list of
148 features supported by the Scheme @dfn{session}. The set of features
149 @cindex session
150 provided by a session may change over time. Some features are
151 properties of the Scheme implementation being used. The following
152 features detail what sort of numbers are available from an
153 implementation.
154
155 @itemize @bullet
156 @item
157 'inexact
158 @item
159 'rational
160 @item
161 'real
162 @item
163 'complex
164 @item
165 'bignum
166 @end itemize
167
168 @noindent
169 Other features correspond to the presence of sets of Scheme procedures
170 or syntax (macros).
171
172 @defun provided? feature
173 Returns @code{#t} if @var{feature} is supported by the current Scheme
174 session.
175 @end defun
176
177 @deffn Procedure provide feature
178 Informs SLIB that @var{feature} is supported. Henceforth
179 @code{(provided? @var{feature})} will return @code{#t}.
180 @end deffn
181
182 @example
183 (provided? 'foo) @result{} #f
184 (provide 'foo)
185 (provided? 'foo) @result{} #t
186 @end example
187
188
189 @node Requesting Features, Library Catalogs, Feature, The Library System
190 @section Requesting Features
191
192 @noindent
193 @cindex catalog
194 SLIB creates and maintains a @dfn{catalog} mapping features to locations
195 of files introducing procedures and syntax denoted by those features.
196
197 @noindent
198 At the beginning of each section of this manual, there is a line like
199 @code{(require '@var{feature})}.
200 @ftindex feature
201 The Scheme files comprising SLIB are cataloged so that these feature
202 names map to the corresponding files.
203
204 @noindent
205 SLIB provides a form, @code{require}, which loads the files providing
206 the requested feature.
207
208 @deffn Procedure require feature
209 @itemize @bullet
210 @item
211 If @code{(provided? @var{feature})} is true,
212 then @code{require} just returns an unspecified value.
213 @item
214 Otherwise, if @var{feature} is found in the catalog, then the
215 corresponding files will be loaded and an unspecified value returned.
216
217 Subsequently @code{(provided? @var{feature})} will return @code{#t}.
218 @item
219 Otherwise (@var{feature} not found in the catalog), an error is
220 signaled.
221 @end itemize
222 @end deffn
223
224 @noindent
225 The catalog can also be queried using @code{require:feature->path}.
226
227 @defun require:feature->path feature
228 @itemize @bullet
229 @item
230 If @var{feature} is already provided, then returns @code{#t}.
231 @item
232 Otherwise, if @var{feature} is in the catalog, the path or list of paths
233 associated with @var{feature} is returned.
234 @item
235 Otherwise, returns @code{#f}.
236 @end itemize
237 @end defun
238
239
240 @node Library Catalogs, Catalog Compilation, Requesting Features, The Library System
241 @section Library Catalogs
242
243 @noindent
244 At the start of a session no catalog is present, but is created with the
245 first catalog inquiry (such as @code{(require 'random)}). Several
246 sources of catalog information are combined to produce the catalog:
247
248 @itemize @bullet
249 @item
250 standard SLIB packages.
251 @item
252 additional packages of interest to this site.
253 @item
254 packages specifically for the variety of Scheme which this
255 session is running.
256 @item
257 packages this user wants to always have available. This catalog is the
258 file @file{homecat} in the user's @dfn{HOME} directory.
259 @cindex HOME
260 @item
261 packages germane to working in this (current working) directory. This
262 catalog is the file @file{usercat} in the directory to which it applies.
263 One would typically @code{cd} to this directory before starting the
264 Scheme session.
265 @end itemize
266
267 @noindent
268 Catalog files consist of one or more @dfn{association list}s.
269 @cindex Catalog File
270 In the circumstance where a feature symbol appears in more than one
271 list, the latter list's association is retrieved. Here are the
272 supported formats for elements of catalog lists:
273
274 @table @code
275 @item (@var{feature} . @i{<symbol>})
276 Redirects to the feature named @i{<symbol>}.
277 @item (@var{feature} . "@i{<path>}")
278 Loads file @i{<path>}.
279 @item (@var{feature} source "@i{<path>"})
280 @code{slib:load}s the Scheme source file @i{<path>}.
281 @item (@var{feature} compiled "@i{<path>"} @dots{})
282 @code{slib:load-compiled}s the files @i{<path>} @dots{}.
283 @end table
284
285 @noindent
286 The various macro styles first @code{require} the named macro package,
287 then just load @i{<path>} or load-and-macro-expand @i{<path>} as
288 appropriate for the implementation.
289
290 @table @code
291 @item (@var{feature} defmacro "@i{<path>"})
292 @code{defmacro:load}s the Scheme source file @i{<path>}.
293 @item (@var{feature} macro-by-example "@i{<path>"})
294 @code{defmacro:load}s the Scheme source file @i{<path>}.
295 @end table
296
297 @table @code
298 @item (@var{feature} macro "@i{<path>"})
299 @code{macro:load}s the Scheme source file @i{<path>}.
300 @item (@var{feature} macros-that-work "@i{<path>"})
301 @code{macro:load}s the Scheme source file @i{<path>}.
302 @item (@var{feature} syntax-case "@i{<path>"})
303 @code{macro:load}s the Scheme source file @i{<path>}.
304 @item (@var{feature} syntactic-closures "@i{<path>"})
305 @code{macro:load}s the Scheme source file @i{<path>}.
306 @end table
307
308 @noindent
309 Here is an example of a @file{usercat} catalog. A Program in this
310 directory can invoke the @samp{run} feature with @code{(require 'run)}.
311
312 @example
313 ;;; "usercat": SLIB catalog additions for SIMSYNCH. -*-scheme-*-
314
315 (
316 (simsynch . "../synch/simsynch.scm")
317 (run . "../synch/run.scm")
318 (schlep . "schlep.scm")
319 )
320 @end example
321
322
323 @node Catalog Compilation, Built-in Support, Library Catalogs, The Library System
324 @section Catalog Compilation
325
326
327 @noindent
328 SLIB combines the catalog information which doesn't vary per user into
329 the file @file{slibcat} in the implementation-vicinity. Therefore
330 @file{slibcat} needs change only when new software is installed or
331 compiled. Because the actual pathnames of files can differ from
332 installation to installation, SLIB builds a separate catalog for each
333 implementation it is used with.
334
335 @noindent
336 The definition of @code{*SLIB-VERSION*} in SLIB file @file{require.scm}
337 is checked against the catalog association of @code{*SLIB-VERSION*} to
338 ascertain when versions have changed. I recommend that the definition
339 of @code{*SLIB-VERSION*} be changed whenever the library is changed. If
340 multiple implementations of Scheme use SLIB, remember that recompiling
341 one @file{slibcat} will fix only that implementation's catalog.
342
343 @noindent
344 The compilation scripts of Scheme implementations which work with SLIB
345 can automatically trigger catalog compilation by deleting
346 @file{slibcat} or by invoking a special form of @code{require}:
347
348 @deffn Procedure require @r{'new-catalog}
349 @cindex new-catalog
350 This will load @file{mklibcat}, which compiles and writes a new
351 @file{slibcat}.
352 @end deffn
353
354 @noindent
355 Another special form of @code{require} erases SLIB's catalog, forcing it
356 to be reloaded the next time the catalog is queried.
357
358 @deffn Procedure require @r{#f}
359 Removes SLIB's catalog information. This should be done before saving
360 an executable image so that, when restored, its catalog will be loaded
361 afresh.
362 @end deffn
363
364 @noindent
365 Each file in the table below is descibed in terms of its
366 file-system independent @dfn{vicinity} (@pxref{Vicinity}). The entries
367 of a catalog in the table override those of catalogs above it in the
368 table.
369
370 @table @asis
371
372 @item @code{implementation-vicinity} @file{slibcat}
373 @cindex slibcat
374 This file contains the associations for the packages comprising SLIB,
375 the @file{implcat} and the @file{sitecat}s. The associations in the
376 other catalogs override those of the standard catalog.
377
378 @item @code{library-vicinity} @file{mklibcat.scm}
379 @cindex mklibcat.scm
380 creates @file{slibcat}.
381
382 @item @code{library-vicinity} @file{sitecat}
383 @cindex sitecat
384 This file contains the associations specific to an SLIB installation.
385
386 @item @code{implementation-vicinity} @file{implcat}
387 @cindex implcat
388 This file contains the associations specific to an implementation of
389 Scheme. Different implementations of Scheme should have different
390 @code{implementation-vicinity}.
391
392 @item @code{implementation-vicinity} @file{mkimpcat.scm}
393 @cindex mkimpcat.scm
394 if present, creates @file{implcat}.
395
396 @item @code{implementation-vicinity} @file{sitecat}
397 @cindex sitecat
398 This file contains the associations specific to a Scheme implementation
399 installation.
400
401 @item @code{home-vicinity} @file{homecat}
402 @cindex homecat
403 This file contains the associations specific to an SLIB user.
404
405 @item @code{user-vicinity} @file{usercat}
406 @cindex usercat
407 This file contains associations effecting only those sessions whose
408 @dfn{working directory} is @code{user-vicinity}.
409
410 @end table
411
412 @node Built-in Support, About this manual, Catalog Compilation, The Library System
413 @section Built-in Support
414
415 @noindent
416 The procedures described in these sections are supported by all
417 implementations as part of the @samp{*.init} files or by
418 @file{require.scm}.
419
420 @menu
421 * Require:: Module Management
422 * Vicinity:: Pathname Management
423 * Configuration:: Characteristics of Scheme Implementation
424 * Input/Output:: Things not provided by the Scheme specs.
425 * Legacy::
426 * System:: LOADing, EVALing, ERRORing, and EXITing
427 @end menu
428
429
430 @node Require, Vicinity, Built-in Support, Built-in Support
431 @subsection Require
432
433 @defvar *features*
434 Is a list of symbols denoting features supported in this implementation.
435 @var{*features*} can grow as modules are @code{require}d.
436 @var{*features*} must be defined by all implementations
437 (@pxref{Porting}).
438
439 Here are features which SLIB (@file{require.scm}) adds to
440 @var{*features*} when appropriate.
441
442 @itemize @bullet
443 @item
444 'inexact
445 @item
446 'rational
447 @item
448 'real
449 @item
450 'complex
451 @item
452 'bignum
453 @end itemize
454
455 For each item, @code{(provided? '@var{feature})} will return @code{#t}
456 if that feature is available, and @code{#f} if not.
457 @end defvar
458
459 @defvar *modules*
460 Is a list of pathnames denoting files which have been loaded.
461 @end defvar
462
463 @defvar *catalog*
464 Is an association list of features (symbols) and pathnames which will
465 supply those features. The pathname can be either a string or a pair.
466 If pathname is a pair then the first element should be a macro feature
467 symbol, @code{source}, or @code{compiled}. The cdr of the pathname
468 should be either a string or a list.
469 @end defvar
470
471 @noindent
472 In the following functions if the argument @var{feature} is not a symbol
473 it is assumed to be a pathname.
474
475 @defun provided? feature
476 Returns @code{#t} if @var{feature} is a member of @code{*features*} or
477 @code{*modules*} or if @var{feature} is supported by a file already
478 loaded and @code{#f} otherwise.
479 @end defun
480
481 @deffn Procedure require feature
482 @var{feature} is a symbol. If @code{(provided? @var{feature})} is true
483 @code{require} returns. Otherwise, if @code{(assq @var{feature}
484 *catalog*)} is not @code{#f}, the associated files will be loaded and
485 @code{(provided? @var{feature})} will henceforth return @code{#t}. An
486 unspecified value is returned. If @var{feature} is not found in
487 @code{*catalog*}, then an error is signaled.
488
489 @deffnx Procedure require pathname
490 @var{pathname} is a string. If @var{pathname} has not already been
491 given as an argument to @code{require}, @var{pathname} is loaded. An
492 unspecified value is returned.
493 @end deffn
494
495 @deffn Procedure provide feature
496 Assures that @var{feature} is contained in @code{*features*} if
497 @var{feature} is a symbol and @code{*modules*} otherwise.
498 @end deffn
499
500 @defun require:feature->path feature
501 Returns @code{#t} if @var{feature} is a member of @code{*features*} or
502 @code{*modules*} or if @var{feature} is supported by a file already
503 loaded. Returns a path if one was found in @code{*catalog*} under the
504 feature name, and @code{#f} otherwise. The path can either be a string
505 suitable as an argument to load or a pair as described above for
506 *catalog*.
507 @end defun
508
509
510
511
512 @node Vicinity, Configuration, Require, Built-in Support
513 @subsection Vicinity
514
515 @noindent
516 A vicinity is a descriptor for a place in the file system. Vicinities
517 hide from the programmer the concepts of host, volume, directory, and
518 version. Vicinities express only the concept of a file environment
519 where a file name can be resolved to a file in a system independent
520 manner. Vicinities can even be used on @dfn{flat} file systems (which
521 have no directory structure) by having the vicinity express constraints
522 on the file name. On most systems a vicinity would be a string. All of
523 these procedures are file system dependent.
524
525 @noindent
526 These procedures are provided by all implementations.
527
528 @defun make-vicinity path
529 Returns the vicinity of @var{path} for use by @code{in-vicinity}.
530 @end defun
531
532 @defun program-vicinity
533 Returns the vicinity of the currently loading Scheme code. For an
534 interpreter this would be the directory containing source code. For a
535 compiled system (with multiple files) this would be the directory where
536 the object or executable files are. If no file is currently loading it
537 the result is undefined. @strong{Warning:} @code{program-vicinity} can
538 return incorrect values if your program escapes back into a
539 @code{load}.
540 @end defun
541
542 @defun library-vicinity
543 Returns the vicinity of the shared Scheme library.
544 @end defun
545
546 @defun implementation-vicinity
547 Returns the vicinity of the underlying Scheme implementation. This
548 vicinity will likely contain startup code and messages and a compiler.
549 @end defun
550
551 @defun user-vicinity
552 Returns the vicinity of the current directory of the user. On most
553 systems this is @file{""} (the empty string).
554 @end defun
555
556 @defun home-vicinity
557 Returns the vicinity of the user's @dfn{HOME} directory, the directory
558 @cindex HOME
559 which typically contains files which customize a computer environment
560 for a user. If scheme is running without a user (eg. a daemon) or if
561 this concept is meaningless for the platform, then @code{home-vicinity}
562 returns @code{#f}.
563 @end defun
564
565 @c @defun scheme-file-suffix
566 @c Returns the default filename suffix for scheme source files. On most
567 @c systems this is @samp{.scm}.
568 @c @end defun
569
570 @defun in-vicinity vicinity filename
571 Returns a filename suitable for use by @code{slib:load},
572 @code{slib:load-source}, @code{slib:load-compiled},
573 @code{open-input-file}, @code{open-output-file}, etc. The returned
574 filename is @var{filename} in @var{vicinity}. @code{in-vicinity} should
575 allow @var{filename} to override @var{vicinity} when @var{filename} is
576 an absolute pathname and @var{vicinity} is equal to the value of
577 @code{(user-vicinity)}. The behavior of @code{in-vicinity} when
578 @var{filename} is absolute and @var{vicinity} is not equal to the value
579 of @code{(user-vicinity)} is unspecified. For most systems
580 @code{in-vicinity} can be @code{string-append}.
581 @end defun
582
583 @defun sub-vicinity vicinity name
584 Returns the vicinity of @var{vicinity} restricted to @var{name}. This
585 is used for large systems where names of files in subsystems could
586 conflict. On systems with directory structure @code{sub-vicinity} will
587 return a pathname of the subdirectory @var{name} of
588 @var{vicinity}.
589 @end defun
590
591
592
593 @node Configuration, Input/Output, Vicinity, Built-in Support
594 @subsection Configuration
595
596 @noindent
597 These constants and procedures describe characteristics of the Scheme
598 and underlying operating system. They are provided by all
599 implementations.
600
601 @defvr Constant char-code-limit
602 An integer 1 larger that the largest value which can be returned by
603 @code{char->integer}.
604 @end defvr
605
606 @defvr Constant most-positive-fixnum
607 In implementations which support integers of practically unlimited size,
608 @var{most-positive-fixnum} is a large exact integer within the range of
609 exact integers that may result from computing the length of a list,
610 vector, or string.
611
612 In implementations which do not support integers of practically
613 unlimited size, @var{most-positive-fixnum} is the largest exact integer
614 that may result from computing the length of a list, vector, or string.
615 @end defvr
616
617 @defvr Constant slib:tab
618 The tab character.
619 @end defvr
620
621 @defvr Constant slib:form-feed
622 The form-feed character.
623 @end defvr
624
625 @defun software-type
626 Returns a symbol denoting the generic operating system type. For
627 instance, @code{unix}, @code{vms}, @code{macos}, @code{amiga}, or
628 @code{ms-dos}.
629 @end defun
630
631 @defun slib:report-version
632 Displays the versions of SLIB and the underlying Scheme implementation
633 and the name of the operating system. An unspecified value is returned.
634
635 @example
636 (slib:report-version) @result{} slib "@value{SLIBVERSION}" on scm "5b1" on unix
637 @end example
638 @end defun
639
640 @defun slib:report
641 Displays the information of @code{(slib:report-version)} followed by
642 almost all the information neccessary for submitting a problem report.
643 An unspecified value is returned.
644
645 @defunx slib:report #t
646 provides a more verbose listing.
647
648 @defunx slib:report filename
649 Writes the report to file @file{filename}.
650
651 @example
652 (slib:report)
653 @result{}
654 slib "@value{SLIBVERSION}" on scm "5b1" on unix
655 (implementation-vicinity) is "/home/jaffer/scm/"
656 (library-vicinity) is "/home/jaffer/slib/"
657 (scheme-file-suffix) is ".scm"
658 loaded *features* :
659 trace alist qp sort
660 common-list-functions macro values getopt
661 compiled
662 implementation *features* :
663 bignum complex real rational
664 inexact vicinity ed getenv
665 tmpnam abort transcript with-file
666 ieee-p1178 rev4-report rev4-optional-procedures hash
667 object-hash delay eval dynamic-wind
668 multiarg-apply multiarg/and- logical defmacro
669 string-port source current-time record
670 rev3-procedures rev2-procedures sun-dl string-case
671 array dump char-ready? full-continuation
672 system
673 implementation *catalog* :
674 (i/o-extensions compiled "/home/jaffer/scm/ioext.so")
675 ...
676 @end example
677 @end defun
678
679 @node Input/Output, Legacy, Configuration, Built-in Support
680 @subsection Input/Output
681
682 @noindent
683 These procedures are provided by all implementations.
684
685 @deffn Procedure file-exists? filename
686 Returns @code{#t} if the specified file exists. Otherwise, returns
687 @code{#f}. If the underlying implementation does not support this
688 feature then @code{#f} is always returned.
689 @end deffn
690
691 @deffn Procedure delete-file filename
692 Deletes the file specified by @var{filename}. If @var{filename} can not
693 be deleted, @code{#f} is returned. Otherwise, @code{#t} is
694 returned.
695 @end deffn
696
697 @deffn Procedure tmpnam
698 Returns a pathname for a file which will likely not be used by any other
699 process. Successive calls to @code{(tmpnam)} will return different
700 pathnames.
701 @end deffn
702
703 @deffn Procedure current-error-port
704 Returns the current port to which diagnostic and error output is
705 directed.
706 @end deffn
707
708 @deffn Procedure force-output
709 @deffnx Procedure force-output port
710 Forces any pending output on @var{port} to be delivered to the output
711 device and returns an unspecified value. The @var{port} argument may be
712 omitted, in which case it defaults to the value returned by
713 @code{(current-output-port)}.
714 @end deffn
715
716 @deffn Procedure output-port-width
717 @deffnx Procedure output-port-width port
718
719 Returns the width of @var{port}, which defaults to
720 @code{(current-output-port)} if absent. If the width cannot be
721 determined 79 is returned.
722 @end deffn
723
724 @deffn Procedure output-port-height
725 @deffnx Procedure output-port-height port
726
727 Returns the height of @var{port}, which defaults to
728 @code{(current-output-port)} if absent. If the height cannot be
729 determined 24 is returned.
730 @end deffn
731
732 @node Legacy, System, Input/Output, Built-in Support
733 @subsection Legacy
734
735 These procedures are provided by all implementations.
736
737 @defun identity x
738 @var{identity} returns its argument.
739
740 Example:
741 @lisp
742 (identity 3)
743 @result{} 3
744 (identity '(foo bar))
745 @result{} (foo bar)
746 (map identity @var{lst})
747 @equiv{} (copy-list @var{lst})
748 @end lisp
749 @end defun
750
751 @noindent
752 The following procedures were present in Scheme until R4RS
753 (@pxref{Notes, , Language changes ,r4rs, Revised(4) Scheme}).
754 They are provided by all SLIB implementations.
755
756 @defvr Constant t
757 Derfined as @code{#t}.
758 @end defvr
759
760 @defvr Constant nil
761 Defined as @code{#f}.
762 @end defvr
763
764 @defun last-pair l
765 Returns the last pair in the list @var{l}. Example:
766 @lisp
767 (last-pair (cons 1 2))
768 @result{} (1 . 2)
769 (last-pair '(1 2))
770 @result{} (2)
771 @equiv{} (cons 2 '())
772 @end lisp
773 @end defun
774
775 @node System, , Legacy, Built-in Support
776 @subsection System
777
778 @noindent
779 These procedures are provided by all implementations.
780
781 @deffn Procedure slib:load-source name
782 Loads a file of Scheme source code from @var{name} with the default
783 filename extension used in SLIB. For instance if the filename extension
784 used in SLIB is @file{.scm} then @code{(slib:load-source "foo")} will
785 load from file @file{foo.scm}.
786 @end deffn
787
788 @deffn Procedure slib:load-compiled name
789 On implementations which support separtely loadable compiled modules,
790 loads a file of compiled code from @var{name} with the implementation's
791 filename extension for compiled code appended.
792 @end deffn
793
794 @deffn Procedure slib:load name
795 Loads a file of Scheme source or compiled code from @var{name} with the
796 appropriate suffixes appended. If both source and compiled code are
797 present with the appropriate names then the implementation will load
798 just one. It is up to the implementation to choose which one will be
799 loaded.
800
801 If an implementation does not support compiled code then
802 @code{slib:load} will be identical to @code{slib:load-source}.
803 @end deffn
804
805 @deffn Procedure slib:eval obj
806 @code{eval} returns the value of @var{obj} evaluated in the current top
807 level environment. @ref{Eval} provides a more general evaluation
808 facility.
809 @end deffn
810
811 @deffn Procedure slib:eval-load filename eval
812 @var{filename} should be a string. If filename names an existing file,
813 the Scheme source code expressions and definitions are read from the
814 file and @var{eval} called with them sequentially. The
815 @code{slib:eval-load} procedure does not affect the values returned by
816 @code{current-input-port} and @code{current-output-port}.
817 @end deffn
818
819 @deffn Procedure slib:warn arg1 arg2 @dots{}
820 Outputs a warning message containing the arguments.
821 @end deffn
822
823 @deffn Procedure slib:error arg1 arg2 @dots{}
824 Outputs an error message containing the arguments, aborts evaluation of
825 the current form and responds in a system dependent way to the error.
826 Typical responses are to abort the program or to enter a read-eval-print
827 loop.
828 @end deffn
829
830 @deffn Procedure slib:exit n
831 @deffnx Procedure slib:exit
832 Exits from the Scheme session returning status @var{n} to the system.
833 If @var{n} is omitted or @code{#t}, a success status is returned to the
834 system (if possible). If @var{n} is @code{#f} a failure is returned to
835 the system (if possible). If @var{n} is an integer, then @var{n} is
836 returned to the system (if possible). If the Scheme session cannot exit
837 an unspecified value is returned from @code{slib:exit}.
838 @end deffn
839
840
841 @node About this manual, , Built-in Support, The Library System
842 @section About this manual
843
844 @itemize @bullet
845 @item
846 Entries that are labeled as Functions are called for their return
847 values. Entries that are labeled as Procedures are called primarily for
848 their side effects.
849
850 @item
851 Examples in this text were produced using the @code{scm} Scheme
852 implementation.
853
854 @item
855 At the beginning of each section, there is a line that looks like
856 @ftindex feature
857 @code{(require 'feature)}. Include this line in your code prior to
858 using the package.
859 @end itemize
860
861
862 @node Scheme Syntax Extension Packages, Textual Conversion Packages, The Library System, Top
863 @chapter Scheme Syntax Extension Packages
864
865 @menu
866 * Defmacro:: Supported by all implementations
867
868 * R4RS Macros:: 'macro
869 * Macro by Example:: 'macro-by-example
870 * Macros That Work:: 'macros-that-work
871 * Syntactic Closures:: 'syntactic-closures
872 * Syntax-Case Macros:: 'syntax-case
873
874 Syntax extensions (macros) included with SLIB. Also @xref{Structures}.
875
876 * Fluid-Let:: 'fluid-let
877 * Yasos:: 'yasos, 'oop, 'collect
878 @end menu
879
880
881 @node Defmacro, R4RS Macros, Scheme Syntax Extension Packages, Scheme Syntax Extension Packages
882 @section Defmacro
883
884 Defmacros are supported by all implementations.
885 @c See also @code{gentemp}, in @ref{Macros}.
886
887 @defun gentemp
888 Returns a new (interned) symbol each time it is called. The symbol
889 names are implementation-dependent
890 @lisp
891 (gentemp) @result{} scm:G0
892 (gentemp) @result{} scm:G1
893 @end lisp
894 @end defun
895
896 @defun defmacro:eval e
897 Returns the @code{slib:eval} of expanding all defmacros in scheme
898 expression @var{e}.
899 @end defun
900
901 @defun defmacro:load filename
902 @var{filename} should be a string. If filename names an existing file,
903 the @code{defmacro:load} procedure reads Scheme source code expressions
904 and definitions from the file and evaluates them sequentially. These
905 source code expressions and definitions may contain defmacro
906 definitions. The @code{macro:load} procedure does not affect the values
907 returned by @code{current-input-port} and
908 @code{current-output-port}.
909 @end defun
910
911 @defun defmacro? sym
912 Returns @code{#t} if @var{sym} has been defined by @code{defmacro},
913 @code{#f} otherwise.
914 @end defun
915
916 @defun macroexpand-1 form
917 @defunx macroexpand form
918 If @var{form} is a macro call, @code{macroexpand-1} will expand the
919 macro call once and return it. A @var{form} is considered to be a macro
920 call only if it is a cons whose @code{car} is a symbol for which a
921 @code{defmacro} has been defined.
922
923 @code{macroexpand} is similar to @code{macroexpand-1}, but repeatedly
924 expands @var{form} until it is no longer a macro call.
925 @end defun
926
927 @defmac defmacro name lambda-list form @dots{}
928 When encountered by @code{defmacro:eval}, @code{defmacro:macroexpand*},
929 or @code{defmacro:load} defines a new macro which will henceforth be
930 expanded when encountered by @code{defmacro:eval},
931 @code{defmacro:macroexpand*}, or @code{defmacro:load}.
932 @end defmac
933
934 @subsection Defmacroexpand
935 @code{(require 'defmacroexpand)}
936 @ftindex defmacroexpand
937
938 @defun defmacro:expand* e
939 Returns the result of expanding all defmacros in scheme expression
940 @var{e}.
941 @end defun
942
943 @node R4RS Macros, Macro by Example, Defmacro, Scheme Syntax Extension Packages
944 @section R4RS Macros
945
946 @code{(require 'macro)} is the appropriate call if you want R4RS
947 @ftindex macro
948 high-level macros but don't care about the low level implementation. If
949 an SLIB R4RS macro implementation is already loaded it will be used.
950 Otherwise, one of the R4RS macros implemetations is loaded.
951
952 The SLIB R4RS macro implementations support the following uniform
953 interface:
954
955 @defun macro:expand sexpression
956 Takes an R4RS expression, macro-expands it, and returns the result of
957 the macro expansion.
958 @end defun
959
960 @defun macro:eval sexpression
961 Takes an R4RS expression, macro-expands it, evals the result of the
962 macro expansion, and returns the result of the evaluation.
963 @end defun
964
965 @deffn Procedure macro:load filename
966 @var{filename} should be a string. If filename names an existing file,
967 the @code{macro:load} procedure reads Scheme source code expressions and
968 definitions from the file and evaluates them sequentially. These source
969 code expressions and definitions may contain macro definitions. The
970 @code{macro:load} procedure does not affect the values returned by
971 @code{current-input-port} and @code{current-output-port}.
972 @end deffn
973
974 @node Macro by Example, Macros That Work, R4RS Macros, Scheme Syntax Extension Packages
975 @section Macro by Example
976
977 @code{(require 'macro-by-example)}
978 @ftindex macro-by-example
979
980 A vanilla implementation of @cite{Macro by Example} (Eugene Kohlbecker,
981 R4RS) by Dorai Sitaram, (dorai@@cs.rice.edu) using @code{defmacro}.
982
983 @itemize @bullet
984
985 @item
986 generating hygienic global @code{define-syntax} Macro-by-Example macros
987 @strong{cheaply}.
988
989 @item
990 can define macros which use @code{...}.
991
992 @item
993 needn't worry about a lexical variable in a macro definition
994 clashing with a variable from the macro use context
995
996 @item
997 don't suffer the overhead of redefining the repl if @code{defmacro}
998 natively supported (most implementations)
999
1000 @end itemize
1001 @subsection Caveat
1002 These macros are not referentially transparent (@pxref{Macros, , ,r4rs,
1003 Revised(4) Scheme}). Lexically scoped macros (i.e., @code{let-syntax}
1004 and @code{letrec-syntax}) are not supported. In any case, the problem
1005 of referential transparency gains poignancy only when @code{let-syntax}
1006 and @code{letrec-syntax} are used. So you will not be courting
1007 large-scale disaster unless you're using system-function names as local
1008 variables with unintuitive bindings that the macro can't use. However,
1009 if you must have the full @cite{r4rs} macro functionality, look to the
1010 more featureful (but also more expensive) versions of syntax-rules
1011 available in slib @ref{Macros That Work}, @ref{Syntactic Closures}, and
1012 @ref{Syntax-Case Macros}.
1013
1014 @defmac define-syntax keyword transformer-spec
1015 The @var{keyword} is an identifier, and the @var{transformer-spec}
1016 should be an instance of @code{syntax-rules}.
1017
1018 The top-level syntactic environment is extended by binding the
1019 @var{keyword} to the specified transformer.
1020
1021 @example
1022 (define-syntax let*
1023 (syntax-rules ()
1024 ((let* () body1 body2 ...)
1025 (let () body1 body2 ...))
1026 ((let* ((name1 val1) (name2 val2) ...)
1027 body1 body2 ...)
1028 (let ((name1 val1))
1029 (let* (( name2 val2) ...)
1030 body1 body2 ...)))))
1031 @end example
1032 @end defmac
1033
1034 @defmac syntax-rules literals syntax-rule @dots{}
1035 @var{literals} is a list of identifiers, and each @var{syntax-rule}
1036 should be of the form
1037
1038 @code{(@var{pattern} @var{template})}
1039
1040 where the @var{pattern} and @var{template} are as in the grammar above.
1041
1042 An instance of @code{syntax-rules} produces a new macro transformer by
1043 specifying a sequence of hygienic rewrite rules. A use of a macro whose
1044 keyword is associated with a transformer specified by
1045 @code{syntax-rules} is matched against the patterns contained in the
1046 @var{syntax-rule}s, beginning with the leftmost @var{syntax-rule}.
1047 When a match is found, the macro use is trancribed hygienically
1048 according to the template.
1049
1050 Each pattern begins with the keyword for the macro. This keyword is not
1051 involved in the matching and is not considered a pattern variable or
1052 literal identifier.
1053 @end defmac
1054
1055 @node Macros That Work, Syntactic Closures, Macro by Example, Scheme Syntax Extension Packages
1056 @section Macros That Work
1057
1058 @code{(require 'macros-that-work)}
1059 @ftindex macros-that-work
1060
1061 @cite{Macros That Work} differs from the other R4RS macro
1062 implementations in that it does not expand derived expression types to
1063 primitive expression types.
1064
1065 @defun macro:expand expression
1066 @defunx macwork:expand expression
1067 Takes an R4RS expression, macro-expands it, and returns the result of
1068 the macro expansion.
1069 @end defun
1070
1071 @defun macro:eval expression
1072 @defunx macwork:eval expression
1073 @code{macro:eval} returns the value of @var{expression} in the current
1074 top level environment. @var{expression} can contain macro definitions.
1075 Side effects of @var{expression} will affect the top level
1076 environment.
1077 @end defun
1078
1079 @deffn Procedure macro:load filename
1080 @deffnx Procedure macwork:load filename
1081 @var{filename} should be a string. If filename names an existing file,
1082 the @code{macro:load} procedure reads Scheme source code expressions and
1083 definitions from the file and evaluates them sequentially. These source
1084 code expressions and definitions may contain macro definitions. The
1085 @code{macro:load} procedure does not affect the values returned by
1086 @code{current-input-port} and @code{current-output-port}.
1087 @end deffn
1088
1089 References:
1090
1091 The @cite{Revised^4 Report on the Algorithmic Language Scheme} Clinger
1092 and Rees [editors]. To appear in LISP Pointers. Also available as a
1093 technical report from the University of Oregon, MIT AI Lab, and
1094 Cornell.
1095
1096 @center Macros That Work. Clinger and Rees. POPL '91.
1097
1098 The supported syntax differs from the R4RS in that vectors are allowed
1099 as patterns and as templates and are not allowed as pattern or template
1100 data.
1101
1102 @example
1103 transformer spec @expansion{} (syntax-rules literals rules)
1104
1105 rules @expansion{} ()
1106 | (rule . rules)
1107
1108 rule @expansion{} (pattern template)
1109
1110 pattern @expansion{} pattern_var ; a symbol not in literals
1111 | symbol ; a symbol in literals
1112 | ()
1113 | (pattern . pattern)
1114 | (ellipsis_pattern)
1115 | #(pattern*) ; extends R4RS
1116 | #(pattern* ellipsis_pattern) ; extends R4RS
1117 | pattern_datum
1118
1119 template @expansion{} pattern_var
1120 | symbol
1121 | ()
1122 | (template2 . template2)
1123 | #(template*) ; extends R4RS
1124 | pattern_datum
1125
1126 template2 @expansion{} template
1127 | ellipsis_template
1128
1129 pattern_datum @expansion{} string ; no vector
1130 | character
1131 | boolean
1132 | number
1133
1134 ellipsis_pattern @expansion{} pattern ...
1135
1136 ellipsis_template @expansion{} template ...
1137
1138 pattern_var @expansion{} symbol ; not in literals
1139
1140 literals @expansion{} ()
1141 | (symbol . literals)
1142 @end example
1143
1144 @subsection Definitions
1145
1146 @table @asis
1147
1148 @item Scope of an ellipsis
1149 Within a pattern or template, the scope of an ellipsis (@code{...}) is
1150 the pattern or template that appears to its left.
1151
1152 @item Rank of a pattern variable
1153 The rank of a pattern variable is the number of ellipses within whose
1154 scope it appears in the pattern.
1155
1156 @item Rank of a subtemplate
1157 The rank of a subtemplate is the number of ellipses within whose scope
1158 it appears in the template.
1159
1160 @item Template rank of an occurrence of a pattern variable
1161 The template rank of an occurrence of a pattern variable within a
1162 template is the rank of that occurrence, viewed as a subtemplate.
1163
1164 @item Variables bound by a pattern
1165 The variables bound by a pattern are the pattern variables that appear
1166 within it.
1167
1168 @item Referenced variables of a subtemplate
1169 The referenced variables of a subtemplate are the pattern variables that
1170 appear within it.
1171
1172 @item Variables opened by an ellipsis template
1173 The variables opened by an ellipsis template are the referenced pattern
1174 variables whose rank is greater than the rank of the ellipsis template.
1175
1176 @end table
1177
1178 @subsection Restrictions
1179
1180 No pattern variable appears more than once within a pattern.
1181
1182 For every occurrence of a pattern variable within a template, the
1183 template rank of the occurrence must be greater than or equal to the
1184 pattern variable's rank.
1185
1186 Every ellipsis template must open at least one variable.
1187
1188 For every ellipsis template, the variables opened by an ellipsis
1189 template must all be bound to sequences of the same length.
1190
1191 The compiled form of a @var{rule} is
1192
1193 @example
1194 rule @expansion{} (pattern template inserted)
1195
1196 pattern @expansion{} pattern_var
1197 | symbol
1198 | ()
1199 | (pattern . pattern)
1200 | ellipsis_pattern
1201 | #(pattern)
1202 | pattern_datum
1203
1204 template @expansion{} pattern_var
1205 | symbol
1206 | ()
1207 | (template2 . template2)
1208 | #(pattern)
1209 | pattern_datum
1210
1211 template2 @expansion{} template
1212 | ellipsis_template
1213
1214 pattern_datum @expansion{} string
1215 | character
1216 | boolean
1217 | number
1218
1219 pattern_var @expansion{} #(V symbol rank)
1220
1221 ellipsis_pattern @expansion{} #(E pattern pattern_vars)
1222
1223 ellipsis_template @expansion{} #(E template pattern_vars)
1224
1225 inserted @expansion{} ()
1226 | (symbol . inserted)
1227
1228 pattern_vars @expansion{} ()
1229 | (pattern_var . pattern_vars)
1230
1231 rank @expansion{} exact non-negative integer
1232 @end example
1233
1234 where V and E are unforgeable values.
1235
1236 The pattern variables associated with an ellipsis pattern are the
1237 variables bound by the pattern, and the pattern variables associated
1238 with an ellipsis template are the variables opened by the ellipsis
1239 template.
1240
1241 If the template contains a big chunk that contains no pattern variables
1242 or inserted identifiers, then the big chunk will be copied
1243 unnecessarily. That shouldn't matter very often.
1244
1245
1246
1247
1248
1249 @node Syntactic Closures, Syntax-Case Macros, Macros That Work, Scheme Syntax Extension Packages
1250 @section Syntactic Closures
1251
1252 @code{(require 'syntactic-closures)}
1253 @ftindex syntactic-closures
1254
1255 @defun macro:expand expression
1256 @defunx synclo:expand expression
1257 Returns scheme code with the macros and derived expression types of
1258 @var{expression} expanded to primitive expression types.
1259 @end defun
1260
1261 @defun macro:eval expression
1262 @defunx synclo:eval expression
1263 @code{macro:eval} returns the value of @var{expression} in the current
1264 top level environment. @var{expression} can contain macro definitions.
1265 Side effects of @var{expression} will affect the top level
1266 environment.
1267 @end defun
1268
1269 @deffn Procedure macro:load filename
1270 @deffnx Procedure synclo:load filename
1271 @var{filename} should be a string. If filename names an existing file,
1272 the @code{macro:load} procedure reads Scheme source code expressions and
1273 definitions from the file and evaluates them sequentially. These
1274 source code expressions and definitions may contain macro definitions.
1275 The @code{macro:load} procedure does not affect the values returned by
1276 @code{current-input-port} and @code{current-output-port}.
1277 @end deffn
1278
1279 @subsection Syntactic Closure Macro Facility
1280
1281 @center A Syntactic Closures Macro Facility
1282 @center by Chris Hanson
1283 @center 9 November 1991
1284
1285 This document describes @dfn{syntactic closures}, a low-level macro
1286 facility for the Scheme programming language. The facility is an
1287 alternative to the low-level macro facility described in the
1288 @cite{Revised^4 Report on Scheme.} This document is an addendum to that
1289 report.
1290
1291 The syntactic closures facility extends the BNF rule for
1292 @var{transformer spec} to allow a new keyword that introduces a
1293 low-level macro transformer:@refill
1294 @example
1295 @var{transformer spec} := (transformer @var{expression})
1296 @end example
1297
1298 Additionally, the following procedures are added:
1299 @lisp
1300 make-syntactic-closure
1301 capture-syntactic-environment
1302 identifier?
1303 identifier=?
1304 @end lisp
1305
1306 The description of the facility is divided into three parts. The first
1307 part defines basic terminology. The second part describes how macro
1308 transformers are defined. The third part describes the use of
1309 @dfn{identifiers}, which extend the syntactic closure mechanism to be
1310 compatible with @code{syntax-rules}.
1311
1312 @subsubsection Terminology
1313
1314 This section defines the concepts and data types used by the syntactic
1315 closures facility.
1316
1317 @itemize @bullet
1318
1319 @item @dfn{Forms} are the syntactic entities out of which programs are
1320 recursively constructed. A form is any expression, any definition, any
1321 syntactic keyword, or any syntactic closure. The variable name that
1322 appears in a @code{set!} special form is also a form. Examples of
1323 forms:@refill
1324 @lisp
1325 17
1326 #t
1327 car
1328 (+ x 4)
1329 (lambda (x) x)
1330 (define pi 3.14159)
1331 if
1332 define
1333 @end lisp
1334
1335 @item An @dfn{alias} is an alternate name for a given symbol. It can
1336 appear anywhere in a form that the symbol could be used, and when quoted
1337 it is replaced by the symbol; however, it does not satisfy the predicate
1338 @code{symbol?}. Macro transformers rarely distinguish symbols from
1339 aliases, referring to both as identifiers.
1340
1341 @item A @dfn{syntactic} environment maps identifiers to their
1342 meanings. More precisely, it determines whether an identifier is a
1343 syntactic keyword or a variable. If it is a keyword, the meaning is an
1344 interpretation for the form in which that keyword appears. If it is a
1345 variable, the meaning identifies which binding of that variable is
1346 referenced. In short, syntactic environments contain all of the
1347 contextual information necessary for interpreting the meaning of a
1348 particular form.
1349
1350 @item A @dfn{syntactic closure} consists of a form, a syntactic
1351 environment, and a list of identifiers. All identifiers in the form
1352 take their meaning from the syntactic environment, except those in the
1353 given list. The identifiers in the list are to have their meanings
1354 determined later. A syntactic closure may be used in any context in
1355 which its form could have been used. Since a syntactic closure is also
1356 a form, it may not be used in contexts where a form would be illegal.
1357 For example, a form may not appear as a clause in the cond special form.
1358 A syntactic closure appearing in a quoted structure is replaced by its
1359 form.
1360
1361 @end itemize
1362
1363 @subsubsection Transformer Definition
1364
1365 This section describes the @code{transformer} special form and the
1366 procedures @code{make-syntactic-closure} and
1367 @code{capture-syntactic-environment}.
1368
1369 @deffn Syntax transformer expression
1370
1371 Syntax: It is an error if this syntax occurs except as a
1372 @var{transformer spec}.
1373
1374 Semantics: The @var{expression} is evaluated in the standard transformer
1375 environment to yield a macro transformer as described below. This macro
1376 transformer is bound to a macro keyword by the special form in which the
1377 @code{transformer} expression appears (for example,
1378 @code{let-syntax}).
1379
1380 A @dfn{macro transformer} is a procedure that takes two arguments, a
1381 form and a syntactic environment, and returns a new form. The first
1382 argument, the @dfn{input form}, is the form in which the macro keyword
1383 occurred. The second argument, the @dfn{usage environment}, is the
1384 syntactic environment in which the input form occurred. The result of
1385 the transformer, the @dfn{output form}, is automatically closed in the
1386 @dfn{transformer environment}, which is the syntactic environment in
1387 which the @code{transformer} expression occurred.
1388
1389 For example, here is a definition of a push macro using
1390 @code{syntax-rules}:@refill
1391 @lisp
1392 (define-syntax push
1393 (syntax-rules ()
1394 ((push item list)
1395 (set! list (cons item list)))))
1396 @end lisp
1397
1398 Here is an equivalent definition using @code{transformer}:
1399 @lisp
1400 (define-syntax push
1401 (transformer
1402 (lambda (exp env)
1403 (let ((item
1404 (make-syntactic-closure env '() (cadr exp)))
1405 (list
1406 (make-syntactic-closure env '() (caddr exp))))
1407 `(set! ,list (cons ,item ,list))))))
1408 @end lisp
1409
1410 In this example, the identifiers @code{set!} and @code{cons} are closed
1411 in the transformer environment, and thus will not be affected by the
1412 meanings of those identifiers in the usage environment
1413 @code{env}.
1414
1415 Some macros may be non-hygienic by design. For example, the following
1416 defines a loop macro that implicitly binds @code{exit} to an escape
1417 procedure. The binding of @code{exit} is intended to capture free
1418 references to @code{exit} in the body of the loop, so @code{exit} must
1419 be left free when the body is closed:@refill
1420 @lisp
1421 (define-syntax loop
1422 (transformer
1423 (lambda (exp env)
1424 (let ((body (cdr exp)))
1425 `(call-with-current-continuation
1426 (lambda (exit)
1427 (let f ()
1428 ,@@(map (lambda (exp)
1429 (make-syntactic-closure env '(exit)
1430 exp))
1431 body)
1432 (f))))))))
1433 @end lisp
1434
1435 To assign meanings to the identifiers in a form, use
1436 @code{make-syntactic-closure} to close the form in a syntactic
1437 environment.
1438 @end deffn
1439
1440 @defun make-syntactic-closure environment free-names form
1441
1442 @var{environment} must be a syntactic environment, @var{free-names} must
1443 be a list of identifiers, and @var{form} must be a form.
1444 @code{make-syntactic-closure} constructs and returns a syntactic closure
1445 of @var{form} in @var{environment}, which can be used anywhere that
1446 @var{form} could have been used. All the identifiers used in
1447 @var{form}, except those explicitly excepted by @var{free-names}, obtain
1448 their meanings from @var{environment}.
1449
1450 Here is an example where @var{free-names} is something other than the
1451 empty list. It is instructive to compare the use of @var{free-names} in
1452 this example with its use in the @code{loop} example above: the examples
1453 are similar except for the source of the identifier being left
1454 free.
1455 @lisp
1456 (define-syntax let1
1457 (transformer
1458 (lambda (exp env)
1459 (let ((id (cadr exp))
1460 (init (caddr exp))
1461 (exp (cadddr exp)))
1462 `((lambda (,id)
1463 ,(make-syntactic-closure env (list id) exp))
1464 ,(make-syntactic-closure env '() init))))))
1465 @end lisp
1466
1467 @code{let1} is a simplified version of @code{let} that only binds a
1468 single identifier, and whose body consists of a single expression. When
1469 the body expression is syntactically closed in its original syntactic
1470 environment, the identifier that is to be bound by @code{let1} must be
1471 left free, so that it can be properly captured by the @code{lambda} in
1472 the output form.
1473
1474 To obtain a syntactic environment other than the usage environment, use
1475 @code{capture-syntactic-environment}.
1476 @end defun
1477
1478 @defun capture-syntactic-environment procedure
1479
1480 @code{capture-syntactic-environment} returns a form that will, when
1481 transformed, call @var{procedure} on the current syntactic environment.
1482 @var{procedure} should compute and return a new form to be transformed,
1483 in that same syntactic environment, in place of the form.
1484
1485 An example will make this clear. Suppose we wanted to define a simple
1486 @code{loop-until} keyword equivalent to@refill
1487 @lisp
1488 (define-syntax loop-until
1489 (syntax-rules ()
1490 ((loop-until id init test return step)
1491 (letrec ((loop
1492 (lambda (id)
1493 (if test return (loop step)))))
1494 (loop init)))))
1495 @end lisp
1496
1497 The following attempt at defining @code{loop-until} has a subtle bug:
1498 @lisp
1499 (define-syntax loop-until
1500 (transformer
1501 (lambda (exp env)
1502 (let ((id (cadr exp))
1503 (init (caddr exp))
1504 (test (cadddr exp))
1505 (return (cadddr (cdr exp)))
1506 (step (cadddr (cddr exp)))
1507 (close
1508 (lambda (exp free)
1509 (make-syntactic-closure env free exp))))
1510 `(letrec ((loop
1511 (lambda (,id)
1512 (if ,(close test (list id))
1513 ,(close return (list id))
1514 (loop ,(close step (list id)))))))
1515 (loop ,(close init '())))))))
1516 @end lisp
1517
1518 This definition appears to take all of the proper precautions to prevent
1519 unintended captures. It carefully closes the subexpressions in their
1520 original syntactic environment and it leaves the @code{id} identifier
1521 free in the @code{test}, @code{return}, and @code{step} expressions, so
1522 that it will be captured by the binding introduced by the @code{lambda}
1523 expression. Unfortunately it uses the identifiers @code{if} and
1524 @code{loop} within that @code{lambda} expression, so if the user of
1525 @code{loop-until} just happens to use, say, @code{if} for the
1526 identifier, it will be inadvertently captured.
1527
1528 The syntactic environment that @code{if} and @code{loop} want to be
1529 exposed to is the one just outside the @code{lambda} expression: before
1530 the user's identifier is added to the syntactic environment, but after
1531 the identifier loop has been added.
1532 @code{capture-syntactic-environment} captures exactly that environment
1533 as follows:@refill
1534 @lisp
1535 (define-syntax loop-until
1536 (transformer
1537 (lambda (exp env)
1538 (let ((id (cadr exp))
1539 (init (caddr exp))
1540 (test (cadddr exp))
1541 (return (cadddr (cdr exp)))
1542 (step (cadddr (cddr exp)))
1543 (close
1544 (lambda (exp free)
1545 (make-syntactic-closure env free exp))))
1546 `(letrec ((loop
1547 ,(capture-syntactic-environment
1548 (lambda (env)
1549 `(lambda (,id)
1550 (,(make-syntactic-closure env '() `if)
1551 ,(close test (list id))
1552 ,(close return (list id))
1553 (,(make-syntactic-closure env '()
1554 `loop)
1555 ,(close step (list id)))))))))
1556 (loop ,(close init '())))))))
1557 @end lisp
1558
1559 In this case, having captured the desired syntactic environment, it is
1560 convenient to construct syntactic closures of the identifiers @code{if}
1561 and the @code{loop} and use them in the body of the
1562 @code{lambda}.
1563
1564 A common use of @code{capture-syntactic-environment} is to get the
1565 transformer environment of a macro transformer:@refill
1566 @lisp
1567 (transformer
1568 (lambda (exp env)
1569 (capture-syntactic-environment
1570 (lambda (transformer-env)
1571 ...))))
1572 @end lisp
1573 @end defun
1574
1575 @subsubsection Identifiers
1576
1577 This section describes the procedures that create and manipulate
1578 identifiers. Previous syntactic closure proposals did not have an
1579 identifier data type -- they just used symbols. The identifier data
1580 type extends the syntactic closures facility to be compatible with the
1581 high-level @code{syntax-rules} facility.
1582
1583 As discussed earlier, an identifier is either a symbol or an
1584 @dfn{alias}. An alias is implemented as a syntactic closure whose
1585 @dfn{form} is an identifier:@refill
1586 @lisp
1587 (make-syntactic-closure env '() 'a)
1588 @result{} an @dfn{alias}
1589 @end lisp
1590
1591 Aliases are implemented as syntactic closures because they behave just
1592 like syntactic closures most of the time. The difference is that an
1593 alias may be bound to a new value (for example by @code{lambda} or
1594 @code{let-syntax}); other syntactic closures may not be used this way.
1595 If an alias is bound, then within the scope of that binding it is looked
1596 up in the syntactic environment just like any other identifier.
1597
1598 Aliases are used in the implementation of the high-level facility
1599 @code{syntax-rules}. A macro transformer created by @code{syntax-rules}
1600 uses a template to generate its output form, substituting subforms of
1601 the input form into the template. In a syntactic closures
1602 implementation, all of the symbols in the template are replaced by
1603 aliases closed in the transformer environment, while the output form
1604 itself is closed in the usage environment. This guarantees that the
1605 macro transformation is hygienic, without requiring the transformer to
1606 know the syntactic roles of the substituted input subforms.
1607
1608 @defun identifier? object
1609 Returns @code{#t} if @var{object} is an identifier, otherwise returns
1610 @code{#f}. Examples:@refill
1611 @lisp
1612 (identifier? 'a)
1613 @result{} #t
1614 (identifier? (make-syntactic-closure env '() 'a))
1615 @result{} #t
1616 (identifier? "a")
1617 @result{} #f
1618 (identifier? #\a)
1619 @result{} #f
1620 (identifier? 97)
1621 @result{} #f
1622 (identifier? #f)
1623 @result{} #f
1624 (identifier? '(a))
1625 @result{} #f
1626 (identifier? '#(a))
1627 @result{} #f
1628 @end lisp
1629
1630 The predicate @code{eq?} is used to determine if two identifers are
1631 ``the same''. Thus @code{eq?} can be used to compare identifiers
1632 exactly as it would be used to compare symbols. Often, though, it is
1633 useful to know whether two identifiers ``mean the same thing''. For
1634 example, the @code{cond} macro uses the symbol @code{else} to identify
1635 the final clause in the conditional. A macro transformer for
1636 @code{cond} cannot just look for the symbol @code{else}, because the
1637 @code{cond} form might be the output of another macro transformer that
1638 replaced the symbol @code{else} with an alias. Instead the transformer
1639 must look for an identifier that ``means the same thing'' in the usage
1640 environment as the symbol @code{else} means in the transformer
1641 environment.
1642 @end defun
1643
1644 @defun identifier=? environment1 identifier1 environment2 identifier2
1645 @var{environment1} and @var{environment2} must be syntactic
1646 environments, and @var{identifier1} and @var{identifier2} must be
1647 identifiers. @code{identifier=?} returns @code{#t} if the meaning of
1648 @var{identifier1} in @var{environment1} is the same as that of
1649 @var{identifier2} in @var{environment2}, otherwise it returns @code{#f}.
1650 Examples:@refill
1651
1652 @lisp
1653 (let-syntax
1654 ((foo
1655 (transformer
1656 (lambda (form env)
1657 (capture-syntactic-environment
1658 (lambda (transformer-env)
1659 (identifier=? transformer-env 'x env 'x)))))))
1660 (list (foo)
1661 (let ((x 3))
1662 (foo))))
1663 @result{} (#t #f)
1664 @end lisp
1665
1666 @lisp
1667 (let-syntax ((bar foo))
1668 (let-syntax
1669 ((foo
1670 (transformer
1671 (lambda (form env)
1672 (capture-syntactic-environment
1673 (lambda (transformer-env)
1674 (identifier=? transformer-env 'foo
1675 env (cadr form))))))))
1676 (list (foo foo)
1677 (foobar))))
1678 @result{} (#f #t)
1679 @end lisp
1680 @end defun
1681
1682 @subsubsection Acknowledgements
1683
1684 The syntactic closures facility was invented by Alan Bawden and Jonathan
1685 Rees. The use of aliases to implement @code{syntax-rules} was invented
1686 by Alan Bawden (who prefers to call them @dfn{synthetic names}). Much
1687 of this proposal is derived from an earlier proposal by Alan
1688 Bawden.
1689
1690
1691
1692
1693
1694 @node Syntax-Case Macros, Fluid-Let, Syntactic Closures, Scheme Syntax Extension Packages
1695 @section Syntax-Case Macros
1696
1697 @code{(require 'syntax-case)}
1698 @ftindex syntax-case
1699
1700 @defun macro:expand expression
1701 @defunx syncase:expand expression
1702 Returns scheme code with the macros and derived expression types of
1703 @var{expression} expanded to primitive expression types.
1704 @end defun
1705
1706 @defun macro:eval expression
1707 @defunx syncase:eval expression
1708 @code{macro:eval} returns the value of @var{expression} in the current
1709 top level environment. @var{expression} can contain macro definitions.
1710 Side effects of @var{expression} will affect the top level
1711 environment.
1712 @end defun
1713
1714 @deffn Procedure macro:load filename
1715 @deffnx Procedure syncase:load filename
1716 @var{filename} should be a string. If filename names an existing file,
1717 the @code{macro:load} procedure reads Scheme source code expressions and
1718 definitions from the file and evaluates them sequentially. These
1719 source code expressions and definitions may contain macro definitions.
1720 The @code{macro:load} procedure does not affect the values returned by
1721 @code{current-input-port} and @code{current-output-port}.
1722 @end deffn
1723
1724 This is version 2.1 of @code{syntax-case}, the low-level macro facility
1725 proposed and implemented by Robert Hieb and R. Kent Dybvig.
1726
1727 This version is further adapted by Harald Hanche-Olsen
1728 <hanche@@imf.unit.no> to make it compatible with, and easily usable
1729 with, SLIB. Mainly, these adaptations consisted of:
1730
1731 @itemize @bullet
1732 @item
1733 Removing white space from @file{expand.pp} to save space in the
1734 distribution. This file is not meant for human readers anyway@dots{}
1735
1736 @item
1737 Removed a couple of Chez scheme dependencies.
1738
1739 @item
1740 Renamed global variables used to minimize the possibility of name
1741 conflicts.
1742
1743 @item
1744 Adding an SLIB-specific initialization file.
1745
1746 @item
1747 Removing a couple extra files, most notably the documentation (but see
1748 below).
1749 @end itemize
1750
1751 If you wish, you can see exactly what changes were done by reading the
1752 shell script in the file @file{syncase.sh}.
1753
1754 The two PostScript files were omitted in order to not burden the SLIB
1755 distribution with them. If you do intend to use @code{syntax-case},
1756 however, you should get these files and print them out on a PostScript
1757 printer. They are available with the original @code{syntax-case}
1758 distribution by anonymous FTP in
1759 @file{cs.indiana.edu:/pub/scheme/syntax-case}.
1760
1761 In order to use syntax-case from an interactive top level, execute:
1762 @lisp
1763 (require 'syntax-case)
1764 @ftindex syntax-case
1765 (require 'repl)
1766 @ftindex repl
1767 (repl:top-level macro:eval)
1768 @end lisp
1769 See the section Repl (@pxref{Repl}) for more information.
1770
1771 To check operation of syntax-case get
1772 @file{cs.indiana.edu:/pub/scheme/syntax-case}, and type
1773 @lisp
1774 (require 'syntax-case)
1775 @ftindex syntax-case
1776 (syncase:sanity-check)
1777 @end lisp
1778
1779 Beware that @code{syntax-case} takes a long time to load -- about 20s on
1780 a SPARCstation SLC (with SCM) and about 90s on a Macintosh SE/30 (with
1781 Gambit).
1782
1783 @subsection Notes
1784
1785 All R4RS syntactic forms are defined, including @code{delay}. Along
1786 with @code{delay} are simple definitions for @code{make-promise} (into
1787 which @code{delay} expressions expand) and @code{force}.
1788
1789 @code{syntax-rules} and @code{with-syntax} (described in @cite{TR356})
1790 are defined.
1791
1792 @code{syntax-case} is actually defined as a macro that expands into
1793 calls to the procedure @code{syntax-dispatch} and the core form
1794 @code{syntax-lambda}; do not redefine these names.
1795
1796 Several other top-level bindings not documented in TR356 are created:
1797 @itemize @bullet
1798 @item the ``hooks'' in @file{hooks.ss}
1799 @item the @code{build-} procedures in @file{output.ss}
1800 @item @code{expand-syntax} (the expander)
1801 @end itemize
1802
1803 The syntax of define has been extended to allow @code{(define @var{id})},
1804 which assigns @var{id} to some unspecified value.
1805
1806 We have attempted to maintain R4RS compatibility where possible. The
1807 incompatibilities should be confined to @file{hooks.ss}. Please let us
1808 know if there is some incompatibility that is not flagged as such.
1809
1810 Send bug reports, comments, suggestions, and questions to Kent Dybvig
1811 (dyb@@iuvax.cs.indiana.edu).
1812
1813 @subsection Note from maintainer
1814
1815 Included with the @code{syntax-case} files was @file{structure.scm}
1816 which defines a macro @code{define-structure}. There is no
1817 documentation for this macro and it is not used by any code in SLIB.
1818
1819 @node Fluid-Let, Yasos, Syntax-Case Macros, Scheme Syntax Extension Packages
1820 @section Fluid-Let
1821
1822 @code{(require 'fluid-let)}
1823 @ftindex fluid-let
1824
1825 @deffn Syntax fluid-let @code{(@var{bindings} @dots{})} @var{forms}@dots{}
1826 @end deffn
1827 @lisp
1828 (fluid-let ((@var{variable} @var{init}) @dots{})
1829 @var{expression} @var{expression} @dots{})
1830 @end lisp
1831
1832 The @var{init}s are evaluated in the current environment (in some
1833 unspecified order), the current values of the @var{variable}s are saved,
1834 the results are assigned to the @var{variable}s, the @var{expression}s
1835 are evaluated sequentially in the current environment, the
1836 @var{variable}s are restored to their original values, and the value of
1837 the last @var{expression} is returned.
1838
1839 The syntax of this special form is similar to that of @code{let}, but
1840 @code{fluid-let} temporarily rebinds existing @var{variable}s. Unlike
1841 @code{let}, @code{fluid-let} creates no new bindings; instead it
1842 @emph{assigns} the values of each @var{init} to the binding (determined
1843 by the rules of lexical scoping) of its corresponding
1844 @var{variable}.
1845
1846
1847 @node Yasos, , Fluid-Let, Scheme Syntax Extension Packages
1848 @section Yasos
1849
1850 @c Much of the documentation in this section was written by Dave Love
1851 @c (d.love@dl.ac.uk) -- don't blame Ken Dickey for its faults.
1852 @c but we can blame him for not writing it!
1853
1854 @code{(require 'oop)} or @code{(require 'yasos)}
1855 @ftindex oop
1856 @ftindex yasos
1857
1858 `Yet Another Scheme Object System' is a simple object system for Scheme
1859 based on the paper by Norman Adams and Jonathan Rees: @cite{Object
1860 Oriented Programming in Scheme}, Proceedings of the 1988 ACM Conference
1861 on LISP and Functional Programming, July 1988 [ACM #552880].
1862
1863 Another reference is:
1864
1865 Ken Dickey.
1866 @ifset html
1867 <A HREF="ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/swob.txt">
1868 @end ifset
1869 Scheming with Objects
1870 @ifset html
1871 </A>
1872 @end ifset
1873 @cite{AI Expert} Volume 7, Number 10 (October 1992), pp. 24-33.
1874
1875 @menu
1876 * Yasos terms:: Definitions and disclaimer.
1877 * Yasos interface:: The Yasos macros and procedures.
1878 * Setters:: Dylan-like setters in Yasos.
1879 * Yasos examples:: Usage of Yasos and setters.
1880 @end menu
1881
1882 @node Yasos terms, Yasos interface, Yasos, Yasos
1883 @subsection Terms
1884
1885 @table @asis
1886 @item @dfn{Object}
1887 Any Scheme data object.
1888
1889 @item @dfn{Instance}
1890 An instance of the OO system; an @dfn{object}.
1891
1892 @item @dfn{Operation}
1893 A @var{method}.
1894 @end table
1895
1896 @table @emph
1897 @item Notes:
1898 The object system supports multiple inheritance. An instance can
1899 inherit from 0 or more ancestors. In the case of multiple inherited
1900 operations with the same identity, the operation used is that from the
1901 first ancestor which contains it (in the ancestor @code{let}). An
1902 operation may be applied to any Scheme data object---not just instances.
1903 As code which creates instances is just code, there are no @dfn{classes}
1904 and no meta-@var{anything}. Method dispatch is by a procedure call a la
1905 CLOS rather than by @code{send} syntax a la Smalltalk.
1906
1907 @item Disclaimer:
1908 There are a number of optimizations which can be made. This
1909 implementation is expository (although performance should be quite
1910 reasonable). See the L&FP paper for some suggestions.
1911 @end table
1912
1913
1914
1915
1916
1917 @node Yasos interface, Setters, Yasos terms, Yasos
1918 @subsection Interface
1919
1920 @deffn Syntax define-operation @code{(}opname self arg @dots{}@code{)} @var{default-body}
1921 Defines a default behavior for data objects which don't handle the
1922 operation @var{opname}. The default behavior (for an empty
1923 @var{default-body}) is to generate an error.
1924 @end deffn
1925
1926 @deffn Syntax define-predicate opname?
1927 Defines a predicate @var{opname?}, usually used for determining the
1928 @dfn{type} of an object, such that @code{(@var{opname?} @var{object})}
1929 returns @code{#t} if @var{object} has an operation @var{opname?} and
1930 @code{#f} otherwise.
1931 @end deffn
1932
1933 @deffn Syntax object @code{((@var{name} @var{self} @var{arg} @dots{}) @var{body})} @dots{}
1934 Returns an object (an instance of the object system) with operations.
1935 Invoking @code{(@var{name} @var{object} @var{arg} @dots{}} executes the
1936 @var{body} of the @var{object} with @var{self} bound to @var{object} and
1937 with argument(s) @var{arg}@dots{}.
1938 @end deffn
1939
1940 @deffn Syntax object-with-ancestors @code{((}ancestor1 init1@code{)} @dots{}@code{)} operation @dots{}
1941 A @code{let}-like form of @code{object} for multiple inheritance. It
1942 returns an object inheriting the behaviour of @var{ancestor1} etc. An
1943 operation will be invoked in an ancestor if the object itself does not
1944 provide such a method. In the case of multiple inherited operations
1945 with the same identity, the operation used is the one found in the first
1946 ancestor in the ancestor list.
1947 @end deffn
1948
1949 @deffn Syntax operate-as component operation self arg @dots{}
1950 Used in an operation definition (of @var{self}) to invoke the
1951 @var{operation} in an ancestor @var{component} but maintain the object's
1952 identity. Also known as ``send-to-super''.
1953 @end deffn
1954
1955 @deffn Procedure print obj port
1956 A default @code{print} operation is provided which is just @code{(format
1957 @var{port} @var{obj})} (@pxref{Format}) for non-instances and prints
1958 @var{obj} preceded by @samp{#<INSTANCE>} for instances.
1959 @end deffn
1960
1961 @defun size obj
1962 The default method returns the number of elements in @var{obj} if it is
1963 a vector, string or list, @code{2} for a pair, @code{1} for a character
1964 and by default id an error otherwise. Objects such as collections
1965 (@pxref{Collections}) may override the default in an obvious way.
1966 @end defun
1967
1968
1969
1970
1971
1972 @node Setters, Yasos examples, Yasos interface, Yasos
1973 @subsection Setters
1974
1975 @dfn{Setters} implement @dfn{generalized locations} for objects
1976 associated with some sort of mutable state. A @dfn{getter} operation
1977 retrieves a value from a generalized location and the corresponding
1978 setter operation stores a value into the location. Only the getter is
1979 named -- the setter is specified by a procedure call as below. (Dylan
1980 uses special syntax.) Typically, but not necessarily, getters are
1981 access operations to extract values from Yasos objects (@pxref{Yasos}).
1982 Several setters are predefined, corresponding to getters @code{car},
1983 @code{cdr}, @code{string-ref} and @code{vector-ref} e.g., @code{(setter
1984 car)} is equivalent to @code{set-car!}.
1985
1986 This implementation of setters is similar to that in Dylan(TM)
1987 (@cite{Dylan: An object-oriented dynamic language}, Apple Computer
1988 Eastern Research and Technology). Common LISP provides similar
1989 facilities through @code{setf}.
1990
1991 @defun setter getter
1992 Returns the setter for the procedure @var{getter}. E.g., since
1993 @code{string-ref} is the getter corresponding to a setter which is
1994 actually @code{string-set!}:
1995 @example
1996 (define foo "foo")
1997 ((setter string-ref) foo 0 #\F) ; set element 0 of foo
1998 foo @result{} "Foo"
1999 @end example
2000 @end defun
2001
2002 @deffn Syntax set place new-value
2003 If @var{place} is a variable name, @code{set} is equivalent to
2004 @code{set!}. Otherwise, @var{place} must have the form of a procedure
2005 call, where the procedure name refers to a getter and the call indicates
2006 an accessible generalized location, i.e., the call would return a value.
2007 The return value of @code{set} is usually unspecified unless used with a
2008 setter whose definition guarantees to return a useful value.
2009 @example
2010 (set (string-ref foo 2) #\O) ; generalized location with getter
2011 foo @result{} "FoO"
2012 (set foo "foo") ; like set!
2013 foo @result{} "foo"
2014 @end example
2015 @end deffn
2016
2017 @deffn Procedure add-setter getter setter
2018 Add procedures @var{getter} and @var{setter} to the (inaccessible) list
2019 of valid setter/getter pairs. @var{setter} implements the store
2020 operation corresponding to the @var{getter} access operation for the
2021 relevant state. The return value is unspecified.
2022 @end deffn
2023
2024 @deffn Procedure remove-setter-for getter
2025 Removes the setter corresponding to the specified @var{getter} from the
2026 list of valid setters. The return value is unspecified.
2027 @end deffn
2028
2029 @deffn Syntax define-access-operation getter-name
2030 Shorthand for a Yasos @code{define-operation} defining an operation
2031 @var{getter-name} that objects may support to return the value of some
2032 mutable state. The default operation is to signal an error. The return
2033 value is unspecified.
2034 @end deffn
2035
2036
2037
2038
2039
2040 @node Yasos examples, , Setters, Yasos
2041 @subsection Examples
2042
2043 @lisp
2044 ;;; These definitions for PRINT and SIZE are
2045 ;;; already supplied by
2046 (require 'yasos)
2047
2048 (define-operation (print obj port)
2049 (format port
2050 (if (instance? obj) "#<instance>" "~s")
2051 obj))
2052
2053 (define-operation (size obj)
2054 (cond
2055 ((vector? obj) (vector-length obj))
2056 ((list? obj) (length obj))
2057 ((pair? obj) 2)
2058 ((string? obj) (string-length obj))
2059 ((char? obj) 1)
2060 (else
2061 (error "Operation not supported: size" obj))))
2062
2063 (define-predicate cell?)
2064 (define-operation (fetch obj))
2065 (define-operation (store! obj newValue))
2066
2067 (define (make-cell value)
2068 (object
2069 ((cell? self) #t)
2070 ((fetch self) value)
2071 ((store! self newValue)
2072 (set! value newValue)
2073 newValue)
2074 ((size self) 1)
2075 ((print self port)
2076 (format port "#<Cell: ~s>" (fetch self)))))
2077
2078 (define-operation (discard obj value)
2079 (format #t "Discarding ~s~%" value))
2080
2081 (define (make-filtered-cell value filter)
2082 (object-with-ancestors
2083 ((cell (make-cell value)))
2084 ((store! self newValue)
2085 (if (filter newValue)
2086 (store! cell newValue)
2087 (discard self newValue)))))
2088
2089 (define-predicate array?)
2090 (define-operation (array-ref array index))
2091 (define-operation (array-set! array index value))
2092
2093 (define (make-array num-slots)
2094 (let ((anArray (make-vector num-slots)))
2095 (object
2096 ((array? self) #t)
2097 ((size self) num-slots)
2098 ((array-ref self index)
2099 (vector-ref anArray index))
2100 ((array-set! self index newValue)
2101 (vector-set! anArray index newValue))
2102 ((print self port)
2103 (format port "#<Array ~s>" (size self))))))
2104
2105 (define-operation (position obj))
2106 (define-operation (discarded-value obj))
2107
2108 (define (make-cell-with-history value filter size)
2109 (let ((pos 0) (most-recent-discard #f))
2110 (object-with-ancestors
2111 ((cell (make-filtered-call value filter))
2112 (sequence (make-array size)))
2113 ((array? self) #f)
2114 ((position self) pos)
2115 ((store! self newValue)
2116 (operate-as cell store! self newValue)
2117 (array-set! self pos newValue)
2118 (set! pos (+ pos 1)))
2119 ((discard self value)
2120 (set! most-recent-discard value))
2121 ((discarded-value self) most-recent-discard)
2122 ((print self port)
2123 (format port "#<Cell-with-history ~s>"
2124 (fetch self))))))
2125
2126 (define-access-operation fetch)
2127 (add-setter fetch store!)
2128 (define foo (make-cell 1))
2129 (print foo #f)
2130 @result{} "#<Cell: 1>"
2131 (set (fetch foo) 2)
2132 @result{}
2133 (print foo #f)
2134 @result{} "#<Cell: 2>"
2135 (fetch foo)
2136 @result{} 2
2137 @end lisp
2138
2139 @node Textual Conversion Packages, Mathematical Packages, Scheme Syntax Extension Packages, Top
2140 @chapter Textual Conversion Packages
2141
2142 @menu
2143 * Precedence Parsing::
2144 * Format:: Common-Lisp Format
2145 * Standard Formatted I/O:: Posix printf and scanf
2146 * Programs and Arguments::
2147 * HTML::
2148 * HTML Tables:: Databases meet HTML
2149 * HTTP and CGI:: Serve WWW sites
2150 * URI:: Uniform Resource Identifier
2151 * Printing Scheme:: Nicely
2152 * Time and Date::
2153 * Vector Graphics::
2154 * Schmooz:: Documentation markup for Scheme programs
2155 @end menu
2156
2157
2158 @node Precedence Parsing, Format, Textual Conversion Packages, Textual Conversion Packages
2159 @section Precedence Parsing
2160
2161 @code{(require 'precedence-parse)} or @code{(require 'parse)}
2162 @ftindex parse
2163 @ftindex precedence
2164
2165 @noindent
2166 This package implements:
2167
2168 @itemize @bullet
2169 @item
2170 a Pratt style precedence parser;
2171 @item
2172 a @dfn{tokenizer} which congeals tokens according to assigned classes of
2173 constituent characters;
2174 @item
2175 procedures giving direct control of parser rulesets;
2176 @item
2177 procedures for higher level specification of rulesets.
2178 @end itemize
2179
2180 @menu
2181 * Precedence Parsing Overview::
2182 * Ruleset Definition and Use::
2183 * Token definition::
2184 * Nud and Led Definition::
2185 * Grammar Rule Definition::
2186 @end menu
2187
2188 @node Precedence Parsing Overview, Ruleset Definition and Use, Precedence Parsing, Precedence Parsing
2189 @subsection Precedence Parsing Overview
2190
2191 @noindent
2192 This package offers improvements over previous parsers.
2193
2194 @itemize @bullet
2195 @item
2196 Common computer language constructs are concisely specified.
2197 @item
2198 Grammars can be changed dynamically. Operators can be assigned
2199 different meanings within a lexical context.
2200 @item
2201 Rulesets don't need compilation. Grammars can be changed incrementally.
2202 @item
2203 Operator precedence is specified by integers.
2204 @item
2205 All possibilities of bad input are handled @footnote{How do I know this?
2206 I parsed 250kbyte of random input (an e-mail file) with a non-trivial
2207 grammar utilizing all constructs.} and return as much structure as was
2208 parsed when the error occured; The symbol @code{?} is substituted for
2209 missing input.
2210 @end itemize
2211
2212 @noindent
2213 Here are the higher-level syntax types and an example of each.
2214 Precedence considerations are omitted for clarity. See @ref{Grammar
2215 Rule Definition} for full details.
2216 @deftp Grammar nofix bye exit
2217 @example
2218 bye
2219 @end example
2220 calls the function @code{exit} with no arguments.
2221 @end deftp
2222 @deftp Grammar prefix - negate
2223 @example
2224 - 42
2225 @end example
2226 Calls the function @code{negate} with the argument @code{42}.
2227 @end deftp
2228 @deftp Grammar infix - difference
2229 @example
2230 x - y
2231 @end example
2232 Calls the function @code{difference} with arguments @code{x} and @code{y}.
2233 @end deftp
2234 @deftp Grammar nary + sum
2235 @example
2236 x + y + z
2237 @end example
2238 Calls the function @code{sum} with arguments @code{x}, @code{y}, and
2239 @code{y}.
2240 @end deftp
2241 @deftp Grammar postfix ! factorial
2242 @example
2243 5 !
2244 @end example
2245 Calls the function @code{factorial} with the argument @code{5}.
2246 @end deftp
2247 @deftp Grammar prestfix set set!
2248 @example
2249 set foo bar
2250 @end example
2251 Calls the function @code{set!} with the arguments @code{foo} and
2252 @code{bar}.
2253 @end deftp
2254 @deftp Grammar commentfix /* */
2255 @example
2256 /* almost any text here */
2257 @end example
2258 Ignores the comment delimited by @code{/*} and @code{*/}.
2259 @end deftp
2260 @deftp Grammar matchfix @{ list @}
2261 @example
2262 @{0, 1, 2@}
2263 @end example
2264 Calls the function @code{list} with the arguments @code{0}, @code{1},
2265 and @code{2}.
2266 @end deftp
2267 @deftp Grammar inmatchfix ( funcall )
2268 @example
2269 f(x, y)
2270 @end example
2271 Calls the function @code{funcall} with the arguments @code{f}, @code{x},
2272 and @code{y}.
2273 @end deftp
2274 @deftp Grammar delim ;
2275 @example
2276 set foo bar;
2277 @end example
2278 delimits the extent of the restfix operator @code{set}.
2279 @end deftp
2280
2281
2282 @node Ruleset Definition and Use, Token definition, Precedence Parsing Overview, Precedence Parsing
2283 @subsection Ruleset Definition and Use
2284
2285 @defvar *syn-defs*
2286 A grammar is built by one or more calls to @code{prec:define-grammar}.
2287 The rules are appended to @var{*syn-defs*}. The value of
2288 @var{*syn-defs*} is the grammar suitable for passing as an argument to
2289 @code{prec:parse}.
2290 @end defvar
2291
2292 @defvr Constant *syn-ignore-whitespace*
2293 Is a nearly empty grammar with whitespace characters set to group 0,
2294 which means they will not be made into tokens. Most rulesets will want
2295 to start with @code{*syn-ignore-whitespace*}
2296 @end defvr
2297
2298 @noindent
2299 In order to start defining a grammar, either
2300
2301 @example
2302 (set! *syn-defs* '())
2303 @end example
2304 @noindent
2305 or
2306
2307 @example
2308 (set! *syn-defs* *syn-ignore-whitespace*)
2309 @end example
2310
2311 @defun prec:define-grammar rule1 @dots{}
2312 Appends @var{rule1} @dots{} to @var{*syn-defs*}.
2313 @code{prec:define-grammar} is used to define both the character classes
2314 and rules for tokens.
2315 @end defun
2316
2317 @noindent
2318 Once your grammar is defined, save the value of @code{*syn-defs*} in a
2319 variable (for use when calling @code{prec:parse}).
2320
2321 @example
2322 (define my-ruleset *syn-defs*)
2323 @end example
2324
2325 @defun prec:parse ruleset delim
2326 @defunx prec:parse ruleset delim port
2327 The @var{ruleset} argument must be a list of rules as constructed by
2328 @code{prec:define-grammar} and extracted from @var{*syn-defs*}.
2329
2330 The token @var{delim} may be a character, symbol, or string. A
2331 character @var{delim} argument will match only a character token; i.e. a
2332 character for which no token-group is assigned. A symbols or string
2333 will match only a token string; i.e. a token resulting from a token
2334 group.
2335
2336 @code{prec:parse} reads a @var{ruleset} grammar expression delimited
2337 by @var{delim} from the given input @var{port}. @code{prec:parse}
2338 returns the next object parsable from the given input @var{port},
2339 updating @var{port} to point to the first character past the end of the
2340 external representation of the object.
2341
2342 If an end of file is encountered in the input before any characters are
2343 found that can begin an object, then an end of file object is returned.
2344 If a delimiter (such as @var{delim}) is found before any characters are
2345 found that can begin an object, then @code{#f} is returned.
2346
2347 The @var{port} argument may be omitted, in which case it defaults to the
2348 value returned by @code{current-input-port}. It is an error to parse
2349 from a closed port.
2350 @findex current-input-port
2351 @end defun
2352
2353 @node Token definition, Nud and Led Definition, Ruleset Definition and Use, Precedence Parsing
2354 @subsection Token definition
2355
2356 @defun tok:char-group group chars chars-proc
2357 The argument @var{chars} may be a single character, a list of
2358 characters, or a string. Each character in @var{chars} is treated as
2359 though @code{tok:char-group} was called with that character alone.
2360
2361 The argument @var{chars-proc} must be a procedure of one argument, a
2362 list of characters. After @code{tokenize} has finished
2363 accumulating the characters for a token, it calls @var{chars-proc} with
2364 the list of characters. The value returned is the token which
2365 @code{tokenize} returns.
2366
2367 The argument @var{group} may be an exact integer or a procedure of one
2368 character argument. The following discussion concerns the treatment
2369 which the tokenizing routine, @code{tokenize}, will accord to characters
2370 on the basis of their groups.
2371
2372 When @var{group} is a non-zero integer, characters whose group number is
2373 equal to or exactly one less than @var{group} will continue to
2374 accumulate. Any other character causes the accumulation to stop (until
2375 a new token is to be read).
2376
2377 The @var{group} of zero is special. These characters are ignored when
2378 parsed pending a token, and stop the accumulation of token characters
2379 when the accumulation has already begun. Whitespace characters are
2380 usually put in group 0.
2381
2382 If @var{group} is a procedure, then, when triggerd by the occurence of
2383 an initial (no accumulation) @var{chars} character, this procedure will
2384 be repeatedly called with each successive character from the input
2385 stream until the @var{group} procedure returns a non-false value.
2386 @end defun
2387
2388 @noindent
2389 The following convenient constants are provided for use with
2390 @code{tok:char-group}.
2391
2392 @defvr Constant tok:decimal-digits
2393 Is the string @code{"0123456789"}.
2394 @end defvr
2395 @defvr Constant tok:upper-case
2396 Is the string consisting of all upper-case letters
2397 ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
2398 @end defvr
2399 @defvr Constant tok:lower-case
2400 Is the string consisting of all lower-case letters
2401 ("abcdefghijklmnopqrstuvwxyz").
2402 @end defvr
2403 @defvr Constant tok:whitespaces
2404 Is the string consisting of all characters between 0 and 255 for which
2405 @code{char-whitespace?} returns true.
2406 @end defvr
2407
2408
2409 @node Nud and Led Definition, Grammar Rule Definition, Token definition, Precedence Parsing
2410 @subsection Nud and Led Definition
2411
2412 This section describes advanced features. You can skip this section on
2413 first reading.
2414
2415 @noindent
2416 The @dfn{Null Denotation} (or @dfn{nud})
2417 @cindex Null Denotation, nud
2418 of a token is the procedure and arguments applying for that token when
2419 @dfn{Left}, an unclaimed parsed expression is not extant.
2420
2421 @noindent
2422 The @dfn{Left Denotation} (or @dfn{led})
2423 @cindex Left Denotation, led
2424 of a token is the procedure, arguments, and lbp applying for that token
2425 when there is a @dfn{Left}, an unclaimed parsed expression.
2426
2427 @noindent
2428 In his paper,
2429
2430 @quotation
2431 Pratt, V. R.
2432 Top Down Operator Precendence.
2433 @cite{SIGACT/SIGPLAN Symposium on Principles of Programming Languages},
2434 Boston, 1973, pages 41-51
2435 @end quotation
2436
2437 the @dfn{left binding power} (or @dfn{lbp}) was an independent property
2438 of tokens. I think this was done in order to allow tokens with NUDs but
2439 not LEDs to also be used as delimiters, which was a problem for
2440 statically defined syntaxes. It turns out that @emph{dynamically
2441 binding} NUDs and LEDs allows them independence.
2442
2443 @noindent
2444 For the rule-defining procedures that follow, the variable @var{tk} may
2445 be a character, string, or symbol, or a list composed of characters,
2446 strings, and symbols. Each element of @var{tk} is treated as though the
2447 procedure were called for each element.
2448
2449 @noindent
2450 Character @var{tk} arguments will match only character tokens;
2451 i.e. characters for which no token-group is assigned. Symbols and
2452 strings will both match token strings; i.e. tokens resulting from token
2453 groups.
2454
2455 @defun prec:make-nud tk sop arg1 @dots{}
2456 Returns a rule specifying that @var{sop} be called when @var{tk} is
2457 parsed. If @var{sop} is a procedure, it is called with @var{tk} and
2458 @var{arg1} @dots{} as its arguments; the resulting value is incorporated
2459 into the expression being built. Otherwise, @code{(list @var{sop}
2460 @var{arg1} @dots{})} is incorporated.
2461 @end defun
2462
2463 @noindent
2464 If no NUD has been defined for a token; then if that token is a string,
2465 it is converted to a symbol and returned; if not a string, the token is
2466 returned.
2467
2468 @defun prec:make-led tk sop arg1 @dots{}
2469 Returns a rule specifying that @var{sop} be called when @var{tk} is
2470 parsed and @var{left} has an unclaimed parsed expression. If @var{sop}
2471 is a procedure, it is called with @var{left}, @var{tk}, and @var{arg1}
2472 @dots{} as its arguments; the resulting value is incorporated into the
2473 expression being built. Otherwise, @var{left} is incorporated.
2474 @end defun
2475
2476 @noindent
2477 If no LED has been defined for a token, and @var{left} is set, the
2478 parser issues a warning.
2479
2480 @node Grammar Rule Definition, , Nud and Led Definition, Precedence Parsing
2481 @subsection Grammar Rule Definition
2482
2483 @noindent
2484 Here are procedures for defining rules for the syntax types introduced
2485 in @ref{Precedence Parsing Overview}.
2486
2487 @noindent
2488 For the rule-defining procedures that follow, the variable @var{tk} may
2489 be a character, string, or symbol, or a list composed of characters,
2490 strings, and symbols. Each element of @var{tk} is treated as though the
2491 procedure were called for each element.
2492
2493 @noindent
2494 For procedures prec:delim, @dots{}, prec:prestfix, if the @var{sop}
2495 argument is @code{#f}, then the token which triggered this rule is
2496 converted to a symbol and returned. A false @var{sop} argument to the
2497 procedures prec:commentfix, prec:matchfix, or prec:inmatchfix has a
2498 different meaning.
2499
2500 @noindent
2501 Character @var{tk} arguments will match only character tokens;
2502 i.e. characters for which no token-group is assigned. Symbols and
2503 strings will both match token strings; i.e. tokens resulting from token
2504 groups.
2505
2506 @defun prec:delim tk
2507 Returns a rule specifying that @var{tk} should not be returned from
2508 parsing; i.e. @var{tk}'s function is purely syntactic. The end-of-file
2509 is always treated as a delimiter.
2510 @end defun
2511
2512 @defun prec:nofix tk sop
2513 Returns a rule specifying the following actions take place when @var{tk}
2514 is parsed:
2515 @itemize @bullet
2516 @item
2517 If @var{sop} is a procedure, it is called with no arguments; the
2518 resulting value is incorporated into the expression being built.
2519 Otherwise, the list of @var{sop} is incorporated.
2520 @end itemize
2521 @end defun
2522
2523 @defun prec:prefix tk sop bp rule1 @dots{}
2524 Returns a rule specifying the following actions take place when @var{tk}
2525 is parsed:
2526 @itemize @bullet
2527 @item
2528 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2529 rules currently in effect.
2530 @item
2531 @code{prec:parse1} is called with binding-power @var{bp}.
2532 @item
2533 If @var{sop} is a procedure, it is called with the expression returned
2534 from @code{prec:parse1}; the resulting value is incorporated into the
2535 expression being built. Otherwise, the list of @var{sop} and the
2536 expression returned from @code{prec:parse1} is incorporated.
2537 @item
2538 The ruleset in effect before @var{tk} was parsed is restored;
2539 @var{rule1} @dots{} are forgotten.
2540 @end itemize
2541 @end defun
2542
2543 @defun prec:infix tk sop lbp bp rule1 @dots{}
2544 Returns a rule declaring the left-binding-precedence of the token
2545 @var{tk} is @var{lbp} and specifying the following actions take place
2546 when @var{tk} is parsed:
2547 @itemize @bullet
2548 @item
2549 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2550 rules currently in effect.
2551 @item
2552 One expression is parsed with binding-power @var{lbp}. If instead a
2553 delimiter is encountered, a warning is issued.
2554 @item
2555 If @var{sop} is a procedure, it is applied to the list of @var{left} and
2556 the parsed expression; the resulting value is incorporated into the
2557 expression being built. Otherwise, the list of @var{sop}, the
2558 @var{left} expression, and the parsed expression is incorporated.
2559 @item
2560 The ruleset in effect before @var{tk} was parsed is restored;
2561 @var{rule1} @dots{} are forgotten.
2562 @end itemize
2563 @end defun
2564
2565 @defun prec:nary tk sop bp
2566 Returns a rule declaring the left-binding-precedence of the token
2567 @var{tk} is @var{bp} and specifying the following actions take place
2568 when @var{tk} is parsed:
2569 @itemize @bullet
2570 @item
2571 Expressions are parsed with binding-power @var{bp} as far as they are
2572 interleaved with the token @var{tk}.
2573 @item
2574 If @var{sop} is a procedure, it is applied to the list of @var{left} and
2575 the parsed expressions; the resulting value is incorporated into the
2576 expression being built. Otherwise, the list of @var{sop}, the
2577 @var{left} expression, and the parsed expressions is incorporated.
2578 @end itemize
2579 @end defun
2580
2581 @defun prec:postfix tk sop lbp
2582 Returns a rule declaring the left-binding-precedence of the token
2583 @var{tk} is @var{lbp} and specifying the following actions take place
2584 when @var{tk} is parsed:
2585 @itemize @bullet
2586 @item
2587 If @var{sop} is a procedure, it is called with the @var{left} expression;
2588 the resulting value is incorporated into the expression being built.
2589 Otherwise, the list of @var{sop} and the @var{left} expression is
2590 incorporated.
2591 @end itemize
2592 @end defun
2593
2594 @defun prec:prestfix tk sop bp rule1 @dots{}
2595 Returns a rule specifying the following actions take place when @var{tk}
2596 is parsed:
2597 @itemize @bullet
2598 @item
2599 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2600 rules currently in effect.
2601 @item
2602 Expressions are parsed with binding-power @var{bp} until a delimiter is
2603 reached.
2604 @item
2605 If @var{sop} is a procedure, it is applied to the list of parsed
2606 expressions; the resulting value is incorporated into the expression
2607 being built. Otherwise, the list of @var{sop} and the parsed
2608 expressions is incorporated.
2609 @item
2610 The ruleset in effect before @var{tk} was parsed is restored;
2611 @var{rule1} @dots{} are forgotten.
2612 @end itemize
2613 @end defun
2614
2615 @defun prec:commentfix tk stp match rule1 @dots{}
2616 Returns rules specifying the following actions take place when @var{tk}
2617 is parsed:
2618 @itemize @bullet
2619 @item
2620 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2621 rules currently in effect.
2622 @item
2623 Characters are read until and end-of-file or a sequence of characters
2624 is read which matches the @emph{string} @var{match}.
2625 @item
2626 If @var{stp} is a procedure, it is called with the string of all that
2627 was read between the @var{tk} and @var{match} (exclusive).
2628 @item
2629 The ruleset in effect before @var{tk} was parsed is restored;
2630 @var{rule1} @dots{} are forgotten.
2631 @end itemize
2632
2633 Parsing of commentfix syntax differs from the others in several ways.
2634 It reads directly from input without tokenizing; It calls @var{stp} but
2635 does not return its value; nay any value. I added the @var{stp}
2636 argument so that comment text could be echoed.
2637 @end defun
2638
2639 @defun prec:matchfix tk sop sep match rule1 @dots{}
2640 Returns a rule specifying the following actions take place when @var{tk}
2641 is parsed:
2642 @itemize @bullet
2643 @item
2644 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2645 rules currently in effect.
2646 @item
2647 A rule declaring the token @var{match} a delimiter takes effect.
2648 @item
2649 Expressions are parsed with binding-power @code{0} until the token
2650 @var{match} is reached. If the token @var{sep} does not appear between
2651 each pair of expressions parsed, a warning is issued.
2652 @item
2653 If @var{sop} is a procedure, it is applied to the list of parsed
2654 expressions; the resulting value is incorporated into the expression
2655 being built. Otherwise, the list of @var{sop} and the parsed
2656 expressions is incorporated.
2657 @item
2658 The ruleset in effect before @var{tk} was parsed is restored;
2659 @var{rule1} @dots{} are forgotten.
2660 @end itemize
2661 @end defun
2662
2663 @defun prec:inmatchfix tk sop sep match lbp rule1 @dots{}
2664 Returns a rule declaring the left-binding-precedence of the token
2665 @var{tk} is @var{lbp} and specifying the following actions take place
2666 when @var{tk} is parsed:
2667 @itemize @bullet
2668 @item
2669 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2670 rules currently in effect.
2671 @item
2672 A rule declaring the token @var{match} a delimiter takes effect.
2673 @item
2674 Expressions are parsed with binding-power @code{0} until the token
2675 @var{match} is reached. If the token @var{sep} does not appear between
2676 each pair of expressions parsed, a warning is issued.
2677 @item
2678 If @var{sop} is a procedure, it is applied to the list of @var{left} and
2679 the parsed expressions; the resulting value is incorporated into the
2680 expression being built. Otherwise, the list of @var{sop}, the
2681 @var{left} expression, and the parsed expressions is incorporated.
2682 @item
2683 The ruleset in effect before @var{tk} was parsed is restored;
2684 @var{rule1} @dots{} are forgotten.
2685 @end itemize
2686 @end defun
2687
2688
2689 @node Format, Standard Formatted I/O, Precedence Parsing, Textual Conversion Packages
2690 @section Format (version 3.0)
2691
2692 @code{(require 'format)}
2693 @ftindex format
2694
2695 @include fmtdoc.txi
2696
2697 @node Standard Formatted I/O, Programs and Arguments, Format, Textual Conversion Packages
2698 @section Standard Formatted I/O
2699
2700 @menu
2701 * Standard Formatted Output:: 'printf
2702 * Standard Formatted Input:: 'scanf
2703 @end menu
2704
2705 @subsection stdio
2706
2707 @code{(require 'stdio)}
2708 @ftindex stdio
2709
2710 @code{require}s @code{printf} and @code{scanf} and additionally defines
2711 the symbols:
2712
2713 @defvar stdin
2714 Defined to be @code{(current-input-port)}.
2715 @end defvar
2716 @defvar stdout
2717 Defined to be @code{(current-output-port)}.
2718 @end defvar
2719 @defvar stderr
2720 Defined to be @code{(current-error-port)}.
2721 @end defvar
2722
2723
2724 @node Standard Formatted Output, Standard Formatted Input, Standard Formatted I/O, Standard Formatted I/O
2725 @subsection Standard Formatted Output
2726
2727 @code{(require 'printf)}
2728 @ftindex printf
2729
2730 @deffn Procedure printf format arg1 @dots{}
2731 @deffnx Procedure fprintf port format arg1 @dots{}
2732 @deffnx Procedure sprintf str format arg1 @dots{}
2733 @deffnx Procedure sprintf #f format arg1 @dots{}
2734 @deffnx Procedure sprintf k format arg1 @dots{}
2735
2736 Each function converts, formats, and outputs its @var{arg1} @dots{}
2737 arguments according to the control string @var{format} argument and
2738 returns the number of characters output.
2739
2740 @code{printf} sends its output to the port @code{(current-output-port)}.
2741 @code{fprintf} sends its output to the port @var{port}. @code{sprintf}
2742 @code{string-set!}s locations of the non-constant string argument
2743 @var{str} to the output characters.
2744
2745 Two extensions of @code{sprintf} return new strings. If the first
2746 argument is @code{#f}, then the returned string's length is as many
2747 characters as specified by the @var{format} and data; if the first
2748 argument is a non-negative integer @var{k}, then the length of the
2749 returned string is also bounded by @var{k}.
2750
2751 The string @var{format} contains plain characters which are copied to
2752 the output stream, and conversion specifications, each of which results
2753 in fetching zero or more of the arguments @var{arg1} @dots{}. The
2754 results are undefined if there are an insufficient number of arguments
2755 for the format. If @var{format} is exhausted while some of the
2756 @var{arg1} @dots{} arguments remain unused, the excess @var{arg1}
2757 @dots{} arguments are ignored.
2758
2759 The conversion specifications in a format string have the form:
2760
2761 @example
2762 % @r{[} @var{flags} @r{]} @r{[} @var{width} @r{]} @r{[} . @var{precision} @r{]} @r{[} @var{type} @r{]} @var{conversion}
2763 @end example
2764
2765 An output conversion specifications consist of an initial @samp{%}
2766 character followed in sequence by:
2767
2768 @itemize @bullet
2769 @item
2770 Zero or more @dfn{flag characters} that modify the normal behavior of
2771 the conversion specification.
2772
2773 @table @asis
2774 @item @samp{-}
2775 Left-justify the result in the field. Normally the result is
2776 right-justified.
2777
2778 @item @samp{+}
2779 For the signed @samp{%d} and @samp{%i} conversions and all inexact
2780 conversions, prefix a plus sign if the value is positive.
2781
2782 @item @samp{ }
2783 For the signed @samp{%d} and @samp{%i} conversions, if the result
2784 doesn't start with a plus or minus sign, prefix it with a space
2785 character instead. Since the @samp{+} flag ensures that the result
2786 includes a sign, this flag is ignored if both are specified.
2787
2788 @item @samp{#}
2789 For inexact conversions, @samp{#} specifies that the result should
2790 always include a decimal point, even if no digits follow it. For the
2791 @samp{%g} and @samp{%G} conversions, this also forces trailing zeros
2792 after the decimal point to be printed where they would otherwise be
2793 elided.
2794
2795 For the @samp{%o} conversion, force the leading digit to be @samp{0}, as
2796 if by increasing the precision. For @samp{%x} or @samp{%X}, prefix a
2797 leading @samp{0x} or @samp{0X} (respectively) to the result. This
2798 doesn't do anything useful for the @samp{%d}, @samp{%i}, or @samp{%u}
2799 conversions. Using this flag produces output which can be parsed by the
2800 @code{scanf} functions with the @samp{%i} conversion (@pxref{Standard
2801 Formatted Input}).
2802
2803
2804 @item @samp{0}
2805 Pad the field with zeros instead of spaces. The zeros are placed after
2806 any indication of sign or base. This flag is ignored if the @samp{-}
2807 flag is also specified, or if a precision is specified for an exact
2808 converson.
2809 @end table
2810
2811 @item
2812 An optional decimal integer specifying the @dfn{minimum field width}.
2813 If the normal conversion produces fewer characters than this, the field
2814 is padded (with spaces or zeros per the @samp{0} flag) to the specified
2815 width. This is a @emph{minimum} width; if the normal conversion
2816 produces more characters than this, the field is @emph{not} truncated.
2817 @cindex minimum field width (@code{printf})
2818
2819 Alternatively, if the field width is @samp{*}, the next argument in the
2820 argument list (before the actual value to be printed) is used as the
2821 field width. The width value must be an integer. If the value is
2822 negative it is as though the @samp{-} flag is set (see above) and the
2823 absolute value is used as the field width.
2824
2825 @item
2826 An optional @dfn{precision} to specify the number of digits to be
2827 written for numeric conversions and the maximum field width for string
2828 conversions. The precision is specified by a period (@samp{.}) followed
2829 optionally by a decimal integer (which defaults to zero if omitted).
2830 @cindex precision (@code{printf})
2831
2832 Alternatively, if the precision is @samp{.*}, the next argument in the
2833 argument list (before the actual value to be printed) is used as the
2834 precision. The value must be an integer, and is ignored if negative.
2835 If you specify @samp{*} for both the field width and precision, the
2836 field width argument precedes the precision argument. The @samp{.*}
2837 precision is an enhancement. C library versions may not accept this
2838 syntax.
2839
2840 For the @samp{%f}, @samp{%e}, and @samp{%E} conversions, the precision
2841 specifies how many digits follow the decimal-point character. The
2842 default precision is @code{6}. If the precision is explicitly @code{0},
2843 the decimal point character is suppressed.
2844
2845 For the @samp{%g} and @samp{%G} conversions, the precision specifies how
2846 many significant digits to print. Significant digits are the first
2847 digit before the decimal point, and all the digits after it. If the
2848 precision is @code{0} or not specified for @samp{%g} or @samp{%G}, it is
2849 treated like a value of @code{1}. If the value being printed cannot be
2850 expressed accurately in the specified number of digits, the value is
2851 rounded to the nearest number that fits.
2852
2853 For exact conversions, if a precision is supplied it specifies the
2854 minimum number of digits to appear; leading zeros are produced if
2855 necessary. If a precision is not supplied, the number is printed with
2856 as many digits as necessary. Converting an exact @samp{0} with an
2857 explicit precision of zero produces no characters.
2858
2859 @item
2860 An optional one of @samp{l}, @samp{h} or @samp{L}, which is ignored for
2861 numeric conversions. It is an error to specify these modifiers for
2862 non-numeric conversions.
2863
2864 @item
2865 A character that specifies the conversion to be applied.
2866 @end itemize
2867
2868 @subsubsection Exact Conversions
2869
2870 @table @asis
2871 @item @samp{d}, @samp{i}
2872 Print an integer as a signed decimal number. @samp{%d} and @samp{%i}
2873 are synonymous for output, but are different when used with @code{scanf}
2874 for input (@pxref{Standard Formatted Input}).
2875
2876 @item @samp{o}
2877 Print an integer as an unsigned octal number.
2878
2879 @item @samp{u}
2880 Print an integer as an unsigned decimal number.
2881
2882 @item @samp{x}, @samp{X}
2883 Print an integer as an unsigned hexadecimal number. @samp{%x} prints
2884 using the digits @samp{0123456789abcdef}. @samp{%X} prints using the
2885 digits @samp{0123456789ABCDEF}.
2886 @end table
2887
2888 @subsubsection Inexact Conversions
2889
2890 @table @asis
2891 @item @samp{f}
2892 Print a floating-point number in fixed-point notation.
2893
2894 @item @samp{e}, @samp{E}
2895 Print a floating-point number in exponential notation. @samp{%e} prints
2896 @samp{e} between mantissa and exponont. @samp{%E} prints @samp{E}
2897 between mantissa and exponont.
2898
2899 @item @samp{g}, @samp{G}
2900 Print a floating-point number in either fixed or exponential notation,
2901 whichever is more appropriate for its magnitude. Unless an @samp{#}
2902 flag has been supplied, trailing zeros after a decimal point will be
2903 stripped off. @samp{%g} prints @samp{e} between mantissa and exponont.
2904 @samp{%G} prints @samp{E} between mantissa and exponent.
2905
2906 @item @samp{k}, @samp{K}
2907 Print a number like @samp{%g}, except that an SI prefix is output after
2908 the number, which is scaled accordingly. @samp{%K} outputs a space
2909 between number and prefix, @samp{%k} does not.
2910
2911 @end table
2912
2913 @subsubsection Other Conversions
2914 @table @asis
2915 @item @samp{c}
2916 Print a single character. The @samp{-} flag is the only one which can
2917 be specified. It is an error to specify a precision.
2918
2919 @item @samp{s}
2920 Print a string. The @samp{-} flag is the only one which can be
2921 specified. A precision specifies the maximum number of characters to
2922 output; otherwise all characters in the string are output.
2923
2924 @item @samp{a}, @samp{A}
2925 Print a scheme expression. The @samp{-} flag left-justifies the output.
2926 The @samp{#} flag specifies that strings and characters should be quoted
2927 as by @code{write} (which can be read using @code{read}); otherwise,
2928 output is as @code{display} prints. A precision specifies the maximum
2929 number of characters to output; otherwise as many characters as needed
2930 are output.
2931
2932 @emph{Note:} @samp{%a} and @samp{%A} are SLIB extensions.
2933
2934 @c @item @samp{p}
2935 @c Print the value of a pointer.
2936
2937 @c @item @samp{n}
2938 @c Get the number of characters printed so far. See @ref{Other Output Conversions}.
2939 @c Note that this conversion specification never produces any output.
2940
2941 @c @item @samp{m}
2942 @c Print the string corresponding to the value of @code{errno}.
2943 @c (This is a GNU extension.)
2944 @c @xref{Other Output Conversions}.
2945
2946 @item @samp{%}
2947 Print a literal @samp{%} character. No argument is consumed. It is an
2948 error to specifiy flags, field width, precision, or type modifiers with
2949 @samp{%%}.
2950 @end table
2951 @end deffn
2952
2953
2954 @node Standard Formatted Input, , Standard Formatted Output, Standard Formatted I/O
2955 @subsection Standard Formatted Input
2956
2957 @code{(require 'scanf)}
2958 @ftindex scanf
2959
2960 @deffn Function scanf-read-list format
2961 @deffnx Function scanf-read-list format port
2962 @deffnx Function scanf-read-list format string
2963 @end deffn
2964
2965 @defmac scanf format arg1 @dots{}
2966 @defmacx fscanf port format arg1 @dots{}
2967 @defmacx sscanf str format arg1 @dots{}
2968
2969 Each function reads characters, interpreting them according to the
2970 control string @var{format} argument.
2971
2972 @code{scanf-read-list} returns a list of the items specified as far as
2973 the input matches @var{format}. @code{scanf}, @code{fscanf}, and
2974 @code{sscanf} return the number of items successfully matched and
2975 stored. @code{scanf}, @code{fscanf}, and @code{sscanf} also set the
2976 location corresponding to @var{arg1} @dots{} using the methods:
2977
2978 @table @asis
2979 @item symbol
2980 @code{set!}
2981 @item car expression
2982 @code{set-car!}
2983 @item cdr expression
2984 @code{set-cdr!}
2985 @item vector-ref expression
2986 @code{vector-set!}
2987 @item substring expression
2988 @code{substring-move-left!}
2989 @end table
2990
2991 The argument to a @code{substring} expression in @var{arg1} @dots{} must
2992 be a non-constant string. Characters will be stored starting at the
2993 position specified by the second argument to @code{substring}. The
2994 number of characters stored will be limited by either the position
2995 specified by the third argument to @code{substring} or the length of the
2996 matched string, whichever is less.
2997
2998 The control string, @var{format}, contains conversion specifications and
2999 other characters used to direct interpretation of input sequences. The
3000 control string contains:
3001
3002 @itemize @bullet
3003 @item White-space characters (blanks, tabs, newlines, or formfeeds)
3004 that cause input to be read (and discarded) up to the next
3005 non-white-space character.
3006
3007 @item An ordinary character (not @samp{%}) that must match the next
3008 character of the input stream.
3009
3010 @item Conversion specifications, consisting of the character @samp{%}, an
3011 optional assignment suppressing character @samp{*}, an optional
3012 numerical maximum-field width, an optional @samp{l}, @samp{h} or
3013 @samp{L} which is ignored, and a conversion code.
3014
3015 @c @item The conversion specification can alternatively be prefixed by
3016 @c the character sequence @samp{%n$} instead of the character @samp{%},
3017 @c where @var{n} is a decimal integer in the range. The @samp{%n$}
3018 @c construction indicates that the value of the next input field should be
3019 @c placed in the @var{n}th place in the return list, rather than to the next
3020 @c unused one. The two forms of introducing a conversion specification,
3021 @c @samp{%} and @samp{%n$}, must not be mixed within a single format string
3022 @c with the following exception: Skip fields (see below) can be designated
3023 @c as @samp{%*} or @samp{%n$*}. In the latter case, @var{n} is ignored.
3024
3025 @end itemize
3026
3027 Unless the specification contains the @samp{n} conversion character
3028 (described below), a conversion specification directs the conversion of
3029 the next input field. The result of a conversion specification is
3030 returned in the position of the corresponding argument points, unless
3031 @samp{*} indicates assignment suppression. Assignment suppression
3032 provides a way to describe an input field to be skipped. An input field
3033 is defined as a string of characters; it extends to the next
3034 inappropriate character or until the field width, if specified, is
3035 exhausted.
3036
3037 @quotation
3038 @emph{Note:} This specification of format strings differs from the
3039 @cite{ANSI C} and @cite{POSIX} specifications. In SLIB, white space
3040 before an input field is not skipped unless white space appears before
3041 the conversion specification in the format string. In order to write
3042 format strings which work identically with @cite{ANSI C} and SLIB,
3043 prepend whitespace to all conversion specifications except @samp{[} and
3044 @samp{c}.
3045 @end quotation
3046
3047 The conversion code indicates the interpretation of the input field; For
3048 a suppressed field, no value is returned. The following conversion
3049 codes are legal:
3050
3051 @table @asis
3052
3053 @item @samp{%}
3054 A single % is expected in the input at this point; no value is returned.
3055
3056 @item @samp{d}, @samp{D}
3057 A decimal integer is expected.
3058
3059 @item @samp{u}, @samp{U}
3060 An unsigned decimal integer is expected.
3061
3062 @item @samp{o}, @samp{O}
3063 An octal integer is expected.
3064
3065 @item @samp{x}, @samp{X}
3066 A hexadecimal integer is expected.
3067
3068 @item @samp{i}
3069 An integer is expected. Returns the value of the next input item,
3070 interpreted according to C conventions; a leading @samp{0} implies
3071 octal, a leading @samp{0x} implies hexadecimal; otherwise, decimal is
3072 assumed.
3073
3074 @item @samp{n}
3075 Returns the total number of bytes (including white space) read by
3076 @code{scanf}. No input is consumed by @code{%n}.
3077
3078 @item @samp{f}, @samp{F}, @samp{e}, @samp{E}, @samp{g}, @samp{G}
3079 A floating-point number is expected. The input format for
3080 floating-point numbers is an optionally signed string of digits,
3081 possibly containing a radix character @samp{.}, followed by an optional
3082 exponent field consisting of an @samp{E} or an @samp{e}, followed by an
3083 optional @samp{+}, @samp{-}, or space, followed by an integer.
3084
3085 @item @samp{c}, @samp{C}
3086 @var{Width} characters are expected. The normal skip-over-white-space
3087 is suppressed in this case; to read the next non-space character, use
3088 @samp{%1s}. If a field width is given, a string is returned; up to the
3089 indicated number of characters is read.
3090
3091 @item @samp{s}, @samp{S}
3092 A character string is expected The input field is terminated by a
3093 white-space character. @code{scanf} cannot read a null string.
3094
3095 @item @samp{[}
3096 Indicates string data and the normal skip-over-leading-white-space is
3097 suppressed. The left bracket is followed by a set of characters, called
3098 the scanset, and a right bracket; the input field is the maximal
3099 sequence of input characters consisting entirely of characters in the
3100 scanset. @samp{^}, when it appears as the first character in the
3101 scanset, serves as a complement operator and redefines the scanset as
3102 the set of all characters not contained in the remainder of the scanset
3103 string. Construction of the scanset follows certain conventions. A
3104 range of characters may be represented by the construct first-last,
3105 enabling @samp{[0123456789]} to be expressed @samp{[0-9]}. Using this
3106 convention, first must be lexically less than or equal to last;
3107 otherwise, the dash stands for itself. The dash also stands for itself
3108 when it is the first or the last character in the scanset. To include
3109 the right square bracket as an element of the scanset, it must appear as
3110 the first character (possibly preceded by a @samp{^}) of the scanset, in
3111 which case it will not be interpreted syntactically as the closing
3112 bracket. At least one character must match for this conversion to
3113 succeed.
3114 @end table
3115
3116 The @code{scanf} functions terminate their conversions at end-of-file,
3117 at the end of the control string, or when an input character conflicts
3118 with the control string. In the latter case, the offending character is
3119 left unread in the input stream.
3120 @end defmac
3121
3122
3123 @node Programs and Arguments, HTML, Standard Formatted I/O, Textual Conversion Packages
3124 @section Program and Arguments
3125
3126 @menu
3127 * Getopt:: Command Line option parsing
3128 * Command Line:: A command line reader for Scheme shells
3129 * Parameter lists:: 'parameters
3130 * Getopt Parameter lists:: 'getopt-parameters
3131 * Filenames:: 'glob or 'filename
3132 * Batch:: 'batch
3133 @end menu
3134
3135 @node Getopt, Command Line, Programs and Arguments, Programs and Arguments
3136 @subsection Getopt
3137
3138 @code{(require 'getopt)}
3139 @ftindex getopt
3140
3141 This routine implements Posix command line argument parsing. Notice
3142 that returning values through global variables means that @code{getopt}
3143 is @emph{not} reentrant.
3144
3145 @defvar *optind*
3146 Is the index of the current element of the command line. It is
3147 initially one. In order to parse a new command line or reparse an old
3148 one, @var{*opting*} must be reset.
3149 @end defvar
3150
3151 @defvar *optarg*
3152 Is set by getopt to the (string) option-argument of the current option.
3153 @end defvar
3154
3155 @deffn Procedure getopt argc argv optstring
3156 Returns the next option letter in @var{argv} (starting from
3157 @code{(vector-ref argv *optind*)}) that matches a letter in
3158 @var{optstring}. @var{argv} is a vector or list of strings, the 0th of
3159 which getopt usually ignores. @var{argc} is the argument count, usually
3160 the length of @var{argv}. @var{optstring} is a string of recognized
3161 option characters; if a character is followed by a colon, the option
3162 takes an argument which may be immediately following it in the string or
3163 in the next element of @var{argv}.
3164
3165 @var{*optind*} is the index of the next element of the @var{argv} vector
3166 to be processed. It is initialized to 1 by @file{getopt.scm}, and
3167 @code{getopt} updates it when it finishes with each element of
3168 @var{argv}.
3169
3170 @code{getopt} returns the next option character from @var{argv} that
3171 matches a character in @var{optstring}, if there is one that matches.
3172 If the option takes an argument, @code{getopt} sets the variable
3173 @var{*optarg*} to the option-argument as follows:
3174
3175 @itemize @bullet
3176 @item
3177 If the option was the last character in the string pointed to by an
3178 element of @var{argv}, then @var{*optarg*} contains the next element of
3179 @var{argv}, and @var{*optind*} is incremented by 2. If the resulting
3180 value of @var{*optind*} is greater than or equal to @var{argc}, this
3181 indicates a missing option argument, and @code{getopt} returns an error
3182 indication.
3183
3184 @item
3185 Otherwise, @var{*optarg*} is set to the string following the option
3186 character in that element of @var{argv}, and @var{*optind*} is
3187 incremented by 1.
3188 @end itemize
3189
3190 If, when @code{getopt} is called, the string @code{(vector-ref argv
3191 *optind*)} either does not begin with the character @code{#\-} or is
3192 just @code{"-"}, @code{getopt} returns @code{#f} without changing
3193 @var{*optind*}. If @code{(vector-ref argv *optind*)} is the string
3194 @code{"--"}, @code{getopt} returns @code{#f} after incrementing
3195 @var{*optind*}.
3196
3197 If @code{getopt} encounters an option character that is not contained in
3198 @var{optstring}, it returns the question-mark @code{#\?} character. If
3199 it detects a missing option argument, it returns the colon character
3200 @code{#\:} if the first character of @var{optstring} was a colon, or a
3201 question-mark character otherwise. In either case, @code{getopt} sets
3202 the variable @var{getopt:opt} to the option character that caused the
3203 error.
3204
3205 The special option @code{"--"} can be used to delimit the end of the
3206 options; @code{#f} is returned, and @code{"--"} is skipped.
3207
3208 RETURN VALUE
3209
3210 @code{getopt} returns the next option character specified on the command
3211 line. A colon @code{#\:} is returned if @code{getopt} detects a missing
3212 argument and the first character of @var{optstring} was a colon
3213 @code{#\:}.
3214
3215 A question-mark @code{#\?} is returned if @code{getopt} encounters an
3216 option character not in @var{optstring} or detects a missing argument
3217 and the first character of @var{optstring} was not a colon @code{#\:}.
3218
3219 Otherwise, @code{getopt} returns @code{#f} when all command line options
3220 have been parsed.
3221
3222 Example:
3223 @lisp
3224 #! /usr/local/bin/scm
3225 ;;;This code is SCM specific.
3226 (define argv (program-arguments))
3227 (require 'getopt)
3228 @ftindex getopt
3229
3230 (define opts ":a:b:cd")
3231 (let loop ((opt (getopt (length argv) argv opts)))
3232 (case opt
3233 ((#\a) (print "option a: " *optarg*))
3234 ((#\b) (print "option b: " *optarg*))
3235 ((#\c) (print "option c"))
3236 ((#\d) (print "option d"))
3237 ((#\?) (print "error" getopt:opt))
3238 ((#\:) (print "missing arg" getopt:opt))
3239 ((#f) (if (< *optind* (length argv))
3240 (print "argv[" *optind* "]="
3241 (list-ref argv *optind*)))
3242 (set! *optind* (+ *optind* 1))))
3243 (if (< *optind* (length argv))
3244 (loop (getopt (length argv) argv opts))))
3245
3246 (slib:exit)
3247 @end lisp
3248 @end deffn
3249
3250 @subsection Getopt--
3251
3252 @defun getopt-- argc argv optstring
3253 The procedure @code{getopt--} is an extended version of @code{getopt}
3254 which parses @dfn{long option names} of the form
3255 @samp{--hold-the-onions} and @samp{--verbosity-level=extreme}.
3256 @w{@code{Getopt--}} behaves as @code{getopt} except for non-empty
3257 options beginning with @samp{--}.
3258
3259 Options beginning with @samp{--} are returned as strings rather than
3260 characters. If a value is assigned (using @samp{=}) to a long option,
3261 @code{*optarg*} is set to the value. The @samp{=} and value are
3262 not returned as part of the option string.
3263
3264 No information is passed to @code{getopt--} concerning which long
3265 options should be accepted or whether such options can take arguments.
3266 If a long option did not have an argument, @code{*optarg} will be set to
3267 @code{#f}. The caller is responsible for detecting and reporting
3268 errors.
3269
3270 @example
3271 (define opts ":-:b:")
3272 (define argc 5)
3273 (define argv '("foo" "-b9" "--f1" "--2=" "--g3=35234.342" "--"))
3274 (define *optind* 1)
3275 (define *optarg* #f)
3276 (require 'qp)
3277 @ftindex qp
3278 (do ((i 5 (+ -1 i)))
3279 ((zero? i))
3280 (define opt (getopt-- argc argv opts))
3281 (print *optind* opt *optarg*)))
3282 @print{}
3283 2 #\b "9"
3284 3 "f1" #f
3285 4 "2" ""
3286 5 "g3" "35234.342"
3287 5 #f "35234.342"
3288 @end example
3289 @end defun
3290
3291 @node Command Line, Parameter lists, Getopt, Programs and Arguments
3292 @subsection Command Line
3293
3294 @code{(require 'read-command)}
3295 @ftindex read-command
3296
3297 @defun read-command port
3298 @defunx read-command
3299 @code{read-command} converts a @dfn{command line} into a list of strings
3300 @cindex command line
3301 suitable for parsing by @code{getopt}. The syntax of command lines
3302 supported resembles that of popular @dfn{shell}s. @code{read-command}
3303 updates @var{port} to point to the first character past the command
3304 delimiter.
3305
3306 If an end of file is encountered in the input before any characters are
3307 found that can begin an object or comment, then an end of file object is
3308 returned.
3309
3310 The @var{port} argument may be omitted, in which case it defaults to the
3311 value returned by @code{current-input-port}.
3312
3313 The fields into which the command line is split are delimited by
3314 whitespace as defined by @code{char-whitespace?}. The end of a command
3315 is delimited by end-of-file or unescaped semicolon (@key{;}) or
3316 @key{newline}. Any character can be literally included in a field by
3317 escaping it with a backslach (@key{\}).
3318
3319 The initial character and types of fields recognized are:
3320 @table @asis
3321 @item @samp{\}
3322 The next character has is taken literally and not interpreted as a field
3323 delimiter. If @key{\} is the last character before a @key{newline},
3324 that @key{newline} is just ignored. Processing continues from the
3325 characters after the @key{newline} as though the backslash and
3326 @key{newline} were not there.
3327 @item @samp{"}
3328 The characters up to the next unescaped @key{"} are taken literally,
3329 according to [R4RS] rules for literal strings (@pxref{Strings, , ,r4rs,
3330 Revised(4) Scheme}).
3331 @item @samp{(}, @samp{%'}
3332 One scheme expression is @code{read} starting with this character. The
3333 @code{read} expression is evaluated, converted to a string
3334 (using @code{display}), and replaces the expression in the returned
3335 field.
3336 @item @samp{;}
3337 Semicolon delimits a command. Using semicolons more than one command
3338 can appear on a line. Escaped semicolons and semicolons inside strings
3339 do not delimit commands.
3340 @end table
3341
3342 @noindent
3343 The comment field differs from the previous fields in that it must be
3344 the first character of a command or appear after whitespace in order to
3345 be recognized. @key{#} can be part of fields if these conditions are
3346 not met. For instance, @code{ab#c} is just the field ab#c.
3347
3348 @table @samp
3349 @item #
3350 Introduces a comment. The comment continues to the end of the line on
3351 which the semicolon appears. Comments are treated as whitespace by
3352 @code{read-dommand-line} and backslashes before @key{newline}s in
3353 comments are also ignored.
3354 @end table
3355 @end defun
3356
3357 @defun read-options-file filename
3358 @code{read-options-file} converts an @dfn{options file} into a list of
3359 @cindex options file
3360 strings suitable for parsing by @code{getopt}. The syntax of options
3361 files is the same as the syntax for command
3362 lines, except that @key{newline}s do not terminate reading (only @key{;}
3363 or end of file).
3364
3365 If an end of file is encountered before any characters are found that
3366 can begin an object or comment, then an end of file object is returned.
3367 @end defun
3368
3369
3370
3371 @node Parameter lists, Getopt Parameter lists, Command Line, Programs and Arguments
3372 @subsection Parameter lists
3373
3374 @code{(require 'parameters)}
3375 @ftindex parameters
3376
3377 @noindent
3378 Arguments to procedures in scheme are distinguished from each other by
3379 their position in the procedure call. This can be confusing when a
3380 procedure takes many arguments, many of which are not often used.
3381
3382 @noindent
3383 A @dfn{parameter-list} is a way of passing named information to a
3384 procedure. Procedures are also defined to set unused parameters to
3385 default values, check parameters, and combine parameter lists.
3386
3387 @noindent
3388 A @var{parameter} has the form @code{(@r{parameter-name} @r{value1}
3389 @dots{})}. This format allows for more than one value per
3390 parameter-name.
3391
3392 @noindent
3393 A @var{parameter-list} is a list of @var{parameter}s, each with a
3394 different @var{parameter-name}.
3395
3396 @deffn Function make-parameter-list parameter-names
3397 Returns an empty parameter-list with slots for @var{parameter-names}.
3398 @end deffn
3399
3400 @deffn Function parameter-list-ref parameter-list parameter-name
3401 @var{parameter-name} must name a valid slot of @var{parameter-list}.
3402 @code{parameter-list-ref} returns the value of parameter
3403 @var{parameter-name} of @var{parameter-list}.
3404 @end deffn
3405
3406 @deffn Function remove-parameter parameter-name parameter-list
3407 Removes the parameter @var{parameter-name} from @var{parameter-list}.
3408 @code{remove-parameter} does not alter the argument
3409 @var{parameter-list}.
3410
3411 If there are more than one @var{parameter-name} parameters, an error is
3412 signaled.
3413 @end deffn
3414
3415 @deffn Procedure adjoin-parameters! parameter-list parameter1 @dots{}
3416 Returns @var{parameter-list} with @var{parameter1} @dots{} merged in.
3417 @end deffn
3418
3419 @deffn Procedure parameter-list-expand expanders parameter-list
3420 @var{expanders} is a list of procedures whose order matches the order of
3421 the @var{parameter-name}s in the call to @code{make-parameter-list}
3422 which created @var{parameter-list}. For each non-false element of
3423 @var{expanders} that procedure is mapped over the corresponding
3424 parameter value and the returned parameter lists are merged into
3425 @var{parameter-list}.
3426
3427 This process is repeated until @var{parameter-list} stops growing. The
3428 value returned from @code{parameter-list-expand} is unspecified.
3429 @end deffn
3430
3431 @deffn Function fill-empty-parameters defaulters parameter-list
3432 @var{defaulters} is a list of procedures whose order matches the order
3433 of the @var{parameter-name}s in the call to @code{make-parameter-list}
3434 which created @var{parameter-list}. @code{fill-empty-parameters}
3435 returns a new parameter-list with each empty parameter replaced with the
3436 list returned by calling the corresponding @var{defaulter} with
3437 @var{parameter-list} as its argument.
3438 @end deffn
3439
3440 @deffn Function check-parameters checks parameter-list
3441 @var{checks} is a list of procedures whose order matches the order of
3442 the @var{parameter-name}s in the call to @code{make-parameter-list}
3443 which created @var{parameter-list}.
3444
3445 @code{check-parameters} returns @var{parameter-list} if each @var{check}
3446 of the corresponding @var{parameter-list} returns non-false. If some
3447 @var{check} returns @code{#f} a warning is signaled.
3448 @end deffn
3449
3450 @noindent
3451 In the following procedures @var{arities} is a list of symbols. The
3452 elements of @code{arities} can be:
3453
3454 @table @code
3455 @item single
3456 Requires a single parameter.
3457 @item optional
3458 A single parameter or no parameter is acceptable.
3459 @item boolean
3460 A single boolean parameter or zero parameters is acceptable.
3461 @item nary
3462 Any number of parameters are acceptable.
3463 @item nary1
3464 One or more of parameters are acceptable.
3465 @end table
3466
3467 @deffn Function parameter-list->arglist positions arities parameter-list
3468 Returns @var{parameter-list} converted to an argument list. Parameters
3469 of @var{arity} type @code{single} and @code{boolean} are converted to
3470 the single value associated with them. The other @var{arity} types are
3471 converted to lists of the value(s).
3472
3473 @var{positions} is a list of positive integers whose order matches the
3474 order of the @var{parameter-name}s in the call to
3475 @code{make-parameter-list} which created @var{parameter-list}. The
3476 integers specify in which argument position the corresponding parameter
3477 should appear.
3478 @end deffn
3479
3480
3481 @node Getopt Parameter lists, Filenames, Parameter lists, Programs and Arguments
3482 @subsection Getopt Parameter lists
3483
3484 @code{(require 'getopt-parameters)}
3485
3486 @deffn Function getopt->parameter-list argc argv optnames arities types aliases desc @dots{}
3487 Returns @var{argv} converted to a parameter-list. @var{optnames} are
3488 the parameter-names. @var{arities} and @var{types} are lists of symbols
3489 corresponding to @var{optnames}.
3490
3491 @var{aliases} is a list of lists of strings or integers paired with
3492 elements of @var{optnames}. Each one-character string will be treated
3493 as a single @samp{-} option by @code{getopt}. Longer strings will be
3494 treated as long-named options (@pxref{Getopt, getopt--}).
3495
3496 If the @var{aliases} association list has only strings as its
3497 @code{car}s, then all the option-arguments after an option (and before
3498 the next option) are adjoined to that option.
3499
3500 If the @var{aliases} association list has integers, then each (string)
3501 option will take at most one option-argument. Unoptioned arguments are
3502 collected in a list. A @samp{-1} alias will take the last argument in
3503 this list; @samp{+1} will take the first argument in the list. The
3504 aliases -2 then +2; -3 then +3; @dots{} are tried so long as a positive
3505 or negative consecutive alias is found and arguments remain in the list.
3506 Finally a @samp{0} alias, if found, absorbs any remaining arguments.
3507
3508 In all cases, if unclaimed arguments remain after processing, a warning
3509 is signaled and #f is returned.
3510 @end deffn
3511
3512 @deffn Function getopt->arglist argc argv optnames positions arities types defaulters checks aliases desc @dots{}
3513 Like @code{getopt->parameter-list}, but converts @var{argv} to an
3514 argument-list as specified by @var{optnames}, @var{positions},
3515 @var{arities}, @var{types}, @var{defaulters}, @var{checks}, and
3516 @var{aliases}. If the options supplied violate the @var{arities} or
3517 @var{checks} constraints, then a warning is signaled and #f is returned.
3518 @end deffn
3519
3520 @noindent
3521 These @code{getopt} functions can be used with SLIB relational
3522 databases. For an example, @xref{Database Utilities,
3523 make-command-server}.
3524
3525 @noindent
3526 If errors are encountered while processing options, directions for using
3527 the options (and argument strings @var{desc} @dots{}) are printed to
3528 @code{current-error-port}.
3529
3530 @example
3531 (begin
3532 (set! *optind* 1)
3533 (getopt->parameter-list
3534 2
3535 '("cmd" "-?")
3536 '(flag number symbols symbols string flag2 flag3 num2 num3)
3537 '(boolean optional nary1 nary single boolean boolean nary nary)
3538 '(boolean integer symbol symbol string boolean boolean integer integer)
3539 '(("flag" flag)
3540 ("f" flag)
3541 ("Flag" flag2)
3542 ("B" flag3)
3543 ("optional" number)
3544 ("o" number)
3545 ("nary1" symbols)
3546 ("N" symbols)
3547 ("nary" symbols)
3548 ("n" symbols)
3549 ("single" string)
3550 ("s" string)
3551 ("a" num2)
3552 ("Abs" num3))))
3553 @print{}
3554 Usage: cmd [OPTION ARGUMENT ...] ...
3555
3556 -f, --flag
3557 -o, --optional=<number>
3558 -n, --nary=<symbols> ...
3559 -N, --nary1=<symbols> ...
3560 -s, --single=<string>
3561 --Flag
3562 -B
3563 -a <num2> ...
3564 --Abs=<num3> ...
3565
3566 ERROR: getopt->parameter-list "unrecognized option" "-?"
3567 @end example
3568
3569
3570 @node Filenames, Batch, Getopt Parameter lists, Programs and Arguments
3571 @subsection Filenames
3572
3573 @code{(require 'filename)} or @code{(require 'glob)}
3574
3575 @defun filename:match?? pattern
3576 @defunx filename:match-ci?? pattern
3577 Returns a predicate which returns a non-false value if its string argument
3578 matches (the string) @var{pattern}, false otherwise. Filename matching
3579 is like
3580 @cindex glob
3581 @dfn{glob} expansion described the bash manpage, except that names
3582 beginning with @samp{.} are matched and @samp{/} characters are not
3583 treated specially.
3584
3585 These functions interpret the following characters specially in
3586 @var{pattern} strings:
3587 @table @samp
3588 @item *
3589 Matches any string, including the null string.
3590 @item ?
3591 Matches any single character.
3592 @item [@dots{}]
3593 Matches any one of the enclosed characters. A pair of characters
3594 separated by a minus sign (-) denotes a range; any character lexically
3595 between those two characters, inclusive, is matched. If the first
3596 character following the @samp{[} is a @samp{!} or a @samp{^} then any
3597 character not enclosed is matched. A @samp{-} or @samp{]} may be
3598 matched by including it as the first or last character in the set.
3599 @end table
3600
3601 @example
3602 @end example
3603 @end defun
3604
3605 @defun filename:substitute?? pattern template
3606 @defunx filename:substitute-ci?? pattern template
3607 Returns a function transforming a single string argument according to
3608 glob patterns @var{pattern} and @var{template}. @var{pattern} and
3609 @var{template} must have the same number of wildcard specifications,
3610 which need not be identical. @var{pattern} and @var{template} may have
3611 a different number of literal sections. If an argument to the function
3612 matches @var{pattern} in the sense of @code{filename:match??} then it
3613 returns a copy of @var{template} in which each wildcard specification is
3614 replaced by the part of the argument matched by the corresponding
3615 wildcard specification in @var{pattern}. A @code{*} wildcard matches
3616 the longest leftmost string possible. If the argument does not match
3617 @var{pattern} then false is returned.
3618
3619 @var{template} may be a function accepting the same number of string
3620 arguments as there are wildcard specifications in @var{pattern}. In
3621 the case of a match the result of applying @var{template} to a list
3622 of the substrings matched by wildcard specifications will be returned,
3623 otherwise @var{template} will not be called and @code{#f} will be returned.
3624
3625 @example
3626 ((filename:substitute?? "scm_[0-9]*.html" "scm5c4_??.htm")
3627 "scm_10.html")
3628 @result{} "scm5c4_10.htm"
3629 ((filename:substitute?? "??" "beg?mid?end") "AZ")
3630 @result{} "begAmidZend"
3631 ((filename:substitute?? "*na*" "?NA?") "banana")
3632 @result{} "banaNA"
3633 ((filename:substitute?? "?*?" (lambda (s1 s2 s3) (string-append s3 s1))) "ABZ")
3634 @result{} "ZA"
3635 @end example
3636 @end defun
3637
3638 @defun replace-suffix str old new
3639 @var{str} can be a string or a list of strings. Returns a new string
3640 (or strings) similar to @code{str} but with the suffix string @var{old}
3641 removed and the suffix string @var{new} appended. If the end of
3642 @var{str} does not match @var{old}, an error is signaled.
3643
3644 @example
3645 (replace-suffix "/usr/local/lib/slib/batch.scm" ".scm" ".c")
3646 @result{} "/usr/local/lib/slib/batch.c"
3647 @end example
3648 @end defun
3649
3650
3651 @node Batch, , Filenames, Programs and Arguments
3652 @subsection Batch
3653
3654 @code{(require 'batch)}
3655 @ftindex batch
3656
3657 @noindent
3658 The batch procedures provide a way to write and execute portable scripts
3659 for a variety of operating systems. Each @code{batch:} procedure takes
3660 as its first argument a parameter-list (@pxref{Parameter lists}). This
3661 parameter-list argument @var{parms} contains named associations. Batch
3662 currently uses 2 of these:
3663
3664 @table @code
3665 @item batch-port
3666 The port on which to write lines of the batch file.
3667 @item batch-dialect
3668 The syntax of batch file to generate. Currently supported are:
3669 @itemize @bullet
3670 @item
3671 unix
3672 @item
3673 dos
3674 @item
3675 vms
3676 @item
3677 amigados
3678 @item
3679 system
3680 @item
3681 *unknown*
3682 @end itemize
3683 @end table
3684
3685 @noindent
3686 @file{batch.scm} uses 2 enhanced relational tables (@pxref{Database
3687 Utilities}) to store information linking the names of
3688 @code{operating-system}s to @code{batch-dialect}es.
3689
3690 @defun batch:initialize! database
3691 Defines @code{operating-system} and @code{batch-dialect} tables and adds
3692 the domain @code{operating-system} to the enhanced relational database
3693 @var{database}.
3694 @end defun
3695
3696 @defvar batch:platform
3697 Is batch's best guess as to which operating-system it is running under.
3698 @code{batch:platform} is set to @code{(software-type)}
3699 (@pxref{Configuration}) unless @code{(software-type)} is @code{unix},
3700 in which case finer distinctions are made.
3701 @end defvar
3702
3703 @defun batch:call-with-output-script parms file proc
3704 @var{proc} should be a procedure of one argument. If @var{file} is an
3705 output-port, @code{batch:call-with-output-script} writes an appropriate
3706 header to @var{file} and then calls @var{proc} with @var{file} as the
3707 only argument. If @var{file} is a string,
3708 @code{batch:call-with-output-script} opens a output-file of name
3709 @var{file}, writes an appropriate header to @var{file}, and then calls
3710 @var{proc} with the newly opened port as the only argument. Otherwise,
3711 @code{batch:call-with-output-script} acts as if it was called with the
3712 result of @code{(current-output-port)} as its third argument.
3713 @end defun
3714
3715 @noindent
3716 The rest of the @code{batch:} procedures write (or execute if
3717 @code{batch-dialect} is @code{system}) commands to the batch port which
3718 has been added to @var{parms} or @code{(copy-tree @var{parms})} by the
3719 code:
3720
3721 @example
3722 (adjoin-parameters! @var{parms} (list 'batch-port @var{port}))
3723 @end example
3724
3725 @defun batch:command parms string1 string2 @dots{}
3726 Calls @code{batch:try-command} (below) with arguments, but signals an
3727 error if @code{batch:try-command} returns @code{#f}.
3728 @end defun
3729
3730 @noindent
3731 These functions return a non-false value if the command was successfully
3732 translated into the batch dialect and @code{#f} if not. In the case of
3733 the @code{system} dialect, the value is non-false if the operation
3734 suceeded.
3735
3736 @defun batch:try-command parms string1 string2 @dots{}
3737 Writes a command to the @code{batch-port} in @var{parms} which executes
3738 the program named @var{string1} with arguments @var{string2} @dots{}.
3739 @end defun
3740
3741 @defun batch:try-chopped-command parms arg1 arg2 @dots{} list
3742 breaks the last argument @var{list} into chunks small enough so that the
3743 command:
3744
3745 @example
3746 @var{arg1} @var{arg2} @dots{} @var{chunk}
3747 @end example
3748
3749 fits withing the platform's maximum command-line length.
3750
3751 @code{batch:try-chopped-command} calls @code{batch:try-command} with the
3752 command and returns non-false only if the commands all fit and
3753 @code{batch:try-command} of each command line returned non-false.
3754 @end defun
3755
3756 @defun batch:run-script parms string1 string2 @dots{}
3757 Writes a command to the @code{batch-port} in @var{parms} which executes
3758 the batch script named @var{string1} with arguments @var{string2}
3759 @dots{}.
3760
3761 @emph{Note:} @code{batch:run-script} and @code{batch:try-command} are not the
3762 same for some operating systems (VMS).
3763 @end defun
3764
3765 @defun batch:comment parms line1 @dots{}
3766 Writes comment lines @var{line1} @dots{} to the @code{batch-port} in
3767 @var{parms}.
3768 @end defun
3769
3770 @defun batch:lines->file parms file line1 @dots{}
3771 Writes commands to the @code{batch-port} in @var{parms} which create a
3772 file named @var{file} with contents @var{line1} @dots{}.
3773 @end defun
3774
3775 @defun batch:delete-file parms file
3776 Writes a command to the @code{batch-port} in @var{parms} which deletes
3777 the file named @var{file}.
3778 @end defun
3779
3780 @defun batch:rename-file parms old-name new-name
3781 Writes a command to the @code{batch-port} in @var{parms} which renames
3782 the file @var{old-name} to @var{new-name}.
3783 @end defun
3784
3785 @noindent
3786 In addition, batch provides some small utilities very useful for writing
3787 scripts:
3788
3789 @defun truncate-up-to path char
3790 @defunx truncate-up-to path string
3791 @defunx truncate-up-to path charlist
3792 @var{path} can be a string or a list of strings. Returns @var{path}
3793 sans any prefixes ending with a character of the second argument. This
3794 can be used to derive a filename moved locally from elsewhere.
3795
3796 @example
3797 (truncate-up-to "/usr/local/lib/slib/batch.scm" "/")
3798 @result{} "batch.scm"
3799 @end example
3800 @end defun
3801
3802 @defun string-join joiner string1 @dots{}
3803 Returns a new string consisting of all the strings @var{string1} @dots{}
3804 in order appended together with the string @var{joiner} between each
3805 adjacent pair.
3806 @end defun
3807
3808 @defun must-be-first list1 list2
3809 Returns a new list consisting of the elements of @var{list2} ordered so
3810 that if some elements of @var{list1} are @code{equal?} to elements of
3811 @var{list2}, then those elements will appear first and in the order of
3812 @var{list1}.
3813 @end defun
3814
3815 @defun must-be-last list1 list2
3816 Returns a new list consisting of the elements of @var{list1} ordered so
3817 that if some elements of @var{list2} are @code{equal?} to elements of
3818 @var{list1}, then those elements will appear last and in the order of
3819 @var{list2}.
3820 @end defun
3821
3822 @defun os->batch-dialect osname
3823 Returns its best guess for the @code{batch-dialect} to be used for the
3824 operating-system named @var{osname}. @code{os->batch-dialect} uses the
3825 tables added to @var{database} by @code{batch:initialize!}.
3826 @end defun
3827
3828 @noindent
3829 Here is an example of the use of most of batch's procedures:
3830
3831 @example
3832 (require 'database-utilities)
3833 @ftindex database-utilities
3834 (require 'parameters)
3835 @ftindex parameters
3836 (require 'batch)
3837 @ftindex batch
3838 (require 'glob)
3839 @ftindex glob
3840
3841 (define batch (create-database #f 'alist-table))
3842 (batch:initialize! batch)
3843
3844 (define my-parameters
3845 (list (list 'batch-dialect (os->batch-dialect batch:platform))
3846 (list 'platform batch:platform)
3847 (list 'batch-port (current-output-port)))) ;gets filled in later
3848
3849 (batch:call-with-output-script
3850 my-parameters
3851 "my-batch"
3852 (lambda (batch-port)
3853 (adjoin-parameters! my-parameters (list 'batch-port batch-port))
3854 (and
3855 (batch:comment my-parameters
3856 "================ Write file with C program.")
3857 (batch:rename-file my-parameters "hello.c" "hello.c~")
3858 (batch:lines->file my-parameters "hello.c"
3859 "#include <stdio.h>"
3860 "int main(int argc, char **argv)"
3861 "@{"
3862 " printf(\"hello world\\n\");"
3863 " return 0;"
3864 "@}" )
3865 (batch:command my-parameters "cc" "-c" "hello.c")
3866 (batch:command my-parameters "cc" "-o" "hello"
3867 (replace-suffix "hello.c" ".c" ".o"))
3868 (batch:command my-parameters "hello")
3869 (batch:delete-file my-parameters "hello")
3870 (batch:delete-file my-parameters "hello.c")
3871 (batch:delete-file my-parameters "hello.o")
3872 (batch:delete-file my-parameters "my-batch")
3873 )))
3874 @end example
3875
3876 @noindent
3877 Produces the file @file{my-batch}:
3878
3879 @example
3880 #!/bin/sh
3881 # "my-batch" script created by SLIB/batch Sun Oct 31 18:24:10 1999
3882 # ================ Write file with C program.
3883 mv -f hello.c hello.c~
3884 rm -f hello.c
3885 echo '#include <stdio.h>'>>hello.c
3886 echo 'int main(int argc, char **argv)'>>hello.c
3887 echo '@{'>>hello.c
3888 echo ' printf("hello world\n");'>>hello.c
3889 echo ' return 0;'>>hello.c
3890 echo '@}'>>hello.c
3891 cc -c hello.c
3892 cc -o hello hello.o
3893 hello
3894 rm -f hello
3895 rm -f hello.c
3896 rm -f hello.o
3897 rm -f my-batch
3898 @end example
3899
3900 @noindent
3901 When run, @file{my-batch} prints:
3902
3903 @example
3904 bash$ my-batch
3905 mv: hello.c: No such file or directory
3906 hello world
3907 @end example
3908
3909
3910 @node HTML, HTML Tables, Programs and Arguments, Textual Conversion Packages
3911 @section HTML
3912
3913 @include htmlform.txi
3914
3915
3916 @node HTML Tables, HTTP and CGI, HTML, Textual Conversion Packages
3917 @section HTML Tables
3918
3919 @include db2html.txi
3920
3921
3922 @node HTTP and CGI, URI, HTML Tables, Textual Conversion Packages
3923 @section HTTP and CGI
3924
3925 @include http-cgi.txi
3926
3927
3928 @node URI, Printing Scheme, HTTP and CGI, Textual Conversion Packages
3929 @section URI
3930
3931 @include uri.txi
3932
3933
3934
3935 @node Printing Scheme, Time and Date, URI, Textual Conversion Packages
3936 @section Printing Scheme
3937
3938 @menu
3939 * Generic-Write:: 'generic-write
3940 * Object-To-String:: 'object->string
3941 * Pretty-Print:: 'pretty-print, 'pprint-file
3942 @end menu
3943
3944
3945 @node Generic-Write, Object-To-String, Printing Scheme, Printing Scheme
3946 @subsection Generic-Write
3947
3948 @code{(require 'generic-write)}
3949 @ftindex generic-write
3950
3951 @code{generic-write} is a procedure that transforms a Scheme data value
3952 (or Scheme program expression) into its textual representation and
3953 prints it. The interface to the procedure is sufficiently general to
3954 easily implement other useful formatting procedures such as pretty
3955 printing, output to a string and truncated output.
3956
3957 @deffn Procedure generic-write obj display? width output
3958 @table @var
3959 @item obj
3960 Scheme data value to transform.
3961 @item display?
3962 Boolean, controls whether characters and strings are quoted.
3963 @item width
3964 Extended boolean, selects format:
3965 @table @asis
3966 @item #f
3967 single line format
3968 @item integer > 0
3969 pretty-print (value = max nb of chars per line)
3970 @end table
3971 @item output
3972 Procedure of 1 argument of string type, called repeatedly with
3973 successive substrings of the textual representation. This procedure can
3974 return @code{#f} to stop the transformation.
3975 @end table
3976
3977 The value returned by @code{generic-write} is undefined.
3978
3979 Examples:
3980 @lisp
3981 (write obj) @equiv{} (generic-write obj #f #f @var{display-string})
3982 (display obj) @equiv{} (generic-write obj #t #f @var{display-string})
3983 @end lisp
3984 @noindent
3985 where
3986 @lisp
3987 @var{display-string} @equiv{}
3988 (lambda (s) (for-each write-char (string->list s)) #t)
3989 @end lisp
3990 @end deffn
3991
3992
3993
3994 @node Object-To-String, Pretty-Print, Generic-Write, Printing Scheme
3995 @subsection Object-To-String
3996
3997 @code{(require 'object->string)}
3998 @ftindex object->string
3999
4000 @include obj2str.txi
4001
4002
4003 @node Pretty-Print, , Object-To-String, Printing Scheme
4004 @subsection Pretty-Print
4005
4006 @code{(require 'pretty-print)}
4007 @ftindex pretty-print
4008
4009 @deffn Procedure pretty-print obj
4010 @deffnx Procedure pretty-print obj port
4011
4012 @code{pretty-print}s @var{obj} on @var{port}. If @var{port} is not
4013 specified, @code{current-output-port} is used.
4014
4015 Example:
4016 @example
4017 @group
4018 (pretty-print '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15)
4019 (16 17 18 19 20) (21 22 23 24 25)))
4020 @print{} ((1 2 3 4 5)
4021 @print{} (6 7 8 9 10)
4022 @print{} (11 12 13 14 15)
4023 @print{} (16 17 18 19 20)
4024 @print{} (21 22 23 24 25))
4025 @end group
4026 @end example
4027 @end deffn
4028
4029 @deffn Procedure pretty-print->string obj
4030 @deffnx Procedure pretty-print->string obj width
4031
4032 Returns the string of @var{obj} @code{pretty-print}ed in @var{width}
4033 columns. If @var{width} is not specified, @code{(output-port-width)} is
4034 used.
4035
4036 Example:
4037 @example
4038 @group
4039 (pretty-print->string '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15)
4040 (16 17 18 19 20) (21 22 23 24 25)))
4041 @result{}
4042 "((1 2 3 4 5)
4043 (6 7 8 9 10)
4044 (11 12 13 14 15)
4045 (16 17 18 19 20)
4046 (21 22 23 24 25))
4047 "
4048 @end group
4049 @group
4050 (pretty-print->string '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15)
4051 (16 17 18 19 20) (21 22 23 24 25))
4052 16)
4053 @result{}
4054 "((1 2 3 4 5)
4055 (6 7 8 9 10)
4056 (11
4057 12
4058 13
4059 14
4060 15)
4061 (16
4062 17
4063 18
4064 19
4065 20)
4066 (21
4067 22
4068 23
4069 24
4070 25))
4071 "
4072 @end group
4073 @end example
4074 @end deffn
4075
4076
4077 @code{(require 'pprint-file)}
4078 @ftindex pprint-file
4079
4080 @deffn Procedure pprint-file infile
4081 @deffnx Procedure pprint-file infile outfile
4082 Pretty-prints all the code in @var{infile}. If @var{outfile} is
4083 specified, the output goes to @var{outfile}, otherwise it goes to
4084 @code{(current-output-port)}.
4085 @end deffn
4086
4087 @defun pprint-filter-file infile proc outfile
4088 @defunx pprint-filter-file infile proc
4089 @var{infile} is a port or a string naming an existing file. Scheme
4090 source code expressions and definitions are read from the port (or file)
4091 and @var{proc} is applied to them sequentially.
4092
4093 @var{outfile} is a port or a string. If no @var{outfile} is specified
4094 then @code{current-output-port} is assumed. These expanded expressions
4095 are then @code{pretty-print}ed to this port.
4096
4097 Whitepsace and comments (introduced by @code{;}) which are not part of
4098 scheme expressions are reproduced in the output. This procedure does
4099 not affect the values returned by @code{current-input-port} and
4100 @code{current-output-port}.
4101 @end defun
4102
4103 @code{pprint-filter-file} can be used to pre-compile macro-expansion and
4104 thus can reduce loading time. The following will write into
4105 @file{exp-code.scm} the result of expanding all defmacros in
4106 @file{code.scm}.
4107 @lisp
4108 (require 'pprint-file)
4109 @ftindex pprint-file
4110 (require 'defmacroexpand)
4111 @ftindex defmacroexpand
4112 (defmacro:load "my-macros.scm")
4113 (pprint-filter-file "code.scm" defmacro:expand* "exp-code.scm")
4114 @end lisp
4115
4116 @node Time and Date, Vector Graphics, Printing Scheme, Textual Conversion Packages
4117 @section Time and Date
4118
4119 @menu
4120 * Time Zone::
4121 * Posix Time:: 'posix-time
4122 * Common-Lisp Time:: 'common-lisp-time
4123 @end menu
4124
4125 @noindent
4126 If @code{(provided? 'current-time)}:
4127
4128 @noindent
4129 The procedures @code{current-time}, @code{difftime}, and
4130 @code{offset-time} deal with a @dfn{calendar time} datatype
4131 @cindex time
4132 @cindex calendar time
4133 which may or may not be disjoint from other Scheme datatypes.
4134
4135 @defun current-time
4136 Returns the time since 00:00:00 GMT, January 1, 1970, measured in
4137 seconds. Note that the reference time is different from the reference
4138 time for @code{get-universal-time} in @ref{Common-Lisp Time}.
4139 @end defun
4140
4141 @defun difftime caltime1 caltime0
4142 Returns the difference (number of seconds) between twe calendar times:
4143 @var{caltime1} - @var{caltime0}. @var{caltime0} may also be a number.
4144 @end defun
4145
4146 @defun offset-time caltime offset
4147 Returns the calendar time of @var{caltime} offset by @var{offset} number
4148 of seconds @code{(+ caltime offset)}.
4149 @end defun
4150
4151 @node Time Zone, Posix Time, Time and Date, Time and Date
4152 @subsection Time Zone
4153
4154 (require 'time-zone)
4155
4156 @deftp {Data Format} TZ-string
4157
4158 POSIX standards specify several formats for encoding time-zone rules.
4159
4160 @table @t
4161 @item :@i{<pathname>}
4162 If the first character of @i{<pathname>} is @samp{/}, then
4163 @i{<pathname>} specifies the absolute pathname of a tzfile(5) format
4164 time-zone file. Otherwise, @i{<pathname>} is interpreted as a pathname
4165 within @var{tzfile:vicinity} (/usr/lib/zoneinfo/) naming a tzfile(5)
4166 format time-zone file.
4167 @item @i{<std>}@i{<offset>}
4168 The string @i{<std>} consists of 3 or more alphabetic characters.
4169 @i{<offset>} specifies the time difference from GMT. The @i{<offset>}
4170 is positive if the local time zone is west of the Prime Meridian and
4171 negative if it is east. @i{<offset>} can be the number of hours or
4172 hours and minutes (and optionally seconds) separated by @samp{:}. For
4173 example, @code{-4:30}.
4174 @item @i{<std>}@i{<offset>}@i{<dst>}
4175 @i{<dst>} is the at least 3 alphabetic characters naming the local
4176 daylight-savings-time.
4177 @item @i{<std>}@i{<offset>}@i{<dst>}@i{<doffset>}
4178 @i{<doffset>} specifies the offset from the Prime Meridian when
4179 daylight-savings-time is in effect.
4180 @end table
4181
4182 The non-tzfile formats can optionally be followed by transition times
4183 specifying the day and time when a zone changes from standard to
4184 daylight-savings and back again.
4185
4186 @table @t
4187 @item ,@i{<date>}/@i{<time>},@i{<date>}/@i{<time>}
4188 The @i{<time>}s are specified like the @i{<offset>}s above, except that
4189 leading @samp{+} and @samp{-} are not allowed.
4190
4191 Each @i{<date>} has one of the formats:
4192
4193 @table @t
4194 @item J@i{<day>}
4195 specifies the Julian day with @i{<day>} between 1 and 365. February 29
4196 is never counted and cannot be referenced.
4197 @item @i{<day>}
4198 This specifies the Julian day with n between 0 and 365. February 29 is
4199 counted in leap years and can be specified.
4200 @item M@i{<month>}.@i{<week>}.@i{<day>}
4201 This specifies day @i{<day>} (0 <= @i{<day>} <= 6) of week @i{<week>} (1
4202 <= @i{<week>} <= 5) of month @i{<month>} (1 <= @i{<month>} <= 12). Week
4203 1 is the first week in which day d occurs and week 5 is the last week in
4204 which day @i{<day>} occurs. Day 0 is a Sunday.
4205 @end table
4206 @end table
4207
4208 @end deftp
4209
4210 @deftp {Data Type} time-zone
4211 is a datatype encoding how many hours from Greenwich Mean Time the local
4212 time is, and the @dfn{Daylight Savings Time} rules for changing it.
4213 @end deftp
4214
4215 @defun time-zone TZ-string
4216 Creates and returns a time-zone object specified by the string
4217 @var{TZ-string}. If @code{time-zone} cannot interpret @var{TZ-string},
4218 @code{#f} is returned.
4219 @end defun
4220
4221 @defun tz:params caltime tz
4222 @var{tz} is a time-zone object. @code{tz:params} returns a list of
4223 three items:
4224 @enumerate 0
4225 @item
4226 An integer. 0 if standard time is in effect for timezone @var{tz} at
4227 @var{caltime}; 1 if daylight savings time is in effect for timezone
4228 @var{tz} at @var{caltime}.
4229 @item
4230 The number of seconds west of the Prime Meridian timezone @var{tz} is at
4231 @var{caltime}.
4232 @item
4233 The name for timezone @var{tz} at @var{caltime}.
4234 @end enumerate
4235
4236 @code{tz:params} is unaffected by the default timezone; inquiries can be
4237 made of any timezone at any calendar time.
4238
4239 @end defun
4240
4241 @noindent
4242 The rest of these procedures and variables are provided for POSIX
4243 compatability. Because of shared state they are not thread-safe.
4244
4245 @defun tzset
4246 Returns the default time-zone.
4247
4248 @defunx tzset tz
4249 Sets (and returns) the default time-zone to @var{tz}.
4250
4251 @defunx tzset TZ-string
4252 Sets (and returns) the default time-zone to that specified by
4253 @var{TZ-string}.
4254
4255 @code{tzset} also sets the variables @var{*timezone*}, @var{daylight?},
4256 and @var{tzname}. This function is automatically called by the time
4257 conversion procedures which depend on the time zone (@pxref{Time and
4258 Date}).
4259 @end defun
4260
4261 @defvar *timezone*
4262 Contains the difference, in seconds, between Greenwich Mean Time and
4263 local standard time (for example, in the U.S. Eastern time zone (EST),
4264 timezone is 5*60*60). @code{*timezone*} is initialized by @code{tzset}.
4265 @end defvar
4266
4267 @defvar daylight?
4268 is @code{#t} if the default timezone has rules for @dfn{Daylight Savings
4269 Time}. @emph{Note:} @var{daylight?} does not tell you when Daylight
4270 Savings Time is in effect, just that the default zone sometimes has
4271 Daylight Savings Time.
4272 @end defvar
4273
4274 @defvar tzname
4275 is a vector of strings. Index 0 has the abbreviation for the standard
4276 timezone; If @var{daylight?}, then index 1 has the abbreviation for the
4277 Daylight Savings timezone.
4278 @end defvar
4279
4280
4281 @node Posix Time, Common-Lisp Time, Time Zone, Time and Date
4282 @subsection Posix Time
4283
4284 @example
4285 (require 'posix-time)
4286 @ftindex posix-time
4287 @end example
4288
4289 @deftp {Data Type} {Calendar-Time}
4290 @cindex calendar time
4291 @cindex caltime
4292 is a datatype encapsulating time.
4293 @end deftp
4294
4295 @deftp {Data Type} {Coordinated Universal Time}
4296 @cindex Coordinated Universal Time
4297 @cindex UTC
4298 (abbreviated @dfn{UTC}) is a vector of integers representing time:
4299
4300 @enumerate 0
4301 @item
4302 seconds (0 - 61)
4303 @item
4304 minutes (0 - 59)
4305 @item
4306 hours since midnight (0 - 23)
4307 @item
4308 day of month (1 - 31)
4309 @item
4310 month (0 - 11). Note difference from @code{decode-universal-time}.
4311 @item
4312 the number of years since 1900. Note difference from
4313 @code{decode-universal-time}.
4314 @item
4315 day of week (0 - 6)
4316 @item
4317 day of year (0 - 365)
4318 @item
4319 1 for daylight savings, 0 for regular time
4320 @end enumerate
4321 @end deftp
4322
4323 @defun gmtime caltime
4324 Converts the calendar time @var{caltime} to UTC and returns it.
4325
4326 @defunx localtime caltime tz
4327 Returns @var{caltime} converted to UTC relative to timezone @var{tz}.
4328
4329 @defunx localtime caltime
4330 converts the calendar time @var{caltime} to a vector of integers
4331 expressed relative to the user's time zone. @code{localtime} sets the
4332 variable @var{*timezone*} with the difference between Coordinated
4333 Universal Time (UTC) and local standard time in seconds
4334 (@pxref{Time Zone,tzset}).
4335
4336 @end defun
4337
4338 @defun gmktime univtime
4339 Converts a vector of integers in GMT Coordinated Universal Time (UTC)
4340 format to a calendar time.
4341
4342 @defunx mktime univtime
4343 Converts a vector of integers in local Coordinated Universal Time (UTC)
4344 format to a calendar time.
4345
4346 @defunx mktime univtime tz
4347 Converts a vector of integers in Coordinated Universal Time (UTC) format
4348 (relative to time-zone @var{tz})
4349 to calendar time.
4350 @end defun
4351
4352 @defun asctime univtime
4353 Converts the vector of integers @var{caltime} in Coordinated
4354 Universal Time (UTC) format into a string of the form
4355 @code{"Wed Jun 30 21:49:08 1993"}.
4356 @end defun
4357
4358 @defun gtime caltime
4359 @defunx ctime caltime
4360 @defunx ctime caltime tz
4361 Equivalent to @code{(asctime (gmtime @var{caltime}))},
4362 @code{(asctime (localtime @var{caltime}))}, and
4363 @code{(asctime (localtime @var{caltime} @var{tz}))}, respectively.
4364 @end defun
4365
4366
4367 @node Common-Lisp Time, , Posix Time, Time and Date
4368 @subsection Common-Lisp Time
4369
4370 @defun get-decoded-time
4371 Equivalent to @code{(decode-universal-time (get-universal-time))}.
4372 @end defun
4373
4374 @defun get-universal-time
4375 Returns the current time as @dfn{Universal Time}, number of seconds
4376 since 00:00:00 Jan 1, 1900 GMT. Note that the reference time is
4377 different from @code{current-time}.
4378 @end defun
4379
4380 @defun decode-universal-time univtime
4381 Converts @var{univtime} to @dfn{Decoded Time} format.
4382 Nine values are returned:
4383 @enumerate 0
4384 @item
4385 seconds (0 - 61)
4386 @item
4387 minutes (0 - 59)
4388 @item
4389 hours since midnight
4390 @item
4391 day of month
4392 @item
4393 month (1 - 12). Note difference from @code{gmtime} and @code{localtime}.
4394 @item
4395 year (A.D.). Note difference from @code{gmtime} and @code{localtime}.
4396 @item
4397 day of week (0 - 6)
4398 @item
4399 #t for daylight savings, #f otherwise
4400 @item
4401 hours west of GMT (-24 - +24)
4402 @end enumerate
4403
4404 Notice that the values returned by @code{decode-universal-time} do not
4405 match the arguments to @code{encode-universal-time}.
4406 @end defun
4407
4408 @defun encode-universal-time second minute hour date month year
4409 @defunx encode-universal-time second minute hour date month year time-zone
4410 Converts the arguments in Decoded Time format to Universal Time format.
4411 If @var{time-zone} is not specified, the returned time is adjusted for
4412 daylight saving time. Otherwise, no adjustment is performed.
4413
4414 Notice that the values returned by @code{decode-universal-time} do not
4415 match the arguments to @code{encode-universal-time}.
4416 @end defun
4417
4418
4419 @node Vector Graphics, Schmooz, Time and Date, Textual Conversion Packages
4420 @section Vector Graphics
4421
4422 @menu
4423 * Tektronix Graphics Support::
4424 @end menu
4425
4426 @node Tektronix Graphics Support, , Vector Graphics, Vector Graphics
4427 @subsection Tektronix Graphics Support
4428
4429 @emph{Note:} The Tektronix graphics support files need more work, and
4430 are not complete.
4431
4432 @subsubsection Tektronix 4000 Series Graphics
4433
4434 The Tektronix 4000 series graphics protocol gives the user a 1024 by
4435 1024 square drawing area. The origin is in the lower left corner of the
4436 screen. Increasing y is up and increasing x is to the right.
4437
4438 The graphics control codes are sent over the current-output-port and can
4439 be mixed with regular text and ANSI or other terminal control sequences.
4440
4441 @deffn Procedure tek40:init
4442 @end deffn
4443
4444 @deffn Procedure tek40:graphics
4445 @end deffn
4446
4447 @deffn Procedure tek40:text
4448 @end deffn
4449
4450 @deffn Procedure tek40:linetype linetype
4451 @end deffn
4452
4453 @deffn Procedure tek40:move x y
4454 @end deffn
4455
4456 @deffn Procedure tek40:draw x y
4457 @end deffn
4458
4459 @deffn Procedure tek40:put-text x y str
4460 @end deffn
4461
4462 @deffn Procedure tek40:reset
4463 @end deffn
4464
4465
4466 @subsubsection Tektronix 4100 Series Graphics
4467
4468 The graphics control codes are sent over the current-output-port and can
4469 be mixed with regular text and ANSI or other terminal control sequences.
4470
4471 @deffn Procedure tek41:init
4472 @end deffn
4473
4474 @deffn Procedure tek41:reset
4475 @end deffn
4476
4477 @deffn Procedure tek41:graphics
4478 @end deffn
4479
4480 @deffn Procedure tek41:move x y
4481 @end deffn
4482
4483 @deffn Procedure tek41:draw x y
4484 @end deffn
4485
4486 @deffn Procedure tek41:point x y number
4487 @end deffn
4488
4489 @deffn Procedure tek41:encode-x-y x y
4490 @end deffn
4491
4492 @deffn Procedure tek41:encode-int number
4493 @end deffn
4494
4495 @node Schmooz, , Vector Graphics, Textual Conversion Packages
4496 @section Schmooz
4497
4498 @include schmooz.texi
4499
4500 @node Mathematical Packages, Database Packages, Textual Conversion Packages, Top
4501 @chapter Mathematical Packages
4502
4503 @menu
4504 * Bit-Twiddling:: 'logical
4505 * Modular Arithmetic:: 'modular
4506 * Prime Numbers:: 'factor
4507 * Random Numbers:: 'random
4508 * Fast Fourier Transform:: 'fft
4509 * Cyclic Checksum:: 'make-crc
4510 * Plotting:: 'charplot
4511 * Root Finding:: 'root
4512 * Minimizing:: 'minimize
4513 * Commutative Rings:: 'commutative-ring
4514 * Determinant:: 'determinant
4515 @end menu
4516
4517
4518 @node Bit-Twiddling, Modular Arithmetic, Mathematical Packages, Mathematical Packages
4519 @section Bit-Twiddling
4520
4521 @code{(require 'logical)}
4522 @ftindex logical
4523
4524 The bit-twiddling functions are made available through the use of the
4525 @code{logical} package. @code{logical} is loaded by inserting
4526 @code{(require 'logical)} before the code that uses these
4527 @ftindex logical
4528 functions. These functions behave as though operating on integers
4529 in two's-complement representation.
4530
4531 @subheading Bitwise Operations
4532
4533 @defun logand n1 n1
4534 Returns the integer which is the bit-wise AND of the two integer
4535 arguments.
4536
4537 Example:
4538 @lisp
4539 (number->string (logand #b1100 #b1010) 2)
4540 @result{} "1000"
4541 @end lisp
4542 @end defun
4543
4544 @defun logior n1 n2
4545 Returns the integer which is the bit-wise OR of the two integer
4546 arguments.
4547
4548 Example:
4549 @lisp
4550 (number->string (logior #b1100 #b1010) 2)
4551 @result{} "1110"
4552 @end lisp
4553 @end defun
4554
4555 @defun logxor n1 n2
4556 Returns the integer which is the bit-wise XOR of the two integer
4557 arguments.
4558
4559 Example:
4560 @lisp
4561 (number->string (logxor #b1100 #b1010) 2)
4562 @result{} "110"
4563 @end lisp
4564 @end defun
4565
4566 @defun lognot n
4567 Returns the integer which is the 2s-complement of the integer argument.
4568
4569 Example:
4570 @lisp
4571 (number->string (lognot #b10000000) 2)
4572 @result{} "-10000001"
4573 (number->string (lognot #b0) 2)
4574 @result{} "-1"
4575 @end lisp
4576 @end defun
4577
4578 @defun bitwise-if mask n0 n1
4579 Returns an integer composed of some bits from integer @var{n0} and some
4580 from integer @var{n1}. A bit of the result is taken from @var{n0} if the
4581 corresponding bit of integer @var{mask} is 1 and from @var{n1} if that bit
4582 of @var{mask} is 0.
4583 @end defun
4584
4585 @defun logtest j k
4586 @example
4587 (logtest j k) @equiv{} (not (zero? (logand j k)))
4588
4589 (logtest #b0100 #b1011) @result{} #f
4590 (logtest #b0100 #b0111) @result{} #t
4591 @end example
4592 @end defun
4593
4594 @defun logcount n
4595 Returns the number of bits in integer @var{n}. If integer is positive,
4596 the 1-bits in its binary representation are counted. If negative, the
4597 0-bits in its two's-complement binary representation are counted. If 0,
4598 0 is returned.
4599
4600 Example:
4601 @lisp
4602 (logcount #b10101010)
4603 @result{} 4
4604 (logcount 0)
4605 @result{} 0
4606 (logcount -2)
4607 @result{} 1
4608 @end lisp
4609 @end defun
4610
4611
4612 @subheading Bit Within Word
4613
4614 @defun logbit? index j
4615 @example
4616 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
4617
4618 (logbit? 0 #b1101) @result{} #t
4619 (logbit? 1 #b1101) @result{} #f
4620 (logbit? 2 #b1101) @result{} #t
4621 (logbit? 3 #b1101) @result{} #t
4622 (logbit? 4 #b1101) @result{} #f
4623 @end example
4624 @end defun
4625
4626 @defun copy-bit index from bit
4627 Returns an integer the same as @var{from} except in the @var{index}th bit,
4628 which is 1 if @var{bit} is @code{#t} and 0 if @var{bit} is @code{#f}.
4629
4630 Example:
4631 @example
4632 (number->string (copy-bit 0 0 #t) 2) @result{} "1"
4633 (number->string (copy-bit 2 0 #t) 2) @result{} "100"
4634 (number->string (copy-bit 2 #b1111 #f) 2) @result{} "1011"
4635 @end example
4636 @end defun
4637
4638 @subheading Fields of Bits
4639
4640 @defun bit-field n start end
4641 @findex bit-extract
4642 Returns the integer composed of the @var{start} (inclusive) through
4643 @var{end} (exclusive) bits of @var{n}. The @var{start}th bit becomes
4644 the 0-th bit in the result.
4645
4646 This function was called @code{bit-extract} in previous versions of SLIB.
4647 @refill
4648
4649 Example:
4650 @lisp
4651 (number->string (bit-field #b1101101010 0 4) 2)
4652 @result{} "1010"
4653 (number->string (bit-field #b1101101010 4 9) 2)
4654 @result{} "10110"
4655 @end lisp
4656 @end defun
4657
4658 @defun copy-bit-field to start end from
4659 Returns an integer the same as @var{to} except possibly in the
4660 @var{start} (inclusive) through @var{end} (exclusive) bits, which are
4661 the same as those of @var{from}. The 0-th bit of @var{from} becomes the
4662 @var{start}th bit of the result.
4663
4664 Example:
4665 @example
4666 (number->string (copy-bit-field #b1101101010 0 4 0) 2)
4667 @result{} "1101100000"
4668 (number->string (copy-bit-field #b1101101010 0 4 -1) 2)
4669 @result{} "1101101111"
4670 @end example
4671 @end defun
4672
4673 @defun ash int count
4674 Returns an integer equivalent to
4675 @code{(inexact->exact (floor (* @var{int} (expt 2 @var{count}))))}.
4676
4677 Example:
4678 @lisp
4679 (number->string (ash #b1 3) 2)
4680 @result{} "1000"
4681 (number->string (ash #b1010 -1) 2)
4682 @result{} "101"
4683 @end lisp
4684 @end defun
4685
4686 @defun integer-length n
4687 Returns the number of bits neccessary to represent @var{n}.
4688
4689 Example:
4690 @lisp
4691 (integer-length #b10101010)
4692 @result{} 8
4693 (integer-length 0)
4694 @result{} 0
4695 (integer-length #b1111)
4696 @result{} 4
4697 @end lisp
4698 @end defun
4699
4700 @defun integer-expt n k
4701 Returns @var{n} raised to the non-negative integer exponent @var{k}.
4702
4703 Example:
4704 @lisp
4705 (integer-expt 2 5)
4706 @result{} 32
4707 (integer-expt -3 3)
4708 @result{} -27
4709 @end lisp
4710 @end defun
4711
4712 @node Modular Arithmetic, Prime Numbers, Bit-Twiddling, Mathematical Packages
4713 @section Modular Arithmetic
4714
4715 @code{(require 'modular)}
4716 @ftindex modular
4717
4718 @defun extended-euclid n1 n2
4719 Returns a list of 3 integers @code{(d x y)} such that d = gcd(@var{n1},
4720 @var{n2}) = @var{n1} * x + @var{n2} * y.
4721 @end defun
4722
4723 @defun symmetric:modulus n
4724 Returns @code{(quotient (+ -1 n) -2)} for positive odd integer @var{n}.
4725 @end defun
4726
4727 @defun modulus->integer modulus
4728 Returns the non-negative integer characteristic of the ring formed when
4729 @var{modulus} is used with @code{modular:} procedures.
4730 @end defun
4731
4732 @defun modular:normalize modulus n
4733 Returns the integer @code{(modulo @var{n} (modulus->integer
4734 @var{modulus}))} in the representation specified by @var{modulus}.
4735 @end defun
4736
4737 @noindent
4738 The rest of these functions assume normalized arguments; That is, the
4739 arguments are constrained by the following table:
4740
4741 @noindent
4742 For all of these functions, if the first argument (@var{modulus}) is:
4743 @table @code
4744 @item positive?
4745 Work as before. The result is between 0 and @var{modulus}.
4746
4747 @item zero?
4748 The arguments are treated as integers. An integer is returned.
4749
4750 @item negative?
4751 The arguments and result are treated as members of the integers modulo
4752 @code{(+ 1 (* -2 @var{modulus}))}, but with @dfn{symmetric}
4753 representation; i.e. @code{(<= (- @var{modulus}) @var{n}
4754 @var{modulus})}.
4755 @end table
4756
4757 @noindent
4758 If all the arguments are fixnums the computation will use only fixnums.
4759
4760 @defun modular:invertable? modulus k
4761 Returns @code{#t} if there exists an integer n such that @var{k} * n
4762 @equiv{} 1 mod @var{modulus}, and @code{#f} otherwise.
4763 @end defun
4764
4765 @defun modular:invert modulus k2
4766 Returns an integer n such that 1 = (n * @var{k2}) mod @var{modulus}. If
4767 @var{k2} has no inverse mod @var{modulus} an error is signaled.
4768 @end defun
4769
4770 @defun modular:negate modulus k2
4771 Returns (@minus{}@var{k2}) mod @var{modulus}.
4772 @end defun
4773
4774 @defun modular:+ modulus k2 k3
4775 Returns (@var{k2} + @var{k3}) mod @var{modulus}.
4776 @end defun
4777
4778 @defun modular:@minus{} modulus k2 k3
4779 Returns (@var{k2} @minus{} @var{k3}) mod @var{modulus}.
4780 @end defun
4781
4782 @defun modular:* modulus k2 k3
4783 Returns (@var{k2} * @var{k3}) mod @var{modulus}.
4784
4785 The Scheme code for @code{modular:*} with negative @var{modulus} is not
4786 completed for fixnum-only implementations.
4787 @end defun
4788
4789 @defun modular:expt modulus k2 k3
4790 Returns (@var{k2} ^ @var{k3}) mod @var{modulus}.
4791 @end defun
4792
4793
4794
4795 @node Prime Numbers, Random Numbers, Modular Arithmetic, Mathematical Packages
4796 @section Prime Numbers
4797
4798 @code{(require 'factor)}
4799 @ftindex factor
4800 @ftindex primes
4801
4802 @include factor.txi
4803
4804
4805 @node Random Numbers, Fast Fourier Transform, Prime Numbers, Mathematical Packages
4806 @section Random Numbers
4807
4808 @code{(require 'random)}
4809 @ftindex random
4810
4811 @cindex RNG
4812 @cindex PRNG
4813 A pseudo-random number generator is only as good as the tests it passes.
4814 George Marsaglia of Florida State University developed a battery of
4815 tests named @dfn{DIEHARD} (@url{http://stat.fsu.edu/~geo/diehard.html}).
4816 @file{diehard.c} has a bug which the patch
4817 @url{http://swissnet.ai.mit.edu/ftpdir/users/jaffer/diehard.c.pat} corrects.
4818
4819 SLIB's new PRNG generates 8 bits at a time. With the degenerate seed
4820 @samp{0}, the numbers generated pass DIEHARD; but when bits are combined
4821 from sequential bytes, tests fail. With the seed
4822 @samp{http://swissnet.ai.mit.edu/~jaffer/SLIB.html}, all of those tests
4823 pass.
4824
4825 @include random.txi
4826
4827
4828 If inexact numbers are supported by the Scheme implementation,
4829 @file{randinex.scm} will be loaded as well. @file{randinex.scm}
4830 contains procedures for generating inexact distributions.
4831
4832 @include randinex.txi
4833
4834
4835 @node Fast Fourier Transform, Cyclic Checksum, Random Numbers, Mathematical Packages
4836 @section Fast Fourier Transform
4837
4838 @code{(require 'fft)}
4839 @ftindex fft
4840
4841 @defun fft array
4842 @var{array} is an array of @code{(expt 2 n)} numbers. @code{fft}
4843 returns an array of complex numbers comprising the @dfn{Discrete Fourier
4844 Transform} of @var{array}.
4845
4846 @defunx fft-1 array
4847 @code{fft-1} returns an array of complex numbers comprising the inverse
4848 Discrete Fourier Transform of @var{array}.
4849 @end defun
4850
4851 @code{(fft-1 (fft @var{array}))} will return an array of values close to
4852 @var{array}.
4853
4854 @example
4855 (fft '#(1 0+i -1 0-i 1 0+i -1 0-i)) @result{}
4856
4857 #(0.0 0.0 0.0+628.0783185208527e-18i 0.0
4858 0.0 0.0 8.0-628.0783185208527e-18i 0.0)
4859
4860 (fft-1 '#(0 0 0 0 0 0 8 0)) @result{}
4861
4862 #(1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i
4863 1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i)
4864 @end example
4865
4866
4867 @node Cyclic Checksum, Plotting, Fast Fourier Transform, Mathematical Packages
4868 @section Cyclic Checksum
4869
4870 @code{(require 'make-crc)}
4871 @ftindex make-crc
4872
4873 @defun make-port-crc
4874 @defunx make-port-crc degree
4875 Returns an expression for a procedure of one argument, a port. This
4876 procedure reads characters from the port until the end of file and
4877 returns the integer checksum of the bytes read.
4878
4879 The integer @var{degree}, if given, specifies the degree of the
4880 polynomial being computed -- which is also the number of bits computed
4881 in the checksums. The default value is 32.
4882
4883 @defunx make-port-crc generator
4884
4885 The integer @var{generator} specifies the polynomial being computed.
4886 The power of 2 generating each 1 bit is the exponent of a term of the
4887 polynomial. The value of @var{generator} must be larger than 127.
4888
4889 @defunx make-port-crc degree generator
4890
4891 The integer @var{generator} specifies the polynomial being computed.
4892 The power of 2 generating each 1 bit is the exponent of a term of the
4893 polynomial. The bit at position @var{degree} is implicit and should not
4894 be part of @var{generator}. This allows systems with numbers limited to
4895 32 bits to calculate 32 bit checksums. The default value of
4896 @var{generator} when @var{degree} is 32 (its default) is:
4897
4898 @example
4899 (make-port-crc 32 #b00000100110000010001110110110111)
4900 @end example
4901
4902 Creates a procedure to calculate the P1003.2/D11.2 (POSIX.2) 32-bit
4903 checksum from the polynomial:
4904
4905 @example
4906 32 26 23 22 16 12 11
4907 ( x + x + x + x + x + x + x +
4908
4909 10 8 7 5 4 2 1
4910 x + x + x + x + x + x + x + 1 ) mod 2
4911 @end example
4912 @end defun
4913
4914 @example
4915 (require 'make-crc)
4916 @ftindex make-crc
4917 (define crc32 (slib:eval (make-port-crc)))
4918 (define (file-check-sum file) (call-with-input-file file crc32))
4919 (file-check-sum (in-vicinity (library-vicinity) "ratize.scm"))
4920
4921 @result{} 157103930
4922 @end example
4923
4924 @node Plotting, Root Finding, Cyclic Checksum, Mathematical Packages
4925 @section Plotting on Character Devices
4926
4927 @code{(require 'charplot)}
4928 @ftindex charplot
4929
4930 The plotting procedure is made available through the use of the
4931 @code{charplot} package. @code{charplot} is loaded by inserting
4932 @code{(require 'charplot)} before the code that uses this procedure.
4933 @ftindex charplot
4934
4935 @defvar charplot:height
4936 The number of rows to make the plot vertically.
4937 @end defvar
4938
4939 @defvar charplot:width
4940 The number of columns to make the plot horizontally.
4941 @end defvar
4942
4943 @deffn Procedure plot! coords x-label y-label
4944 @var{coords} is a list of pairs of x and y coordinates. @var{x-label}
4945 and @var{y-label} are strings with which to label the x and y
4946 axes.
4947
4948 Example:
4949 @example
4950 (require 'charplot)
4951 @ftindex charplot
4952 (set! charplot:height 19)
4953 (set! charplot:width 45)
4954
4955 (define (make-points n)
4956 (if (zero? n)
4957 '()
4958 (cons (cons (/ n 6) (sin (/ n 6))) (make-points (1- n)))))
4959
4960 (plot! (make-points 37) "x" "Sin(x)")
4961 @print{}
4962 @group
4963 Sin(x) ______________________________________________
4964 1.25|- |
4965 | |
4966 1|- **** |
4967 | ** ** |
4968 0.75|- * * |
4969 | * * |
4970 0.5|- * * |
4971 | * |
4972 0.25|- * |
4973 | * * |
4974 0|-------------------*--------------------------|
4975 | * |
4976 -0.25|- * * |
4977 | * * |
4978 -0.5|- * |
4979 | * * |
4980 -0.75|- * * |
4981 | ** ** |
4982 -1|- **** |
4983 |____________:_____._____:_____._____:_________|
4984 x 2 4 6
4985 @end group
4986 @end example
4987 @end deffn
4988
4989 @deffn Procedure plot-function! func x1 x2
4990 @deffnx Procedure plot-function! func x1 x2 npts
4991 Plots the function of one argument @var{func} over the range @var{x1} to
4992 @var{x2}. If the optional integer argument @var{npts} is supplied, it
4993 specifies the number of points to evaluate @var{func} at.
4994 @end deffn
4995
4996
4997 @node Root Finding, Minimizing, Plotting, Mathematical Packages
4998 @section Root Finding
4999
5000 @code{(require 'root)}
5001 @ftindex root
5002
5003 @defun newtown:find-integer-root f df/dx x0
5004 Given integer valued procedure @var{f}, its derivative (with respect to
5005 its argument) @var{df/dx}, and initial integer value @var{x0} for which
5006 @var{df/dx}(@var{x0}) is non-zero, returns an integer @var{x} for which
5007 @var{f}(@var{x}) is closer to zero than either of the integers adjacent
5008 to @var{x}; or returns @code{#f} if such an integer can't be found.
5009
5010 To find the closest integer to a given integers square root:
5011
5012 @example
5013 (define (integer-sqrt y)
5014 (newton:find-integer-root
5015 (lambda (x) (- (* x x) y))
5016 (lambda (x) (* 2 x))
5017 (ash 1 (quotient (integer-length y) 2))))
5018
5019 (integer-sqrt 15) @result{} 4
5020 @end example
5021 @end defun
5022
5023 @defun integer-sqrt y
5024 Given a non-negative integer @var{y}, returns the rounded square-root of
5025 @var{y}.
5026 @end defun
5027
5028 @defun newton:find-root f df/dx x0 prec
5029 Given real valued procedures @var{f}, @var{df/dx} of one (real)
5030 argument, initial real value @var{x0} for which @var{df/dx}(@var{x0}) is
5031 non-zero, and positive real number @var{prec}, returns a real @var{x}
5032 for which @code{abs}(@var{f}(@var{x})) is less than @var{prec}; or
5033 returns @code{#f} if such a real can't be found.
5034
5035 If @var{prec} is instead a negative integer, @code{newton:find-root}
5036 returns the result of -@var{prec} iterations.
5037 @end defun
5038
5039 @noindent
5040 H. J. Orchard, @cite{The Laguerre Method for Finding the Zeros of
5041 Polynomials}, IEEE Transactions on Circuits and Systems, Vol. 36,
5042 No. 11, November 1989, pp 1377-1381.
5043
5044 @quotation
5045 There are 2 errors in Orchard's Table II. Line k=2 for starting
5046 value of 1000+j0 should have Z_k of 1.0475 + j4.1036 and line k=2
5047 for starting value of 0+j1000 should have Z_k of 1.0988 + j4.0833.
5048 @end quotation
5049
5050
5051 @defun laguerre:find-root f df/dz ddf/dz^2 z0 prec
5052 Given complex valued procedure @var{f} of one (complex) argument, its
5053 derivative (with respect to its argument) @var{df/dx}, its second
5054 derivative @var{ddf/dz^2}, initial complex value @var{z0}, and positive
5055 real number @var{prec}, returns a complex number @var{z} for which
5056 @code{magnitude}(@var{f}(@var{z})) is less than @var{prec}; or returns
5057 @code{#f} if such a number can't be found.
5058
5059 If @var{prec} is instead a negative integer, @code{laguerre:find-root}
5060 returns the result of -@var{prec} iterations.
5061 @end defun
5062
5063 @defun laguerre:find-polynomial-root deg f df/dz ddf/dz^2 z0 prec
5064 Given polynomial procedure @var{f} of integer degree @var{deg} of one
5065 argument, its derivative (with respect to its argument) @var{df/dx}, its
5066 second derivative @var{ddf/dz^2}, initial complex value @var{z0}, and
5067 positive real number @var{prec}, returns a complex number @var{z} for
5068 which @code{magnitude}(@var{f}(@var{z})) is less than @var{prec}; or
5069 returns @code{#f} if such a number can't be found.
5070
5071 If @var{prec} is instead a negative integer,
5072 @code{laguerre:find-polynomial-root} returns the result of -@var{prec}
5073 iterations.
5074 @end defun
5075
5076 @defun secant:find-root f x0 x1 prec
5077 @defunx secant:find-bracketed-root f x0 x1 prec
5078 Given a real valued procedure @var{f} and two real valued starting
5079 points @var{x0} and @var{x1}, returns a real @var{x} for which
5080 @code{(abs (f x))} is less than @var{prec}; or returns
5081 @code{#f} if such a real can't be found.
5082
5083 If @var{x0} and @var{x1} are chosen such that they bracket a root, that is
5084 @example
5085 (or (< (f x0) 0 (f x1))
5086 (< (f x1) 0 (f x0)))
5087 @end example
5088 then the root returned will be between @var{x0} and @var{x1}, and
5089 @var{f} will not be passed an argument outside of that interval.
5090
5091 @code{secant:find-bracketed-root} will return @code{#f} unless @var{x0}
5092 and @var{x1} bracket a root.
5093
5094 The secant method is used until a bracketing interval is found, at which point
5095 a modified @i{regula falsi} method is used.
5096
5097 If @var{prec} is instead a negative integer, @code{secant:find-root}
5098 returns the result of -@var{prec} iterations.
5099
5100 If @var{prec} is a procedure it should accept 5 arguments: @var{x0}
5101 @var{f0} @var{x1} @var{f1} and @var{count}, where @var{f0} will be
5102 @code{(f x0)}, @var{f1} @code{(f x1)}, and @var{count} the number of
5103 iterations performed so far. @var{prec} should return non-false
5104 if the iteration should be stopped.
5105 @end defun
5106
5107 @node Minimizing, Commutative Rings, Root Finding, Mathematical Packages
5108 @section Minimizing
5109
5110 @code{(require 'minimize)}
5111 @ftindex minimize
5112 @cindex minimize
5113
5114 @include minimize.txi
5115
5116 @node Commutative Rings, Determinant, Minimizing, Mathematical Packages
5117 @section Commutative Rings
5118
5119 Scheme provides a consistent and capable set of numeric functions.
5120 Inexacts implement a field; integers a commutative ring (and Euclidean
5121 domain). This package allows one to use basic Scheme numeric functions
5122 with symbols and non-numeric elements of commutative rings.
5123
5124 @code{(require 'commutative-ring)}
5125 @ftindex commutative-ring
5126 @cindex ring, commutative
5127
5128 The @dfn{commutative-ring} package makes the procedures @code{+},
5129 @code{-}, @code{*}, @code{/}, and @code{^} @dfn{careful} in the sense
5130 @cindex careful
5131 that any non-numeric arguments they do not reduce appear in the
5132 expression output. In order to see what working with this package is
5133 like, self-set all the single letter identifiers (to their corresponding
5134 symbols).
5135
5136 @example
5137 (define a 'a)
5138 @dots{}
5139 (define z 'z)
5140 @end example
5141
5142 Or just @code{(require 'self-set)}. Now try some sample expressions:
5143
5144 @example
5145 (+ (+ a b) (- a b)) @result{} (* a 2)
5146 (* (+ a b) (+ a b)) @result{} (^ (+ a b) 2)
5147 (* (+ a b) (- a b)) @result{} (* (+ a b) (- a b))
5148 (* (- a b) (- a b)) @result{} (^ (- a b) 2)
5149 (* (- a b) (+ a b)) @result{} (* (+ a b) (- a b))
5150 (/ (+ a b) (+ c d)) @result{} (/ (+ a b) (+ c d))
5151 (^ (+ a b) 3) @result{} (^ (+ a b) 3)
5152 (^ (+ a 2) 3) @result{} (^ (+ 2 a) 3)
5153 @end example
5154
5155 Associative rules have been applied and repeated addition and
5156 multiplication converted to multiplication and exponentiation.
5157
5158 We can enable distributive rules, thus expanding to sum of products
5159 form:
5160 @example
5161 (set! *ruleset* (combined-rulesets distribute* distribute/))
5162
5163 (* (+ a b) (+ a b)) @result{} (+ (* 2 a b) (^ a 2) (^ b 2))
5164 (* (+ a b) (- a b)) @result{} (- (^ a 2) (^ b 2))
5165 (* (- a b) (- a b)) @result{} (- (+ (^ a 2) (^ b 2)) (* 2 a b))
5166 (* (- a b) (+ a b)) @result{} (- (^ a 2) (^ b 2))
5167 (/ (+ a b) (+ c d)) @result{} (+ (/ a (+ c d)) (/ b (+ c d)))
5168 (/ (+ a b) (- c d)) @result{} (+ (/ a (- c d)) (/ b (- c d)))
5169 (/ (- a b) (- c d)) @result{} (- (/ a (- c d)) (/ b (- c d)))
5170 (/ (- a b) (+ c d)) @result{} (- (/ a (+ c d)) (/ b (+ c d)))
5171 (^ (+ a b) 3) @result{} (+ (* 3 a (^ b 2)) (* 3 b (^ a 2)) (^ a 3) (^ b 3))
5172 (^ (+ a 2) 3) @result{} (+ 8 (* a 12) (* (^ a 2) 6) (^ a 3))
5173 @end example
5174
5175 Use of this package is not restricted to simple arithmetic expressions:
5176
5177 @example
5178 (require 'determinant)
5179
5180 (determinant '((a b c) (d e f) (g h i))) @result{}
5181 (- (+ (* a e i) (* b f g) (* c d h)) (* a f h) (* b d i) (* c e g))
5182 @end example
5183
5184 Currently, only @code{+}, @code{-}, @code{*}, @code{/}, and @code{^}
5185 support non-numeric elements. Expressions with @code{-} are converted
5186 to equivalent expressions without @code{-}, so behavior for @code{-} is
5187 not defined separately. @code{/} expressions are handled similarly.
5188
5189 This list might be extended to include @code{quotient}, @code{modulo},
5190 @code{remainder}, @code{lcm}, and @code{gcd}; but these work only for
5191 the more restrictive Euclidean (Unique Factorization) Domain.
5192 @cindex Unique Factorization
5193 @cindex Euclidean Domain
5194
5195 @heading Rules and Rulesets
5196
5197 The @dfn{commutative-ring} package allows control of ring properties
5198 through the use of @dfn{rulesets}.
5199
5200 @defvar *ruleset*
5201 Contains the set of rules currently in effect. Rules defined by
5202 @code{cring:define-rule} are stored within the value of *ruleset* at the
5203 time @code{cring:define-rule} is called. If @var{*ruleset*} is
5204 @code{#f}, then no rules apply.
5205 @end defvar
5206
5207 @defun make-ruleset rule1 @dots{}
5208 @defunx make-ruleset name rule1 @dots{}
5209 Returns a new ruleset containing the rules formed by applying
5210 @code{cring:define-rule} to each 4-element list argument @var{rule}. If
5211 the first argument to @code{make-ruleset} is a symbol, then the database
5212 table created for the new ruleset will be named @var{name}. Calling
5213 @code{make-ruleset} with no rule arguments creates an empty ruleset.
5214 @end defun
5215
5216 @defun combined-rulesets ruleset1 @dots{}
5217 @defunx combined-rulesets name ruleset1 @dots{}
5218 Returns a new ruleset containing the rules contained in each ruleset
5219 argument @var{ruleset}. If the first argument to
5220 @code{combined-ruleset} is a symbol, then the database table created for
5221 the new ruleset will be named @var{name}. Calling
5222 @code{combined-ruleset} with no ruleset arguments creates an empty
5223 ruleset.
5224 @end defun
5225
5226 Two rulesets are defined by this package.
5227
5228 @defvr Constant distribute*
5229 Contain the ruleset to distribute multiplication over addition and
5230 subtraction.
5231 @defvrx Constant distribute/
5232 Contain the ruleset to distribute division over addition and
5233 subtraction.
5234
5235 Take care when using both @var{distribute*} and @var{distribute/}
5236 simultaneously. It is possible to put @code{/} into an infinite loop.
5237 @end defvr
5238
5239 You can specify how sum and product expressions containing non-numeric
5240 elements simplify by specifying the rules for @code{+} or @code{*} for
5241 cases where expressions involving objects reduce to numbers or to
5242 expressions involving different non-numeric elements.
5243
5244 @defun cring:define-rule op sub-op1 sub-op2 reduction
5245 Defines a rule for the case when the operation represented by symbol
5246 @var{op} is applied to lists whose @code{car}s are @var{sub-op1} and
5247 @var{sub-op2}, respectively. The argument @var{reduction} is a
5248 procedure accepting 2 arguments which will be lists whose @code{car}s
5249 are @var{sub-op1} and @var{sub-op2}.
5250
5251 @defunx cring:define-rule op sub-op1 'identity reduction
5252 Defines a rule for the case when the operation represented by symbol
5253 @var{op} is applied to a list whose @code{car} is @var{sub-op1}, and
5254 some other argument. @var{Reduction} will be called with the list whose
5255 @code{car} is @var{sub-op1} and some other argument.
5256
5257 If @var{reduction} returns @code{#f}, the reduction has failed and other
5258 reductions will be tried. If @var{reduction} returns a non-false value,
5259 that value will replace the two arguments in arithmetic (@code{+},
5260 @code{-}, and @code{*}) calculations involving non-numeric elements.
5261
5262 The operations @code{+} and @code{*} are assumed commutative; hence both
5263 orders of arguments to @var{reduction} will be tried if necessary.
5264
5265 The following rule is the definition for distributing @code{*} over
5266 @code{+}.
5267
5268 @example
5269 (cring:define-rule
5270 '* '+ 'identity
5271 (lambda (exp1 exp2)
5272 (apply + (map (lambda (trm) (* trm exp2)) (cdr exp1))))))
5273 @end example
5274 @end defun
5275
5276 @heading How to Create a Commutative Ring
5277
5278 The first step in creating your commutative ring is to write procedures
5279 to create elements of the ring. A non-numeric element of the ring must
5280 be represented as a list whose first element is a symbol or string.
5281 This first element identifies the type of the object. A convenient and
5282 clear convention is to make the type-identifying element be the same
5283 symbol whose top-level value is the procedure to create it.
5284
5285 @example
5286 (define (n . list1)
5287 (cond ((and (= 2 (length list1))
5288 (eq? (car list1) (cadr list1)))
5289 0)
5290 ((not (term< (first list1) (last1 list1)))
5291 (apply n (reverse list1)))
5292 (else (cons 'n list1))))
5293
5294 (define (s x y) (n x y))
5295
5296 (define (m . list1)
5297 (cond ((neq? (first list1) (term_min list1))
5298 (apply m (cyclicrotate list1)))
5299 ((term< (last1 list1) (cadr list1))
5300 (apply m (reverse (cyclicrotate list1))))
5301 (else (cons 'm list1))))
5302 @end example
5303
5304 Define a procedure to multiply 2 non-numeric elements of the ring.
5305 Other multiplicatons are handled automatically. Objects for which rules
5306 have @emph{not} been defined are not changed.
5307
5308 @example
5309 (define (n*n ni nj)
5310 (let ((list1 (cdr ni)) (list2 (cdr nj)))
5311 (cond ((null? (intersection list1 list2)) #f)
5312 ((and (eq? (last1 list1) (first list2))
5313 (neq? (first list1) (last1 list2)))
5314 (apply n (splice list1 list2)))
5315 ((and (eq? (first list1) (first list2))
5316 (neq? (last1 list1) (last1 list2)))
5317 (apply n (splice (reverse list1) list2)))
5318 ((and (eq? (last1 list1) (last1 list2))
5319 (neq? (first list1) (first list2)))
5320 (apply n (splice list1 (reverse list2))))
5321 ((and (eq? (last1 list1) (first list2))
5322 (eq? (first list1) (last1 list2)))
5323 (apply m (cyclicsplice list1 list2)))
5324 ((and (eq? (first list1) (first list2))
5325 (eq? (last1 list1) (last1 list2)))
5326 (apply m (cyclicsplice (reverse list1) list2)))
5327 (else #f))))
5328 @end example
5329
5330 Test the procedures to see if they work.
5331
5332 @example
5333 ;;; where cyclicrotate(list) is cyclic rotation of the list one step
5334 ;;; by putting the first element at the end
5335 (define (cyclicrotate list1)
5336 (append (rest list1) (list (first list1))))
5337 ;;; and where term_min(list) is the element of the list which is
5338 ;;; first in the term ordering.
5339 (define (term_min list1)
5340 (car (sort list1 term<)))
5341 (define (term< sym1 sym2)
5342 (string<? (symbol->string sym1) (symbol->string sym2)))
5343 (define first car)
5344 (define rest cdr)
5345 (define (last1 list1) (car (last-pair list1)))
5346 (define (neq? obj1 obj2) (not (eq? obj1 obj2)))
5347 ;;; where splice is the concatenation of list1 and list2 except that their
5348 ;;; common element is not repeated.
5349 (define (splice list1 list2)
5350 (cond ((eq? (last1 list1) (first list2))
5351 (append list1 (cdr list2)))
5352 (else (error 'splice list1 list2))))
5353 ;;; where cyclicsplice is the result of leaving off the last element of
5354 ;;; splice(list1,list2).
5355 (define (cyclicsplice list1 list2)
5356 (cond ((and (eq? (last1 list1) (first list2))
5357 (eq? (first list1) (last1 list2)))
5358 (butlast (splice list1 list2) 1))
5359 (else (error 'cyclicsplice list1 list2))))
5360
5361 (N*N (S a b) (S a b)) @result{} (m a b)
5362 @end example
5363
5364 Then register the rule for multiplying type N objects by type N objects.
5365
5366 @example
5367 (cring:define-rule '* 'N 'N N*N))
5368 @end example
5369
5370 Now we are ready to compute!
5371
5372 @example
5373 (define (t)
5374 (define detM
5375 (+ (* (S g b)
5376 (+ (* (S f d)
5377 (- (* (S a f) (S d g)) (* (S a g) (S d f))))
5378 (* (S f f)
5379 (- (* (S a g) (S d d)) (* (S a d) (S d g))))
5380 (* (S f g)
5381 (- (* (S a d) (S d f)) (* (S a f) (S d d))))))
5382 (* (S g d)
5383 (+ (* (S f b)
5384 (- (* (S a g) (S d f)) (* (S a f) (S d g))))
5385 (* (S f f)
5386 (- (* (S a b) (S d g)) (* (S a g) (S d b))))
5387 (* (S f g)
5388 (- (* (S a f) (S d b)) (* (S a b) (S d f))))))
5389 (* (S g f)
5390 (+ (* (S f b)
5391 (- (* (S a d) (S d g)) (* (S a g) (S d d))))
5392 (* (S f d)
5393 (- (* (S a g) (S d b)) (* (S a b) (S d g))))
5394 (* (S f g)
5395 (- (* (S a b) (S d d)) (* (S a d) (S d b))))))
5396 (* (S g g)
5397 (+ (* (S f b)
5398 (- (* (S a f) (S d d)) (* (S a d) (S d f))))
5399 (* (S f d)
5400 (- (* (S a b) (S d f)) (* (S a f) (S d b))))
5401 (* (S f f)
5402 (- (* (S a d) (S d b)) (* (S a b) (S d d))))))))
5403 (* (S b e) (S c a) (S e c)
5404 detM
5405 ))
5406 (pretty-print (t))
5407 @print{}
5408 (- (+ (m a c e b d f g)
5409 (m a c e b d g f)
5410 (m a c e b f d g)
5411 (m a c e b f g d)
5412 (m a c e b g d f)
5413 (m a c e b g f d))
5414 (* 2 (m a b e c) (m d f g))
5415 (* (m a c e b d) (m f g))
5416 (* (m a c e b f) (m d g))
5417 (* (m a c e b g) (m d f)))
5418 @end example
5419
5420 @node Determinant, , Commutative Rings, Mathematical Packages
5421 @section Determinant
5422
5423 @defun determinant square-matrix
5424 Returns the determinant of @var{square-matrix}.
5425
5426 @example
5427 (require 'determinant)
5428 (determinant '((1 2) (3 4))) @result{} -2
5429 (determinant '((1 2 3) (4 5 6) (7 8 9))) @result{} 0
5430 (determinant '((1 2 3 4) (5 6 7 8) (9 10 11 12))) @result{} 0
5431 @end example
5432 @end defun
5433
5434
5435 @node Database Packages, Other Packages, Mathematical Packages, Top
5436 @chapter Database Packages
5437
5438 @menu
5439 * Base Table::
5440 * Relational Database:: 'relational-database
5441 * Weight-Balanced Trees:: 'wt-tree
5442 @end menu
5443
5444 @node Base Table, Relational Database, Database Packages, Database Packages
5445 @section Base Table
5446
5447 A base table implementation using Scheme association lists is available
5448 as the value of the identifier @code{alist-table} after doing:
5449
5450 @code{(require 'alist-table)}
5451 @ftindex alist-table
5452
5453
5454 Association list base tables are suitable for small databases and
5455 support all Scheme types when temporary and readable/writeable Scheme
5456 types when saved. I hope support for other base table implementations
5457 will be added in the future.
5458
5459 This rest of this section documents the interface for a base table
5460 implementation from which the @ref{Relational Database} package
5461 constructs a Relational system. It will be of interest primarily to
5462 those wishing to port or write new base-table implementations.
5463
5464 All of these functions are accessed through a single procedure by
5465 calling that procedure with the symbol name of the operation. A
5466 procedure will be returned if that operation is supported and @code{#f}
5467 otherwise. For example:
5468
5469 @example
5470 @group
5471 (require 'alist-table)
5472 @ftindex alist-table
5473 (define open-base (alist-table 'make-base))
5474 make-base @result{} *a procedure*
5475 (define foo (alist-table 'foo))
5476 foo @result{} #f
5477 @end group
5478 @end example
5479
5480 @defun make-base filename key-dimension column-types
5481 Returns a new, open, low-level database (collection of tables)
5482 associated with @var{filename}. This returned database has an empty
5483 table associated with @var{catalog-id}. The positive integer
5484 @var{key-dimension} is the number of keys composed to make a
5485 @var{primary-key} for the catalog table. The list of symbols
5486 @var{column-types} describes the types of each column for that table.
5487 If the database cannot be created as specified, @code{#f} is returned.
5488
5489 Calling the @code{close-base} method on this database and possibly other
5490 operations will cause @var{filename} to be written to. If
5491 @var{filename} is @code{#f} a temporary, non-disk based database will be
5492 created if such can be supported by the base table implelentation.
5493 @end defun
5494
5495 @defun open-base filename mutable
5496 Returns an open low-level database associated with @var{filename}. If
5497 @var{mutable?} is @code{#t}, this database will have methods capable of
5498 effecting change to the database. If @var{mutable?} is @code{#f}, only
5499 methods for inquiring the database will be available. If the database
5500 cannot be opened as specified @code{#f} is returned.
5501
5502 Calling the @code{close-base} (and possibly other) method on a
5503 @var{mutable?} database will cause @var{filename} to be written to.
5504 @end defun
5505
5506 @defun write-base lldb filename
5507 Causes the low-level database @var{lldb} to be written to
5508 @var{filename}. If the write is successful, also causes @var{lldb} to
5509 henceforth be associated with @var{filename}. Calling the
5510 @code{close-database} (and possibly other) method on @var{lldb} may
5511 cause @var{filename} to be written to. If @var{filename} is @code{#f}
5512 this database will be changed to a temporary, non-disk based database if
5513 such can be supported by the underlying base table implelentation. If
5514 the operations completed successfully, @code{#t} is returned.
5515 Otherwise, @code{#f} is returned.
5516 @end defun
5517
5518 @defun sync-base lldb
5519 Causes the file associated with the low-level database @var{lldb} to be
5520 updated to reflect its current state. If the associated filename is
5521 @code{#f}, no action is taken and @code{#f} is returned. If this
5522 operation completes successfully, @code{#t} is returned. Otherwise,
5523 @code{#f} is returned.
5524 @end defun
5525
5526 @defun close-base lldb
5527 Causes the low-level database @var{lldb} to be written to its associated
5528 file (if any). If the write is successful, subsequent operations to
5529 @var{lldb} will signal an error. If the operations complete
5530 successfully, @code{#t} is returned. Otherwise, @code{#f} is returned.
5531 @end defun
5532
5533 @defun make-table lldb key-dimension column-types
5534 Returns the @var{base-id} for a new base table, otherwise returns
5535 @code{#f}. The base table can then be opened using @code{(open-table
5536 @var{lldb} @var{base-id})}. The positive integer @var{key-dimension} is
5537 the number of keys composed to make a @var{primary-key} for this table.
5538 The list of symbols @var{column-types} describes the types of each
5539 column.
5540 @end defun
5541
5542 @defvr Constant catalog-id
5543 A constant @var{base-id} suitable for passing as a parameter to
5544 @code{open-table}. @var{catalog-id} will be used as the base table for
5545 the system catalog.
5546 @end defvr
5547
5548 @defun open-table lldb base-id key-dimension column-types
5549 Returns a @var{handle} for an existing base table in the low-level
5550 database @var{lldb} if that table exists and can be opened in the mode
5551 indicated by @var{mutable?}, otherwise returns @code{#f}.
5552
5553 As with @code{make-table}, the positive integer @var{key-dimension} is
5554 the number of keys composed to make a @var{primary-key} for this table.
5555 The list of symbols @var{column-types} describes the types of each
5556 column.
5557 @end defun
5558
5559 @defun kill-table lldb base-id key-dimension column-types
5560 Returns @code{#t} if the base table associated with @var{base-id} was
5561 removed from the low level database @var{lldb}, and @code{#f} otherwise.
5562 @end defun
5563
5564 @defun make-keyifier-1 type
5565 Returns a procedure which accepts a single argument which must be of
5566 type @var{type}. This returned procedure returns an object suitable for
5567 being a @var{key} argument in the functions whose descriptions follow.
5568
5569 Any 2 arguments of the supported type passed to the returned function
5570 which are not @code{equal?} must result in returned values which are not
5571 @code{equal?}.
5572 @end defun
5573
5574 @defun make-list-keyifier key-dimension types
5575 The list of symbols @var{types} must have at least @var{key-dimension}
5576 elements. Returns a procedure which accepts a list of length
5577 @var{key-dimension} and whose types must corresopond to the types named
5578 by @var{types}. This returned procedure combines the elements of its
5579 list argument into an object suitable for being a @var{key} argument in
5580 the functions whose descriptions follow.
5581
5582 Any 2 lists of supported types (which must at least include symbols and
5583 non-negative integers) passed to the returned function which are not
5584 @code{equal?} must result in returned values which are not
5585 @code{equal?}.
5586 @end defun
5587
5588 @defun make-key-extractor key-dimension types column-number
5589 Returns a procedure which accepts objects produced by application of the
5590 result of @code{(make-list-keyifier @var{key-dimension} @var{types})}.
5591 This procedure returns a @var{key} which is @code{equal?} to the
5592 @var{column-number}th element of the list which was passed to create
5593 @var{combined-key}. The list @var{types} must have at least
5594 @var{key-dimension} elements.
5595 @end defun
5596
5597 @defun make-key->list key-dimension types
5598 Returns a procedure which accepts objects produced by application of the
5599 result of @code{(make-list-keyifier @var{key-dimension} @var{types})}.
5600 This procedure returns a list of @var{key}s which are elementwise
5601 @code{equal?} to the list which was passed to create @var{combined-key}.
5602 @end defun
5603
5604 @noindent
5605 In the following functions, the @var{key} argument can always be assumed
5606 to be the value returned by a call to a @emph{keyify} routine.
5607
5608 @noindent
5609 @cindex match-keys
5610 @cindex match
5611 @cindex wild-card
5612 In contrast, a @var{match-keys} argument is a list of length equal to
5613 the number of primary keys. The @var{match-keys} restrict the actions
5614 of the table command to those records whose primary keys all satisfy the
5615 corresponding element of the @var{match-keys} list. The elements and
5616 their actions are:
5617
5618 @quotation
5619 @table @asis
5620 @item @code{#f}
5621 The false value matches any key in the corresponding position.
5622 @item an object of type procedure
5623 This procedure must take a single argument, the key in the corresponding
5624 position. Any key for which the procedure returns a non-false value is
5625 a match; Any key for which the procedure returns a @code{#f} is not.
5626 @item other values
5627 Any other value matches only those keys @code{equal?} to it.
5628 @end table
5629 @end quotation
5630
5631 @noindent
5632 The @var{key-dimension} and @var{column-types} arguments are needed to
5633 decode the combined-keys for matching with @var{match-keys}.
5634
5635 @defun for-each-key handle procedure key-dimension column-types match-keys
5636 Calls @var{procedure} once with each @var{key} in the table opened in
5637 @var{handle} which satisfy @var{match-keys} in an unspecified order.
5638 An unspecified value is returned.
5639 @end defun
5640
5641 @defun map-key handle procedure key-dimension column-types match-keys
5642 Returns a list of the values returned by calling @var{procedure} once
5643 with each @var{key} in the table opened in @var{handle} which satisfy
5644 @var{match-keys} in an unspecified order.
5645 @end defun
5646
5647 @defun ordered-for-each-key handle procedure key-dimension column-types match-keys
5648 Calls @var{procedure} once with each @var{key} in the table opened in
5649 @var{handle} which satisfy @var{match-keys} in the natural order for
5650 the types of the primary key fields of that table. An unspecified value
5651 is returned.
5652 @end defun
5653
5654 @defun delete* handle key-dimension column-types match-keys
5655 Removes all rows which satisfy @var{match-keys} from the table opened in
5656 @var{handle}. An unspecified value is returned.
5657 @end defun
5658
5659 @defun present? handle key
5660 Returns a non-@code{#f} value if there is a row associated with
5661 @var{key} in the table opened in @var{handle} and @code{#f} otherwise.
5662 @end defun
5663
5664 @defun delete handle key
5665 Removes the row associated with @var{key} from the table opened in
5666 @var{handle}. An unspecified value is returned.
5667 @end defun
5668
5669 @defun make-getter key-dimension types
5670 Returns a procedure which takes arguments @var{handle} and @var{key}.
5671 This procedure returns a list of the non-primary values of the relation
5672 (in the base table opened in @var{handle}) whose primary key is
5673 @var{key} if it exists, and @code{#f} otherwise.
5674 @end defun
5675
5676 @defun make-putter key-dimension types
5677 Returns a procedure which takes arguments @var{handle} and @var{key} and
5678 @var{value-list}. This procedure associates the primary key @var{key}
5679 with the values in @var{value-list} (in the base table opened in
5680 @var{handle}) and returns an unspecified value.
5681 @end defun
5682
5683 @defun supported-type? symbol
5684 Returns @code{#t} if @var{symbol} names a type allowed as a column value
5685 by the implementation, and @code{#f} otherwise. At a minimum, an
5686 implementation must support the types @code{integer}, @code{symbol},
5687 @code{string}, @code{boolean}, and @code{base-id}.
5688 @end defun
5689
5690 @defun supported-key-type? symbol
5691 Returns @code{#t} if @var{symbol} names a type allowed as a key value by
5692 the implementation, and @code{#f} otherwise. At a minimum, an
5693 implementation must support the types @code{integer}, and @code{symbol}.
5694 @end defun
5695
5696 @table @code
5697 @item integer
5698 Scheme exact integer.
5699 @item symbol
5700 Scheme symbol.
5701 @item boolean
5702 @code{#t} or @code{#f}.
5703 @item base-id
5704 Objects suitable for passing as the @var{base-id} parameter to
5705 @code{open-table}. The value of @var{catalog-id} must be an acceptable
5706 @code{base-id}.
5707 @end table
5708
5709 @node Relational Database, Weight-Balanced Trees, Base Table, Database Packages
5710 @section Relational Database
5711
5712 @code{(require 'relational-database)}
5713 @ftindex relational-database
5714
5715 This package implements a database system inspired by the Relational
5716 Model (@cite{E. F. Codd, A Relational Model of Data for Large Shared
5717 Data Banks}). An SLIB relational database implementation can be created
5718 from any @ref{Base Table} implementation.
5719
5720 @menu
5721 * Motivations:: Database Manifesto
5722 * Creating and Opening Relational Databases::
5723 * Relational Database Operations::
5724 * Table Operations::
5725 * Catalog Representation::
5726 * Unresolved Issues::
5727 * Database Utilities:: 'database-utilities
5728 * Database Reports::
5729 * Database Browser:: 'database-browse
5730 @end menu
5731
5732 @node Motivations, Creating and Opening Relational Databases, Relational Database, Relational Database
5733 @subsection Motivations
5734
5735 Most nontrivial programs contain databases: Makefiles, configure
5736 scripts, file backup, calendars, editors, source revision control, CAD
5737 systems, display managers, menu GUIs, games, parsers, debuggers,
5738 profilers, and even error reporting are all rife with databases. Coding
5739 databases is such a common activity in programming that many may not be
5740 aware of how often they do it.
5741
5742 A database often starts as a dispatch in a program. The author, perhaps
5743 because of the need to make the dispatch configurable, the need for
5744 correlating dispatch in other routines, or because of changes or growth,
5745 devises a data structure to contain the information, a routine for
5746 interpreting that data structure, and perhaps routines for augmenting
5747 and modifying the stored data. The dispatch must be converted into this
5748 form and tested.
5749
5750 The programmer may need to devise an interactive program for enabling
5751 easy examination and modification of the information contained in this
5752 database. Often, in an attempt to foster modularity and avoid delays in
5753 release, intermediate file formats for the database information are
5754 devised. It often turns out that users prefer modifying these
5755 intermediate files with a text editor to using the interactive program
5756 in order to do operations (such as global changes) not forseen by the
5757 program's author.
5758
5759 In order to address this need, the conscientious software engineer may
5760 even provide a scripting language to allow users to make repetitive
5761 database changes. Users will grumble that they need to read a large
5762 manual and learn yet another programming language (even if it
5763 @emph{almost} has language "xyz" syntax) in order to do simple
5764 configuration.
5765
5766 All of these facilities need to be designed, coded, debugged,
5767 documented, and supported; often causing what was very simple in concept
5768 to become a major developement project.
5769
5770 This view of databases just outlined is somewhat the reverse of the view
5771 of the originators of the @dfn{Relational Model} of database
5772 abstraction. The relational model was devised to unify and allow
5773 interoperation of large multi-user databases running on diverse
5774 platforms. A fairly general purpose "Comprehensive Language" for
5775 database manipulations is mandated (but not specified) as part of the
5776 relational model for databases.
5777
5778 One aspect of the Relational Model of some importance is that the
5779 "Comprehensive Language" must be expressible in some form which can be
5780 stored in the database. This frees the programmer from having to make
5781 programs data-driven in order to use a database.
5782
5783 This package includes as one of its basic supported types Scheme
5784 @dfn{expression}s. This type allows expressions as defined by the
5785 Scheme standards to be stored in the database. Using @code{slib:eval}
5786 retrieved expressions can be evaluated (in the top-level environment).
5787 Scheme's @code{lambda} facilitates closure of environments, modularity,
5788 etc. so that procedures (which could not be stored directly most
5789 databases) can still be effectively retrieved. Since @code{slib:eval}
5790 evaluates expressions in the top-level environment, built-in and user
5791 defined procedures can be easily accessed by name.
5792
5793 This package's purpose is to standardize (through a common interface)
5794 database creation and usage in Scheme programs. The relational model's
5795 provision for inclusion of language expressions as data as well as the
5796 description (in tables, of course) of all of its tables assures that
5797 relational databases are powerful enough to assume the roles currently
5798 played by thousands of ad-hoc routines and data formats.
5799
5800 @noindent
5801 Such standardization to a relational-like model brings many benefits:
5802
5803 @itemize @bullet
5804 @item
5805 Tables, fields, domains, and types can be dealt with by name in
5806 programs.
5807 @item
5808 The underlying database implementation can be changed (for
5809 performance or other reasons) by changing a single line of code.
5810 @item
5811 The formats of tables can be easily extended or changed without
5812 altering code.
5813 @item
5814 Consistency checks are specified as part of the table descriptions.
5815 Changes in checks need only occur in one place.
5816 @item
5817 All the configuration information which the developer wishes to group
5818 together is easily grouped, without needing to change programs aware of
5819 only some of these tables.
5820 @item
5821 Generalized report generators, interactive entry programs, and other
5822 database utilities can be part of a shared library. The burden of
5823 adding configurability to a program is greatly reduced.
5824 @item
5825 Scheme is the "comprehensive language" for these databases. Scripting
5826 for configuration no longer needs to be in a separate language with
5827 additional documentation.
5828 @item
5829 Scheme's latent types mesh well with the strict typing and logical
5830 requirements of the relational model.
5831 @item
5832 Portable formats allow easy interchange of data. The included table
5833 descriptions help prevent misinterpretation of format.
5834 @end itemize
5835
5836 @node Creating and Opening Relational Databases, Relational Database Operations, Motivations, Relational Database
5837 @subsection Creating and Opening Relational Databases
5838
5839 @defun make-relational-system base-table-implementation
5840
5841 Returns a procedure implementing a relational database using the
5842 @var{base-table-implementation}.
5843
5844 All of the operations of a base table implementation are accessed
5845 through a procedure defined by @code{require}ing that implementation.
5846 Similarly, all of the operations of the relational database
5847 implementation are accessed through the procedure returned by
5848 @code{make-relational-system}. For instance, a new relational database
5849 could be created from the procedure returned by
5850 @code{make-relational-system} by:
5851
5852 @example
5853 (require 'alist-table)
5854 @ftindex alist-table
5855 (define relational-alist-system
5856 (make-relational-system alist-table))
5857 (define create-alist-database
5858 (relational-alist-system 'create-database))
5859 (define my-database
5860 (create-alist-database "mydata.db"))
5861 @end example
5862 @end defun
5863
5864 @noindent
5865 What follows are the descriptions of the methods available from
5866 relational system returned by a call to @code{make-relational-system}.
5867
5868 @defun create-database filename
5869
5870 Returns an open, nearly empty relational database associated with
5871 @var{filename}. The only tables defined are the system catalog and
5872 domain table. Calling the @code{close-database} method on this database
5873 and possibly other operations will cause @var{filename} to be written
5874 to. If @var{filename} is @code{#f} a temporary, non-disk based database
5875 will be created if such can be supported by the underlying base table
5876 implelentation. If the database cannot be created as specified
5877 @code{#f} is returned. For the fields and layout of descriptor tables,
5878 @ref{Catalog Representation}
5879 @end defun
5880
5881 @defun open-database filename mutable?
5882
5883 Returns an open relational database associated with @var{filename}. If
5884 @var{mutable?} is @code{#t}, this database will have methods capable of
5885 effecting change to the database. If @var{mutable?} is @code{#f}, only
5886 methods for inquiring the database will be available. Calling the
5887 @code{close-database} (and possibly other) method on a @var{mutable?}
5888 database will cause @var{filename} to be written to. If the database
5889 cannot be opened as specified @code{#f} is returned.
5890 @end defun
5891
5892 @node Relational Database Operations, Table Operations, Creating and Opening Relational Databases, Relational Database
5893 @subsection Relational Database Operations
5894
5895 @noindent
5896 These are the descriptions of the methods available from an open
5897 relational database. A method is retrieved from a database by calling
5898 the database with the symbol name of the operation. For example:
5899
5900 @example
5901 (define my-database
5902 (create-alist-database "mydata.db"))
5903 (define telephone-table-desc
5904 ((my-database 'create-table) 'telephone-table-desc))
5905 @end example
5906
5907 @defun close-database
5908 Causes the relational database to be written to its associated file (if
5909 any). If the write is successful, subsequent operations to this
5910 database will signal an error. If the operations completed
5911 successfully, @code{#t} is returned. Otherwise, @code{#f} is returned.
5912 @end defun
5913
5914 @defun write-database filename
5915 Causes the relational database to be written to @var{filename}. If the
5916 write is successful, also causes the database to henceforth be
5917 associated with @var{filename}. Calling the @code{close-database} (and
5918 possibly other) method on this database will cause @var{filename} to be
5919 written to. If @var{filename} is @code{#f} this database will be
5920 changed to a temporary, non-disk based database if such can be supported
5921 by the underlying base table implelentation. If the operations
5922 completed successfully, @code{#t} is returned. Otherwise, @code{#f} is
5923 returned.
5924 @end defun
5925
5926 @defun sync-database
5927 Causes any pending updates to the database file to be written out. If
5928 the operations completed successfully, @code{#t} is returned.
5929 Otherwise, @code{#f} is returned.
5930 @end defun
5931
5932 @defun table-exists? table-name
5933 Returns @code{#t} if @var{table-name} exists in the system catalog,
5934 otherwise returns @code{#f}.
5935 @end defun
5936
5937 @defun open-table table-name mutable?
5938 Returns a @dfn{methods} procedure for an existing relational table in
5939 this database if it exists and can be opened in the mode indicated by
5940 @var{mutable?}, otherwise returns @code{#f}.
5941 @end defun
5942
5943 @noindent
5944 These methods will be present only in databases which are
5945 @var{mutable?}.
5946
5947 @defun delete-table table-name
5948 Removes and returns the @var{table-name} row from the system catalog if
5949 the table or view associated with @var{table-name} gets removed from the
5950 database, and @code{#f} otherwise.
5951 @end defun
5952
5953 @defun create-table table-desc-name
5954 Returns a methods procedure for a new (open) relational table for
5955 describing the columns of a new base table in this database, otherwise
5956 returns @code{#f}. For the fields and layout of descriptor tables,
5957 @xref{Catalog Representation}.
5958
5959 @defunx create-table table-name table-desc-name
5960 Returns a methods procedure for a new (open) relational table with
5961 columns as described by @var{table-desc-name}, otherwise returns
5962 @code{#f}.
5963 @end defun
5964
5965 @defun create-view ??
5966 @defunx project-table ??
5967 @defunx restrict-table ??
5968 @defunx cart-prod-tables ??
5969 Not yet implemented.
5970 @end defun
5971
5972 @node Table Operations, Catalog Representation, Relational Database Operations, Relational Database
5973 @subsection Table Operations
5974
5975 @noindent
5976 These are the descriptions of the methods available from an open
5977 relational table. A method is retrieved from a table by calling
5978 the table with the symbol name of the operation. For example:
5979
5980 @example
5981 @group
5982 (define telephone-table-desc
5983 ((my-database 'create-table) 'telephone-table-desc))
5984 (require 'common-list-functions)
5985 (define ndrp (telephone-table-desc 'row:insert))
5986 (ndrp '(1 #t name #f string))
5987 (ndrp '(2 #f telephone
5988 (lambda (d)
5989 (and (string? d) (> (string-length d) 2)
5990 (every
5991 (lambda (c)
5992 (memv c '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
5993 #\+ #\( #\ #\) #\-)))
5994 (string->list d))))
5995 string))
5996 @end group
5997 @end example
5998
5999 @noindent
6000 Some operations described below require primary key arguments. Primary
6001 keys arguments are denoted @var{key1} @var{key2} @dots{}. It is an
6002 error to call an operation for a table which takes primary key arguments
6003 with the wrong number of primary keys for that table.
6004
6005 @noindent
6006 The term @dfn{row} used below refers to a Scheme list of values (one for
6007 each column) in the order specified in the descriptor (table) for this
6008 table. Missing values appear as @code{#f}. Primary keys must not
6009 be missing.
6010
6011 @defun get column-name
6012 Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
6013 returns the value for the @var{column-name} column of the row associated
6014 with primary keys @var{key1}, @var{key2} @dots{} if that row exists in
6015 the table, or @code{#f} otherwise.
6016
6017 @example
6018 ((plat 'get 'processor) 'djgpp) @result{} i386
6019 ((plat 'get 'processor) 'be-os) @result{} #f
6020 @end example
6021
6022 @defunx get* column-name
6023 Returns a procedure of optional arguments @var{match-key1} @dots{} which
6024 returns a list of the values for the specified column for all rows in
6025 this table. The optional @var{match-key1} @dots{} arguments restrict
6026 actions to a subset of the table. See the match-key description below
6027 for details.
6028
6029 @example
6030 ((plat 'get* 'processor)) @result{}
6031 (i386 8086 i386 8086 i386 i386 8086 m68000
6032 m68000 m68000 m68000 m68000 powerpc)
6033
6034 ((plat 'get* 'processor) #f) @result{}
6035 (i386 8086 i386 8086 i386 i386 8086 m68000
6036 m68000 m68000 m68000 m68000 powerpc)
6037
6038 (define (a-key? key)
6039 (char=? #\a (string-ref (symbol->string key) 0)))
6040
6041 ((plat 'get* 'processor) a-key?) @result{}
6042 (m68000 m68000 m68000 m68000 m68000 powerpc)
6043
6044 ((plat 'get* 'name) a-key?) @result{}
6045 (atari-st-turbo-c atari-st-gcc amiga-sas/c-5.10
6046 amiga-aztec amiga-dice-c aix)
6047 @end example
6048 @end defun
6049
6050 @defun row:retrieve
6051 Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
6052 returns the row associated with primary keys @var{key1}, @var{key2}
6053 @dots{} if it exists, or @code{#f} otherwise.
6054
6055 @example
6056 ((plat 'row:retrieve) 'linux) @result{} (linux i386 linux gcc)
6057 ((plat 'row:retrieve) 'multics) @result{} #f
6058 @end example
6059
6060 @defunx row:retrieve*
6061 Returns a procedure of optional arguments @var{match-key1} @dots{} which
6062 returns a list of all rows in this table. The optional @var{match-key1}
6063 @dots{} arguments restrict actions to a subset of the table. See the
6064 match-key description below for details.
6065 @end defun
6066
6067 @example
6068 ((plat 'row:retrieve*) a-key?) @result{}
6069 ((atari-st-turbo-c m68000 atari turbo-c)
6070 (atari-st-gcc m68000 atari gcc)
6071 (amiga-sas/c-5.10 m68000 amiga sas/c)
6072 (amiga-aztec m68000 amiga aztec)
6073 (amiga-dice-c m68000 amiga dice-c)
6074 (aix powerpc aix -))
6075 @end example
6076
6077 @defun row:remove
6078 Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
6079 removes and returns the row associated with primary keys @var{key1},
6080 @var{key2} @dots{} if it exists, or @code{#f} otherwise.
6081
6082 @defunx row:remove*
6083 Returns a procedure of optional arguments @var{match-key1} @dots{} which
6084 removes and returns a list of all rows in this table. The optional
6085 @var{match-key1} @dots{} arguments restrict actions to a subset of the
6086 table. See the match-key description below for details.
6087 @end defun
6088
6089 @defun row:delete
6090 Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
6091 deletes the row associated with primary keys @var{key1}, @var{key2}
6092 @dots{} if it exists. The value returned is unspecified.
6093
6094 @defunx row:delete*
6095 Returns a procedure of optional arguments @var{match-key1} @dots{} which
6096 Deletes all rows from this table. The optional @var{match-key1} @dots{}
6097 arguments restrict deletions to a subset of the table. See the
6098 match-key description below for details. The value returned is
6099 unspecified. The descriptor table and catalog entry for this table are
6100 not affected.
6101 @end defun
6102
6103 @defun row:update
6104 Returns a procedure of one argument, @var{row}, which adds the row,
6105 @var{row}, to this table. If a row for the primary key(s) specified by
6106 @var{row} already exists in this table, it will be overwritten. The
6107 value returned is unspecified.
6108
6109 @defunx row:update*
6110 Returns a procedure of one argument, @var{rows}, which adds each row in
6111 the list of rows, @var{rows}, to this table. If a row for the primary
6112 key specified by an element of @var{rows} already exists in this table,
6113 it will be overwritten. The value returned is unspecified.
6114 @end defun
6115
6116 @defun row:insert
6117 Adds the row @var{row} to this table. If a row for the primary key(s)
6118 specified by @var{row} already exists in this table an error is
6119 signaled. The value returned is unspecified.
6120
6121 @defunx row:insert*
6122 Returns a procedure of one argument, @var{rows}, which adds each row in
6123 the list of rows, @var{rows}, to this table. If a row for the primary
6124 key specified by an element of @var{rows} already exists in this table,
6125 an error is signaled. The value returned is unspecified.
6126 @end defun
6127
6128 @defun for-each-row
6129 Returns a procedure of arguments @var{proc} @var{match-key1} @dots{}
6130 which calls @var{proc} with each @var{row} in this table in the
6131 (implementation-dependent) natural ordering for rows. The optional
6132 @var{match-key1} @dots{} arguments restrict actions to a subset of the
6133 table. See the match-key description below for details.
6134
6135 @emph{Real} relational programmers would use some least-upper-bound join
6136 for every row to get them in order; But we don't have joins yet.
6137 @end defun
6138
6139 @noindent
6140 @cindex match-keys
6141 The (optional) @var{match-key1} @dots{} arguments are used to restrict
6142 actions of a whole-table operation to a subset of that table. Those
6143 procedures (returned by methods) which accept match-key arguments will
6144 accept any number of match-key arguments between zero and the number of
6145 primary keys in the table. Any unspecified @var{match-key} arguments
6146 default to @code{#f}.
6147
6148 @noindent
6149 The @var{match-key1} @dots{} restrict the actions of the table command
6150 to those records whose primary keys each satisfy the corresponding
6151 @var{match-key} argument. The arguments and their actions are:
6152
6153 @quotation
6154 @table @asis
6155 @item @code{#f}
6156 The false value matches any key in the corresponding position.
6157 @item an object of type procedure
6158 This procedure must take a single argument, the key in the corresponding
6159 position. Any key for which the procedure returns a non-false value is
6160 a match; Any key for which the procedure returns a @code{#f} is not.
6161 @item other values
6162 Any other value matches only those keys @code{equal?} to it.
6163 @end table
6164 @end quotation
6165
6166 @defun close-table
6167 Subsequent operations to this table will signal an error.
6168 @end defun
6169
6170 @defvr Constant column-names
6171 @defvrx Constant column-foreigns
6172 @defvrx Constant column-domains
6173 @defvrx Constant column-types
6174 Return a list of the column names, foreign-key table names, domain
6175 names, or type names respectively for this table. These 4 methods are
6176 different from the others in that the list is returned, rather than a
6177 procedure to obtain the list.
6178
6179 @defvrx Constant primary-limit
6180 Returns the number of primary keys fields in the relations in this
6181 table.
6182 @end defvr
6183
6184 @node Catalog Representation, Unresolved Issues, Table Operations, Relational Database
6185 @subsection Catalog Representation
6186
6187 @noindent
6188 Each database (in an implementation) has a @dfn{system catalog} which
6189 describes all the user accessible tables in that database (including
6190 itself).
6191
6192 @noindent
6193 The system catalog base table has the following fields. @code{PRI}
6194 indicates a primary key for that table.
6195
6196 @example
6197 @group
6198 PRI table-name
6199 column-limit the highest column number
6200 coltab-name descriptor table name
6201 bastab-id data base table identifier
6202 user-integrity-rule
6203 view-procedure A scheme thunk which, when called,
6204 produces a handle for the view. coltab
6205 and bastab are specified if and only if
6206 view-procedure is not.
6207 @end group
6208 @end example
6209
6210 @noindent
6211 Descriptors for base tables (not views) are tables (pointed to by
6212 system catalog). Descriptor (base) tables have the fields:
6213
6214 @example
6215 @group
6216 PRI column-number sequential integers from 1
6217 primary-key? boolean TRUE for primary key components
6218 column-name
6219 column-integrity-rule
6220 domain-name
6221 @end group
6222 @end example
6223
6224 @noindent
6225 A @dfn{primary key} is any column marked as @code{primary-key?} in the
6226 corresponding descriptor table. All the @code{primary-key?} columns
6227 must have lower column numbers than any non-@code{primary-key?} columns.
6228 Every table must have at least one primary key. Primary keys must be
6229 sufficient to distinguish all rows from each other in the table. All of
6230 the system defined tables have a single primary key.
6231
6232 @noindent
6233 This package currently supports tables having from 1 to 4 primary keys
6234 if there are non-primary columns, and any (natural) number if @emph{all}
6235 columns are primary keys. If you need more than 4 primary keys, I would
6236 like to hear what you are doing!
6237
6238 @noindent
6239 A @dfn{domain} is a category describing the allowable values to occur in
6240 a column. It is described by a (base) table with the fields:
6241
6242 @example
6243 @group
6244 PRI domain-name
6245 foreign-table
6246 domain-integrity-rule
6247 type-id
6248 type-param
6249 @end group
6250 @end example
6251
6252 @noindent
6253 The @dfn{type-id} field value is a symbol. This symbol may be used by
6254 the underlying base table implementation in storing that field.
6255
6256 @noindent
6257 If the @code{foreign-table} field is non-@code{#f} then that field names
6258 a table from the catalog. The values for that domain must match a
6259 primary key of the table referenced by the @var{type-param} (or
6260 @code{#f}, if allowed). This package currently does not support
6261 composite foreign-keys.
6262
6263 @noindent
6264 The types for which support is planned are:
6265 @example
6266 @group
6267 atom
6268 symbol
6269 string [<length>]
6270 number [<base>]
6271 money <currency>
6272 date-time
6273 boolean
6274
6275 foreign-key <table-name>
6276 expression
6277 virtual <expression>
6278 @end group
6279 @end example
6280
6281 @node Unresolved Issues, Database Utilities, Catalog Representation, Relational Database
6282 @subsection Unresolved Issues
6283
6284 Although @file{rdms.scm} is not large, I found it very difficult to
6285 write (six rewrites). I am not aware of any other examples of a
6286 generalized relational system (although there is little new in CS). I
6287 left out several aspects of the Relational model in order to simplify
6288 the job. The major features lacking (which might be addressed portably)
6289 are views, transaction boundaries, and protection.
6290
6291 Protection needs a model for specifying priveledges. Given how
6292 operations are accessed from handles it should not be difficult to
6293 restrict table accesses to those allowed for that user.
6294
6295 The system catalog has a field called @code{view-procedure}. This
6296 should allow a purely functional implementation of views. This will
6297 work but is unsatisfying for views resulting from a @dfn{select}ion
6298 (subset of rows); for whole table operations it will not be possible to
6299 reduce the number of keys scanned over when the selection is specified
6300 only by an opaque procedure.
6301
6302 Transaction boundaries present the most intriguing area. Transaction
6303 boundaries are actually a feature of the "Comprehensive Language" of the
6304 Relational database and not of the database. Scheme would seem to
6305 provide the opportunity for an extremely clean semantics for transaction
6306 boundaries since the builtin procedures with side effects are small in
6307 number and easily identified.
6308
6309 These side-effect builtin procedures might all be portably redefined to
6310 versions which properly handled transactions. Compiled library routines
6311 would need to be recompiled as well. Many system extensions
6312 (delete-file, system, etc.) would also need to be redefined.
6313
6314 @noindent
6315 There are 2 scope issues that must be resolved for multiprocess
6316 transaction boundaries:
6317
6318 @table @asis
6319 @item Process scope
6320 The actions captured by a transaction should be only for the process
6321 which invoked the start of transaction. Although standard Scheme does
6322 not provide process primitives as such, @code{dynamic-wind} would
6323 provide a workable hook into process switching for many implementations.
6324 @item Shared utilities with state
6325 Some shared utilities have state which should @emph{not} be part of a
6326 transaction. An example would be calling a pseudo-random number
6327 generator. If the success of a transaction depended on the
6328 pseudo-random number and failed, the state of the generator would be set
6329 back. Subsequent calls would keep returning the same number and keep
6330 failing.
6331
6332 Pseudo-random number generators are not reentrant; thus they would
6333 require locks in order to operate properly in a multiprocess
6334 environment. Are all examples of utilities whose state should not be
6335 part of transactions also non-reentrant? If so, perhaps suspending
6336 transaction capture for the duration of locks would solve this problem.
6337 @end table
6338
6339 @node Database Utilities, Database Reports, Unresolved Issues, Relational Database
6340 @subsection Database Utilities
6341
6342 @code{(require 'database-utilities)}
6343 @ftindex database-utilities
6344
6345 @noindent
6346 This enhancement wraps a utility layer on @code{relational-database}
6347 which provides:
6348 @itemize @bullet
6349 @item
6350 Automatic loading of the appropriate base-table package when opening a
6351 database.
6352 @item
6353 Automatic execution of initialization commands stored in database.
6354 @item
6355 Transparent execution of database commands stored in @code{*commands*}
6356 table in database.
6357 @end itemize
6358
6359 @noindent
6360 Also included are utilities which provide:
6361 @itemize @bullet
6362 @item
6363 Data definition from Scheme lists and
6364 @item
6365 Report generation
6366 @end itemize
6367 @noindent
6368 for any SLIB relational database.
6369
6370 @defun create-database filename base-table-type
6371 Returns an open, nearly empty enhanced (with @code{*commands*} table)
6372 relational database (with base-table type @var{base-table-type})
6373 associated with @var{filename}.
6374 @end defun
6375
6376 @defun open-database filename
6377 @defunx open-database filename base-table-type
6378 Returns an open enchanced relational database associated with
6379 @var{filename}. The database will be opened with base-table type
6380 @var{base-table-type}) if supplied. If @var{base-table-type} is not
6381 supplied, @code{open-database} will attempt to deduce the correct
6382 base-table-type. If the database can not be opened or if it lacks the
6383 @code{*commands*} table, @code{#f} is returned.
6384
6385 @defunx open-database! filename
6386 @defunx open-database! filename base-table-type
6387 Returns @emph{mutable} open enchanced relational database @dots{}
6388 @end defun
6389
6390 @noindent
6391 The table @code{*commands*} in an @dfn{enhanced} relational-database has
6392 the fields (with domains):
6393 @example
6394 @group
6395 PRI name symbol
6396 parameters parameter-list
6397 procedure expression
6398 documentation string
6399 @end group
6400 @end example
6401
6402 The @code{parameters} field is a foreign key (domain
6403 @code{parameter-list}) of the @code{*catalog-data*} table and should
6404 have the value of a table described by @code{*parameter-columns*}. This
6405 @code{parameter-list} table describes the arguments suitable for passing
6406 to the associated command. The intent of this table is to be of a form
6407 such that different user-interfaces (for instance, pull-down menus or
6408 plain-text queries) can operate from the same table. A
6409 @code{parameter-list} table has the following fields:
6410 @example
6411 @group
6412 PRI index uint
6413 name symbol
6414 arity parameter-arity
6415 domain domain
6416 defaulter expression
6417 expander expression
6418 documentation string
6419 @end group
6420 @end example
6421
6422 The @code{arity} field can take the values:
6423
6424 @table @code
6425 @item single
6426 Requires a single parameter of the specified domain.
6427 @item optional
6428 A single parameter of the specified domain or zero parameters is
6429 acceptable.
6430 @item boolean
6431 A single boolean parameter or zero parameters (in which case @code{#f}
6432 is substituted) is acceptable.
6433 @item nary
6434 Any number of parameters of the specified domain are acceptable. The
6435 argument passed to the command function is always a list of the
6436 parameters.
6437 @item nary1
6438 One or more of parameters of the specified domain are acceptable. The
6439 argument passed to the command function is always a list of the
6440 parameters.
6441 @end table
6442
6443 The @code{domain} field specifies the domain which a parameter or
6444 parameters in the @code{index}th field must satisfy.
6445
6446 The @code{defaulter} field is an expression whose value is either
6447 @code{#f} or a procedure of one argument (the parameter-list) which
6448 returns a @emph{list} of the default value or values as appropriate.
6449 Note that since the @code{defaulter} procedure is called every time a
6450 default parameter is needed for this column, @dfn{sticky} defaults can
6451 be implemented using shared state with the domain-integrity-rule.
6452
6453 @subsubheading Invoking Commands
6454
6455 When an enhanced relational-database is called with a symbol which
6456 matches a @var{name} in the @code{*commands*} table, the associated
6457 procedure expression is evaluated and applied to the enhanced
6458 relational-database. A procedure should then be returned which the user
6459 can invoke on (optional) arguments.
6460
6461 The command @code{*initialize*} is special. If present in the
6462 @code{*commands*} table, @code{open-database} or @code{open-database!}
6463 will return the value of the @code{*initialize*} command. Notice that
6464 arbitrary code can be run when the @code{*initialize*} procedure is
6465 automatically applied to the enhanced relational-database.
6466
6467 Note also that if you wish to shadow or hide from the user
6468 relational-database methods described in @ref{Relational Database
6469 Operations}, this can be done by a dispatch in the closure returned by
6470 the @code{*initialize*} expression rather than by entries in the
6471 @code{*commands*} table if it is desired that the underlying methods
6472 remain accessible to code in the @code{*commands*} table.
6473
6474 @defun make-command-server rdb table-name
6475 Returns a procedure of 2 arguments, a (symbol) command and a call-back
6476 procedure. When this returned procedure is called, it looks up
6477 @var{command} in table @var{table-name} and calls the call-back
6478 procedure with arguments:
6479 @table @var
6480 @item command
6481 The @var{command}
6482 @item command-value
6483 The result of evaluating the expression in the @var{procedure} field of
6484 @var{table-name} and calling it with @var{rdb}.
6485 @item parameter-name
6486 A list of the @dfn{official} name of each parameter. Corresponds to the
6487 @code{name} field of the @var{command}'s parameter-table.
6488 @item positions
6489 A list of the positive integer index of each parameter. Corresponds to
6490 the @code{index} field of the @var{command}'s parameter-table.
6491 @item arities
6492 A list of the arities of each parameter. Corresponds to the
6493 @code{arity} field of the @var{command}'s parameter-table. For a
6494 description of @code{arity} see table above.
6495 @item types
6496 A list of the type name of each parameter. Correspnds to the
6497 @code{type-id} field of the contents of the @code{domain} of the
6498 @var{command}'s parameter-table.
6499 @item defaulters
6500 A list of the defaulters for each parameter. Corresponds to
6501 the @code{defaulters} field of the @var{command}'s parameter-table.
6502 @item domain-integrity-rules
6503 A list of procedures (one for each parameter) which tests whether a
6504 value for a parameter is acceptable for that parameter. The procedure
6505 should be called with each datum in the list for @code{nary} arity
6506 parameters.
6507 @item aliases
6508 A list of lists of @code{(@r{alias} @r{parameter-name})}. There can be
6509 more than one alias per @var{parameter-name}.
6510 @end table
6511 @end defun
6512
6513 For information about parameters, @xref{Parameter lists}. Here is an
6514 example of setting up a command with arguments and parsing those
6515 arguments from a @code{getopt} style argument list (@pxref{Getopt}).
6516
6517 @example
6518 (require 'database-utilities)
6519 @ftindex database-utilities
6520 (require 'fluid-let)
6521 @ftindex fluid-let
6522 (require 'parameters)
6523 @ftindex parameters
6524 (require 'getopt)
6525 @ftindex getopt
6526
6527 (define my-rdb (create-database #f 'alist-table))
6528
6529 (define-tables my-rdb
6530 '(foo-params
6531 *parameter-columns*
6532 *parameter-columns*
6533 ((1 single-string single string
6534 (lambda (pl) '("str")) #f "single string")
6535 (2 nary-symbols nary symbol
6536 (lambda (pl) '()) #f "zero or more symbols")
6537 (3 nary1-symbols nary1 symbol
6538 (lambda (pl) '(symb)) #f "one or more symbols")
6539 (4 optional-number optional uint
6540 (lambda (pl) '()) #f "zero or one number")
6541 (5 flag boolean boolean
6542 (lambda (pl) '(#f)) #f "a boolean flag")))
6543 '(foo-pnames
6544 ((name string))
6545 ((parameter-index uint))
6546 (("s" 1)
6547 ("single-string" 1)
6548 ("n" 2)
6549 ("nary-symbols" 2)
6550 ("N" 3)
6551 ("nary1-symbols" 3)
6552 ("o" 4)
6553 ("optional-number" 4)
6554 ("f" 5)
6555 ("flag" 5)))
6556 '(my-commands
6557 ((name symbol))
6558 ((parameters parameter-list)
6559 (parameter-names parameter-name-translation)
6560 (procedure expression)
6561 (documentation string))
6562 ((foo
6563 foo-params
6564 foo-pnames
6565 (lambda (rdb) (lambda args (print args)))
6566 "test command arguments"))))
6567
6568 (define (dbutil:serve-command-line rdb command-table
6569 command argc argv)
6570 (set! argv (if (vector? argv) (vector->list argv) argv))
6571 ((make-command-server rdb command-table)
6572 command
6573 (lambda (comname comval options positions
6574 arities types defaulters dirs aliases)
6575 (apply comval (getopt->arglist
6576 argc argv options positions
6577 arities types defaulters dirs aliases)))))
6578
6579 (define (cmd . opts)
6580 (fluid-let ((*optind* 1))
6581 (printf "%-34s @result{} "
6582 (call-with-output-string
6583 (lambda (pt) (write (cons 'cmd opts) pt))))
6584 (set! opts (cons "cmd" opts))
6585 (force-output)
6586 (dbutil:serve-command-line
6587 my-rdb 'my-commands 'foo (length opts) opts)))
6588
6589 (cmd) @result{} ("str" () (symb) () #f)
6590 (cmd "-f") @result{} ("str" () (symb) () #t)
6591 (cmd "--flag") @result{} ("str" () (symb) () #t)
6592 (cmd "-o177") @result{} ("str" () (symb) (177) #f)
6593 (cmd "-o" "177") @result{} ("str" () (symb) (177) #f)
6594 (cmd "--optional" "621") @result{} ("str" () (symb) (621) #f)
6595 (cmd "--optional=621") @result{} ("str" () (symb) (621) #f)
6596 (cmd "-s" "speciality") @result{} ("speciality" () (symb) () #f)
6597 (cmd "-sspeciality") @result{} ("speciality" () (symb) () #f)
6598 (cmd "--single" "serendipity") @result{} ("serendipity" () (symb) () #f)
6599 (cmd "--single=serendipity") @result{} ("serendipity" () (symb) () #f)
6600 (cmd "-n" "gravity" "piety") @result{} ("str" () (piety gravity) () #f)
6601 (cmd "-ngravity" "piety") @result{} ("str" () (piety gravity) () #f)
6602 (cmd "--nary" "chastity") @result{} ("str" () (chastity) () #f)
6603 (cmd "--nary=chastity" "") @result{} ("str" () ( chastity) () #f)
6604 (cmd "-N" "calamity") @result{} ("str" () (calamity) () #f)
6605 (cmd "-Ncalamity") @result{} ("str" () (calamity) () #f)
6606 (cmd "--nary1" "surety") @result{} ("str" () (surety) () #f)
6607 (cmd "--nary1=surety") @result{} ("str" () (surety) () #f)
6608 (cmd "-N" "levity" "fealty") @result{} ("str" () (fealty levity) () #f)
6609 (cmd "-Nlevity" "fealty") @result{} ("str" () (fealty levity) () #f)
6610 (cmd "--nary1" "surety" "brevity") @result{} ("str" () (brevity surety) () #f)
6611 (cmd "--nary1=surety" "brevity") @result{} ("str" () (brevity surety) () #f)
6612 (cmd "-?")
6613 @print{}
6614 Usage: cmd [OPTION ARGUMENT ...] ...
6615
6616 -f, --flag
6617 -o, --optional[=]<number>
6618 -n, --nary[=]<symbols> ...
6619 -N, --nary1[=]<symbols> ...
6620 -s, --single[=]<string>
6621
6622 ERROR: getopt->parameter-list "unrecognized option" "-?"
6623 @end example
6624
6625 Some commands are defined in all extended relational-databases. The are
6626 called just like @ref{Relational Database Operations}.
6627
6628 @defun add-domain domain-row
6629 Adds @var{domain-row} to the @dfn{domains} table if there is no row in
6630 the domains table associated with key @code{(car @var{domain-row})} and
6631 returns @code{#t}. Otherwise returns @code{#f}.
6632
6633 For the fields and layout of the domain table, @xref{Catalog
6634 Representation}. Currently, these fields are
6635 @itemize @bullet
6636 @item
6637 domain-name
6638 @item
6639 foreign-table
6640 @item
6641 domain-integrity-rule
6642 @item
6643 type-id
6644 @item
6645 type-param
6646 @end itemize
6647
6648 The following example adds 3 domains to the @samp{build} database.
6649 @samp{Optstring} is either a string or @code{#f}. @code{filename} is a
6650 string and @code{build-whats} is a symbol.
6651
6652 @example
6653 (for-each (build 'add-domain)
6654 '((optstring #f
6655 (lambda (x) (or (not x) (string? x)))
6656 string
6657 #f)
6658 (filename #f #f string #f)
6659 (build-whats #f #f symbol #f)))
6660 @end example
6661 @end defun
6662
6663 @defun delete-domain domain-name
6664 Removes and returns the @var{domain-name} row from the @dfn{domains}
6665 table.
6666 @end defun
6667
6668 @defun domain-checker domain
6669 Returns a procedure to check an argument for conformance to domain
6670 @var{domain}.
6671 @end defun
6672
6673 @subsubheading Defining Tables
6674
6675 @deffn Procedure define-tables rdb spec-0 @dots{}
6676 Adds tables as specified in @var{spec-0} @dots{} to the open
6677 relational-database @var{rdb}. Each @var{spec} has the form:
6678
6679 @lisp
6680 (@r{<name>} @r{<descriptor-name>} @r{<descriptor-name>} @r{<rows>})
6681 @end lisp
6682 or
6683 @lisp
6684 (@r{<name>} @r{<primary-key-fields>} @r{<other-fields>} @r{<rows>})
6685 @end lisp
6686
6687 where @r{<name>} is the table name, @r{<descriptor-name>} is the symbol
6688 name of a descriptor table, @r{<primary-key-fields>} and
6689 @r{<other-fields>} describe the primary keys and other fields
6690 respectively, and @r{<rows>} is a list of data rows to be added to the
6691 table.
6692
6693 @r{<primary-key-fields>} and @r{<other-fields>} are lists of field
6694 descriptors of the form:
6695
6696 @lisp
6697 (@r{<column-name>} @r{<domain>})
6698 @end lisp
6699 or
6700 @lisp
6701 (@r{<column-name>} @r{<domain>} @r{<column-integrity-rule>})
6702 @end lisp
6703
6704 where @r{<column-name>} is the column name, @r{<domain>} is the domain
6705 of the column, and @r{<column-integrity-rule>} is an expression whose
6706 value is a procedure of one argument (which returns @code{#f} to signal
6707 an error).
6708
6709 If @r{<domain>} is not a defined domain name and it matches the name of
6710 this table or an already defined (in one of @var{spec-0} @dots{}) single
6711 key field table, a foriegn-key domain will be created for it.
6712 @end deffn
6713
6714
6715 @noindent
6716 The following example shows a new database with the name of
6717 @file{foo.db} being created with tables describing processor families
6718 and processor/os/compiler combinations.
6719
6720 @noindent
6721 The database command @code{define-tables} is defined to call
6722 @code{define-tables} with its arguments. The database is also
6723 configured to print @samp{Welcome} when the database is opened. The
6724 database is then closed and reopened.
6725
6726 @example
6727 (require 'database-utilities)
6728 @ftindex database-utilities
6729 (define my-rdb (create-database "foo.db" 'alist-table))
6730
6731 (define-tables my-rdb
6732 '(*commands*
6733 ((name symbol))
6734 ((parameters parameter-list)
6735 (procedure expression)
6736 (documentation string))
6737 ((define-tables
6738 no-parameters
6739 no-parameter-names
6740 (lambda (rdb) (lambda specs (apply define-tables rdb specs)))
6741 "Create or Augment tables from list of specs")
6742 (*initialize*
6743 no-parameters
6744 no-parameter-names
6745 (lambda (rdb) (display "Welcome") (newline) rdb)
6746 "Print Welcome"))))
6747
6748 ((my-rdb 'define-tables)
6749 '(processor-family
6750 ((family atom))
6751 ((also-ran processor-family))
6752 ((m68000 #f)
6753 (m68030 m68000)
6754 (i386 8086)
6755 (8086 #f)
6756 (powerpc #f)))
6757
6758 '(platform
6759 ((name symbol))
6760 ((processor processor-family)
6761 (os symbol)
6762 (compiler symbol))
6763 ((aix powerpc aix -)
6764 (amiga-dice-c m68000 amiga dice-c)
6765 (amiga-aztec m68000 amiga aztec)
6766 (amiga-sas/c-5.10 m68000 amiga sas/c)
6767 (atari-st-gcc m68000 atari gcc)
6768 (atari-st-turbo-c m68000 atari turbo-c)
6769 (borland-c-3.1 8086 ms-dos borland-c)
6770 (djgpp i386 ms-dos gcc)
6771 (linux i386 linux gcc)
6772 (microsoft-c 8086 ms-dos microsoft-c)
6773 (os/2-emx i386 os/2 gcc)
6774 (turbo-c-2 8086 ms-dos turbo-c)
6775 (watcom-9.0 i386 ms-dos watcom))))
6776
6777 ((my-rdb 'close-database))
6778
6779 (set! my-rdb (open-database "foo.db" 'alist-table))
6780 @print{}
6781 Welcome
6782 @end example
6783
6784 @subsubheading Listing Tables
6785
6786 @deffn Procedure list-table-definition rdb table-name
6787 If symbol @var{table-name} exists in the open relational-database
6788 @var{rdb}, then returns a list of the table-name, its primary key names
6789 and domains, its other key names and domains, and the table's records
6790 (as lists). Otherwise, returns #f.
6791
6792 The list returned by @code{list-table-definition}, when passed as an
6793 argument to @code{define-tables}, will recreate the table.
6794 @end deffn
6795
6796
6797 @node Database Reports, Database Browser, Database Utilities, Relational Database
6798 @subsection Database Reports
6799
6800 @noindent
6801 Code for generating database reports is in @file{report.scm}. After
6802 writing it using @code{format}, I discovered that Common-Lisp
6803 @code{format} is not useable for this application because there is no
6804 mechanismm for truncating fields. @file{report.scm} needs to be
6805 rewritten using @code{printf}.
6806
6807 @deffn Procedure create-report rdb destination report-name table
6808 @deffnx Procedure create-report rdb destination report-name
6809 The symbol @var{report-name} must be primary key in the table named
6810 @code{*reports*} in the relational database @var{rdb}.
6811 @var{destination} is a port, string, or symbol. If @var{destination} is
6812 a:
6813
6814 @table @asis
6815 @item port
6816 The table is created as ascii text and written to that port.
6817 @item string
6818 The table is created as ascii text and written to the file named by
6819 @var{destination}.
6820 @item symbol
6821 @var{destination} is the primary key for a row in the table named *printers*.
6822 @end table
6823
6824 The report is prepared as follows:
6825
6826 @itemize @bullet
6827 @item
6828 @code{Format} (@pxref{Format}) is called with the @code{header} field
6829 and the (list of) @code{column-names} of the table.
6830 @item
6831 @code{Format} is called with the @code{reporter} field and (on
6832 successive calls) each record in the natural order for the table. A
6833 count is kept of the number of newlines output by format. When the
6834 number of newlines to be output exceeds the number of lines per page,
6835 the set of lines will be broken if there are more than
6836 @code{minimum-break} left on this page and the number of lines for this
6837 row is larger or equal to twice @code{minimum-break}.
6838 @item
6839 @code{Format} is called with the @code{footer} field and the (list of)
6840 @code{column-names} of the table. The footer field should not output a
6841 newline.
6842 @item
6843 A new page is output.
6844 @item
6845 This entire process repeats until all the rows are output.
6846 @end itemize
6847 @end deffn
6848
6849 Each row in the table *reports* has the fields:
6850
6851 @table @asis
6852 @item name
6853 The report name.
6854 @item default-table
6855 The table to report on if none is specified.
6856 @item header, footer
6857 A @code{format} string. At the beginning and end of each page
6858 respectively, @code{format} is called with this string and the (list of)
6859 column-names of this table.
6860 @item reporter
6861 A @code{format} string. For each row in the table, @code{format} is
6862 called with this string and the row.
6863 @item minimum-break
6864 The minimum number of lines into which the report lines for a row can be
6865 broken. Use @code{0} if a row's lines should not be broken over page
6866 boundaries.
6867 @end table
6868
6869 Each row in the table *printers* has the fields:
6870
6871 @table @asis
6872 @item name
6873 The printer name.
6874 @item print-procedure
6875 The procedure to call to actually print.
6876 @end table
6877
6878
6879
6880 @node Database Browser, , Database Reports, Relational Database
6881 @subsection Database Browser
6882
6883 (require 'database-browse)
6884
6885 @deffn Procedure browse database
6886
6887 Prints the names of all the tables in @var{database} and sets browse's
6888 default to @var{database}.
6889
6890 @deffnx Procedure browse
6891
6892 Prints the names of all the tables in the default database.
6893
6894 @deffnx Procedure browse table-name
6895
6896 For each record of the table named by the symbol @var{table-name},
6897 prints a line composed of all the field values.
6898
6899 @deffnx Procedure browse pathname
6900
6901 Opens the database named by the string @var{pathname}, prints the names
6902 of all its tables, and sets browse's default to the database.
6903
6904 @deffnx Procedure browse database table-name
6905
6906 Sets browse's default to @var{database} and prints the records of the
6907 table named by the symbol @var{table-name}.
6908
6909 @deffnx Procedure browse pathname table-name
6910
6911 Opens the database named by the string @var{pathname} and sets browse's
6912 default to it; @code{browse} prints the records of the table named by
6913 the symbol @var{table-name}.
6914
6915 @end deffn
6916
6917 @node Weight-Balanced Trees, , Relational Database, Database Packages
6918 @section Weight-Balanced Trees
6919
6920 @code{(require 'wt-tree)}
6921 @ftindex wt-tree
6922
6923 @cindex trees, balanced binary
6924 @cindex balanced binary trees
6925 @cindex binary trees
6926 @cindex weight-balanced binary trees
6927 Balanced binary trees are a useful data structure for maintaining large
6928 sets of ordered objects or sets of associations whose keys are ordered.
6929 MIT Scheme has an comprehensive implementation of weight-balanced binary
6930 trees which has several advantages over the other data structures for
6931 large aggregates:
6932
6933 @itemize @bullet
6934 @item
6935 In addition to the usual element-level operations like insertion,
6936 deletion and lookup, there is a full complement of collection-level
6937 operations, like set intersection, set union and subset test, all of
6938 which are implemented with good orders of growth in time and space.
6939 This makes weight balanced trees ideal for rapid prototyping of
6940 functionally derived specifications.
6941
6942 @item
6943 An element in a tree may be indexed by its position under the ordering
6944 of the keys, and the ordinal position of an element may be determined,
6945 both with reasonable efficiency.
6946
6947 @item
6948 Operations to find and remove minimum element make weight balanced trees
6949 simple to use for priority queues.
6950
6951 @item
6952 The implementation is @emph{functional} rather than @emph{imperative}.
6953 This means that operations like `inserting' an association in a tree do
6954 not destroy the old tree, in much the same way that @code{(+ 1 x)}
6955 modifies neither the constant 1 nor the value bound to @code{x}. The
6956 trees are referentially transparent thus the programmer need not worry
6957 about copying the trees. Referential transparency allows space
6958 efficiency to be achieved by sharing subtrees.
6959
6960 @end itemize
6961
6962 These features make weight-balanced trees suitable for a wide range of
6963 applications, especially those that
6964 require large numbers of sets or discrete maps. Applications that have
6965 a few global databases and/or concentrate on element-level operations like
6966 insertion and lookup are probably better off using hash-tables or
6967 red-black trees.
6968
6969 The @emph{size} of a tree is the number of associations that it
6970 contains. Weight balanced binary trees are balanced to keep the sizes
6971 of the subtrees of each node within a constant factor of each other.
6972 This ensures logarithmic times for single-path operations (like lookup
6973 and insertion). A weight balanced tree takes space that is proportional
6974 to the number of associations in the tree. For the current
6975 implementation, the constant of proportionality is six words per
6976 association.
6977
6978 @cindex binary trees, as sets
6979 @cindex binary trees, as discrete maps
6980 @cindex sets, using binary trees
6981 @cindex discrete maps, using binary trees
6982 Weight balanced trees can be used as an implementation for either
6983 discrete sets or discrete maps (associations). Sets are implemented by
6984 ignoring the datum that is associated with the key. Under this scheme
6985 if an associations exists in the tree this indicates that the key of the
6986 association is a member of the set. Typically a value such as
6987 @code{()}, @code{#t} or @code{#f} is associated with the key.
6988
6989 Many operations can be viewed as computing a result that, depending on
6990 whether the tree arguments are thought of as sets or maps, is known by
6991 two different names. An example is @code{wt-tree/member?}, which, when
6992 regarding the tree argument as a set, computes the set membership
6993 operation, but, when regarding the tree as a discrete map,
6994 @code{wt-tree/member?} is the predicate testing if the map is defined at
6995 an element in its domain. Most names in this package have been chosen
6996 based on interpreting the trees as sets, hence the name
6997 @code{wt-tree/member?} rather than @code{wt-tree/defined-at?}.
6998
6999
7000 @cindex run-time-loadable option
7001 @cindex option, run-time-loadable
7002 The weight balanced tree implementation is a run-time-loadable option.
7003 To use weight balanced trees, execute
7004
7005 @example
7006 (load-option 'wt-tree)
7007 @end example
7008 @findex load-option
7009
7010 @noindent
7011 once before calling any of the procedures defined here.
7012
7013
7014 @menu
7015 * Construction of Weight-Balanced Trees::
7016 * Basic Operations on Weight-Balanced Trees::
7017 * Advanced Operations on Weight-Balanced Trees::
7018 * Indexing Operations on Weight-Balanced Trees::
7019 @end menu
7020
7021 @node Construction of Weight-Balanced Trees, Basic Operations on Weight-Balanced Trees, Weight-Balanced Trees, Weight-Balanced Trees
7022 @subsection Construction of Weight-Balanced Trees
7023
7024 Binary trees require there to be a total order on the keys used to
7025 arrange the elements in the tree. Weight balanced trees are organized
7026 by @emph{types}, where the type is an object encapsulating the ordering
7027 relation. Creating a tree is a two-stage process. First a tree type
7028 must be created from the predicate which gives the ordering. The tree
7029 type is then used for making trees, either empty or singleton trees or
7030 trees from other aggregate structures like association lists. Once
7031 created, a tree `knows' its type and the type is used to test
7032 compatibility between trees in operations taking two trees. Usually a
7033 small number of tree types are created at the beginning of a program and
7034 used many times throughout the program's execution.
7035
7036 @deffn {procedure+} make-wt-tree-type key<?
7037 This procedure creates and returns a new tree type based on the ordering
7038 predicate @var{key<?}.
7039 @var{Key<?} must be a total ordering, having the property that for all
7040 key values @code{a}, @code{b} and @code{c}:
7041
7042 @example
7043 (key<? a a) @result{} #f
7044 (and (key<? a b) (key<? b a)) @result{} #f
7045 (if (and (key<? a b) (key<? b c))
7046 (key<? a c)
7047 #t) @result{} #t
7048 @end example
7049
7050 @noindent
7051 Two key values are assumed to be equal if neither is less than the other
7052 by @var{key<?}.
7053
7054 Each call to @code{make-wt-tree-type} returns a distinct value, and
7055 trees are only compatible if their tree types are @code{eq?}. A
7056 consequence is that trees that are intended to be used in binary tree
7057 operations must all be created with a tree type originating from the
7058 same call to @code{make-wt-tree-type}.
7059 @end deffn
7060
7061 @defvr {variable+} number-wt-type
7062 A standard tree type for trees with numeric keys. @code{Number-wt-type}
7063 could have been defined by
7064
7065 @example
7066 (define number-wt-type (make-wt-tree-type <))
7067 @end example
7068 @end defvr
7069
7070 @defvr {variable+} string-wt-type
7071 A standard tree type for trees with string keys. @code{String-wt-type}
7072 could have been defined by
7073
7074 @example
7075 (define string-wt-type (make-wt-tree-type string<?))
7076 @end example
7077 @end defvr
7078
7079
7080
7081 @deffn {procedure+} make-wt-tree wt-tree-type
7082 This procedure creates and returns a newly allocated weight balanced
7083 tree. The tree is empty, i.e. it contains no associations.
7084 @var{Wt-tree-type} is a weight balanced tree type obtained by calling
7085 @code{make-wt-tree-type}; the returned tree has this type.
7086 @end deffn
7087
7088 @deffn {procedure+} singleton-wt-tree wt-tree-type key datum
7089 This procedure creates and returns a newly allocated weight balanced
7090 tree. The tree contains a single association, that of @var{datum} with
7091 @var{key}. @var{Wt-tree-type} is a weight balanced tree type obtained
7092 by calling @code{make-wt-tree-type}; the returned tree has this type.
7093 @end deffn
7094
7095 @deffn {procedure+} alist->wt-tree tree-type alist
7096 Returns a newly allocated weight-balanced tree that contains the same
7097 associations as @var{alist}. This procedure is equivalent to:
7098
7099 @example
7100 (lambda (type alist)
7101 (let ((tree (make-wt-tree type)))
7102 (for-each (lambda (association)
7103 (wt-tree/add! tree
7104 (car association)
7105 (cdr association)))
7106 alist)
7107 tree))
7108 @end example
7109 @end deffn
7110
7111
7112
7113 @node Basic Operations on Weight-Balanced Trees, Advanced Operations on Weight-Balanced Trees, Construction of Weight-Balanced Trees, Weight-Balanced Trees
7114 @subsection Basic Operations on Weight-Balanced Trees
7115
7116 This section describes the basic tree operations on weight balanced
7117 trees. These operations are the usual tree operations for insertion,
7118 deletion and lookup, some predicates and a procedure for determining the
7119 number of associations in a tree.
7120
7121 @deffn {procedure+} wt-tree? object
7122 Returns @code{#t} if @var{object} is a weight-balanced tree, otherwise
7123 returns @code{#f}.
7124 @end deffn
7125
7126 @deffn {procedure+} wt-tree/empty? wt-tree
7127 Returns @code{#t} if @var{wt-tree} contains no associations, otherwise
7128 returns @code{#f}.
7129 @end deffn
7130
7131 @deffn {procedure+} wt-tree/size wt-tree
7132 Returns the number of associations in @var{wt-tree}, an exact
7133 non-negative integer. This operation takes constant time.
7134 @end deffn
7135
7136
7137 @deffn {procedure+} wt-tree/add wt-tree key datum
7138 Returns a new tree containing all the associations in @var{wt-tree} and
7139 the association of @var{datum} with @var{key}. If @var{wt-tree} already
7140 had an association for @var{key}, the new association overrides the old.
7141 The average and worst-case times required by this operation are
7142 proportional to the logarithm of the number of associations in
7143 @var{wt-tree}.
7144 @end deffn
7145
7146 @deffn {procedure+} wt-tree/add! wt-tree key datum
7147 Associates @var{datum} with @var{key} in @var{wt-tree} and returns an
7148 unspecified value. If @var{wt-tree} already has an association for
7149 @var{key}, that association is replaced. The average and worst-case
7150 times required by this operation are proportional to the logarithm of
7151 the number of associations in @var{wt-tree}.
7152 @end deffn
7153
7154 @deffn {procedure+} wt-tree/member? key wt-tree
7155 Returns @code{#t} if @var{wt-tree} contains an association for
7156 @var{key}, otherwise returns @code{#f}. The average and worst-case
7157 times required by this operation are proportional to the logarithm of
7158 the number of associations in @var{wt-tree}.
7159 @end deffn
7160
7161 @deffn {procedure+} wt-tree/lookup wt-tree key default
7162 Returns the datum associated with @var{key} in @var{wt-tree}. If
7163 @var{wt-tree} doesn't contain an association for @var{key},
7164 @var{default} is returned. The average and worst-case times required by
7165 this operation are proportional to the logarithm of the number of
7166 associations in @var{wt-tree}.
7167 @end deffn
7168
7169 @deffn {procedure+} wt-tree/delete wt-tree key
7170 Returns a new tree containing all the associations in @var{wt-tree},
7171 except that if @var{wt-tree} contains an association for @var{key}, it
7172 is removed from the result. The average and worst-case times required
7173 by this operation are proportional to the logarithm of the number of
7174 associations in @var{wt-tree}.
7175 @end deffn
7176
7177 @deffn {procedure+} wt-tree/delete! wt-tree key
7178 If @var{wt-tree} contains an association for @var{key} the association
7179 is removed. Returns an unspecified value. The average and worst-case
7180 times required by this operation are proportional to the logarithm of
7181 the number of associations in @var{wt-tree}.
7182 @end deffn
7183
7184
7185 @node Advanced Operations on Weight-Balanced Trees, Indexing Operations on Weight-Balanced Trees, Basic Operations on Weight-Balanced Trees, Weight-Balanced Trees
7186 @subsection Advanced Operations on Weight-Balanced Trees
7187
7188 In the following the @emph{size} of a tree is the number of associations
7189 that the tree contains, and a @emph{smaller} tree contains fewer
7190 associations.
7191
7192 @deffn {procedure+} wt-tree/split< wt-tree bound
7193 Returns a new tree containing all and only the associations in
7194 @var{wt-tree} which have a key that is less than @var{bound} in the
7195 ordering relation of the tree type of @var{wt-tree}. The average and
7196 worst-case times required by this operation are proportional to the
7197 logarithm of the size of @var{wt-tree}.
7198 @end deffn
7199
7200 @deffn {procedure+} wt-tree/split> wt-tree bound
7201 Returns a new tree containing all and only the associations in
7202 @var{wt-tree} which have a key that is greater than @var{bound} in the
7203 ordering relation of the tree type of @var{wt-tree}. The average and
7204 worst-case times required by this operation are proportional to the
7205 logarithm of size of @var{wt-tree}.
7206 @end deffn
7207
7208 @deffn {procedure+} wt-tree/union wt-tree-1 wt-tree-2
7209 Returns a new tree containing all the associations from both trees.
7210 This operation is asymmetric: when both trees have an association for
7211 the same key, the returned tree associates the datum from @var{wt-tree-2}
7212 with the key. Thus if the trees are viewed as discrete maps then
7213 @code{wt-tree/union} computes the map override of @var{wt-tree-1} by
7214 @var{wt-tree-2}. If the trees are viewed as sets the result is the set
7215 union of the arguments.
7216 The worst-case time required by this operation
7217 is proportional to the sum of the sizes of both trees.
7218 If the minimum key of one tree is greater than the maximum key of
7219 the other tree then the time required is at worst proportional to
7220 the logarithm of the size of the larger tree.
7221 @end deffn
7222
7223 @deffn {procedure+} wt-tree/intersection wt-tree-1 wt-tree-2
7224 Returns a new tree containing all and only those associations from
7225 @var{wt-tree-1} which have keys appearing as the key of an association
7226 in @var{wt-tree-2}. Thus the associated data in the result are those
7227 from @var{wt-tree-1}. If the trees are being used as sets the result is
7228 the set intersection of the arguments. As a discrete map operation,
7229 @code{wt-tree/intersection} computes the domain restriction of
7230 @var{wt-tree-1} to (the domain of) @var{wt-tree-2}.
7231 The time required by this operation is never worse that proportional to
7232 the sum of the sizes of the trees.
7233 @end deffn
7234
7235 @deffn {procedure+} wt-tree/difference wt-tree-1 wt-tree-2
7236 Returns a new tree containing all and only those associations from
7237 @var{wt-tree-1} which have keys that @emph{do not} appear as the key of
7238 an association in @var{wt-tree-2}. If the trees are viewed as sets the
7239 result is the asymmetric set difference of the arguments. As a discrete
7240 map operation, it computes the domain restriction of @var{wt-tree-1} to
7241 the complement of (the domain of) @var{wt-tree-2}.
7242 The time required by this operation is never worse that proportional to
7243 the sum of the sizes of the trees.
7244 @end deffn
7245
7246
7247 @deffn {procedure+} wt-tree/subset? wt-tree-1 wt-tree-2
7248 Returns @code{#t} iff the key of each association in @var{wt-tree-1} is
7249 the key of some association in @var{wt-tree-2}, otherwise returns @code{#f}.
7250 Viewed as a set operation, @code{wt-tree/subset?} is the improper subset
7251 predicate.
7252 A proper subset predicate can be constructed:
7253
7254 @example
7255 (define (proper-subset? s1 s2)
7256 (and (wt-tree/subset? s1 s2)
7257 (< (wt-tree/size s1) (wt-tree/size s2))))
7258 @end example
7259
7260 As a discrete map operation, @code{wt-tree/subset?} is the subset
7261 test on the domain(s) of the map(s). In the worst-case the time
7262 required by this operation is proportional to the size of
7263 @var{wt-tree-1}.
7264 @end deffn
7265
7266
7267 @deffn {procedure+} wt-tree/set-equal? wt-tree-1 wt-tree-2
7268 Returns @code{#t} iff for every association in @var{wt-tree-1} there is
7269 an association in @var{wt-tree-2} that has the same key, and @emph{vice
7270 versa}.
7271
7272 Viewing the arguments as sets @code{wt-tree/set-equal?} is the set
7273 equality predicate. As a map operation it determines if two maps are
7274 defined on the same domain.
7275
7276 This procedure is equivalent to
7277
7278 @example
7279 (lambda (wt-tree-1 wt-tree-2)
7280 (and (wt-tree/subset? wt-tree-1 wt-tree-2
7281 (wt-tree/subset? wt-tree-2 wt-tree-1)))
7282 @end example
7283
7284 In the worst-case the time required by this operation is proportional to
7285 the size of the smaller tree.
7286 @end deffn
7287
7288
7289 @deffn {procedure+} wt-tree/fold combiner initial wt-tree
7290 This procedure reduces @var{wt-tree} by combining all the associations,
7291 using an reverse in-order traversal, so the associations are visited in
7292 reverse order. @var{Combiner} is a procedure of three arguments: a key,
7293 a datum and the accumulated result so far. Provided @var{combiner}
7294 takes time bounded by a constant, @code{wt-tree/fold} takes time
7295 proportional to the size of @var{wt-tree}.
7296
7297 A sorted association list can be derived simply:
7298
7299 @example
7300 (wt-tree/fold (lambda (key datum list)
7301 (cons (cons key datum) list))
7302 '()
7303 @var{wt-tree}))
7304 @end example
7305
7306 The data in the associations can be summed like this:
7307
7308 @example
7309 (wt-tree/fold (lambda (key datum sum) (+ sum datum))
7310 0
7311 @var{wt-tree})
7312 @end example
7313 @end deffn
7314
7315 @deffn {procedure+} wt-tree/for-each action wt-tree
7316 This procedure traverses the tree in-order, applying @var{action} to
7317 each association.
7318 The associations are processed in increasing order of their keys.
7319 @var{Action} is a procedure of two arguments which take the key and
7320 datum respectively of the association.
7321 Provided @var{action} takes time bounded by a constant,
7322 @code{wt-tree/for-each} takes time proportional to in the size of
7323 @var{wt-tree}.
7324 The example prints the tree:
7325
7326 @example
7327 (wt-tree/for-each (lambda (key value)
7328 (display (list key value)))
7329 @var{wt-tree}))
7330 @end example
7331 @end deffn
7332
7333
7334 @node Indexing Operations on Weight-Balanced Trees, , Advanced Operations on Weight-Balanced Trees, Weight-Balanced Trees
7335 @subsection Indexing Operations on Weight-Balanced Trees
7336
7337 Weight balanced trees support operations that view the tree as sorted
7338 sequence of associations. Elements of the sequence can be accessed by
7339 position, and the position of an element in the sequence can be
7340 determined, both in logarthmic time.
7341
7342 @deffn {procedure+} wt-tree/index wt-tree index
7343 @deffnx {procedure+} wt-tree/index-datum wt-tree index
7344 @deffnx {procedure+} wt-tree/index-pair wt-tree index
7345 Returns the 0-based @var{index}th association of @var{wt-tree} in the
7346 sorted sequence under the tree's ordering relation on the keys.
7347 @code{wt-tree/index} returns the @var{index}th key,
7348 @code{wt-tree/index-datum} returns the datum associated with the
7349 @var{index}th key and @code{wt-tree/index-pair} returns a new pair
7350 @code{(@var{key} . @var{datum})} which is the @code{cons} of the
7351 @var{index}th key and its datum. The average and worst-case times
7352 required by this operation are proportional to the logarithm of the
7353 number of associations in the tree.
7354
7355 These operations signal an error if the tree is empty, if
7356 @var{index}@code{<0}, or if @var{index} is greater than or equal to the
7357 number of associations in the tree.
7358
7359 Indexing can be used to find the median and maximum keys in the tree as
7360 follows:
7361
7362 @example
7363 median: (wt-tree/index @var{wt-tree}
7364 (quotient (wt-tree/size @var{wt-tree}) 2))
7365
7366 maximum: (wt-tree/index @var{wt-tree}
7367 (-1+ (wt-tree/size @var{wt-tree})))
7368 @end example
7369 @end deffn
7370
7371 @deffn {procedure+} wt-tree/rank wt-tree key
7372 Determines the 0-based position of @var{key} in the sorted sequence of
7373 the keys under the tree's ordering relation, or @code{#f} if the tree
7374 has no association with for @var{key}. This procedure returns either an
7375 exact non-negative integer or @code{#f}. The average and worst-case
7376 times required by this operation are proportional to the logarithm of
7377 the number of associations in the tree.
7378 @end deffn
7379
7380 @deffn {procedure+} wt-tree/min wt-tree
7381 @deffnx {procedure+} wt-tree/min-datum wt-tree
7382 @deffnx {procedure+} wt-tree/min-pair wt-tree
7383 Returns the association of @var{wt-tree} that has the least key under
7384 the tree's ordering relation. @code{wt-tree/min} returns the least key,
7385 @code{wt-tree/min-datum} returns the datum associated with the least key
7386 and @code{wt-tree/min-pair} returns a new pair @code{(key . datum)}
7387 which is the @code{cons} of the minimum key and its datum. The average
7388 and worst-case times required by this operation are proportional to the
7389 logarithm of the number of associations in the tree.
7390
7391 These operations signal an error if the tree is empty.
7392 They could be written
7393 @example
7394 (define (wt-tree/min tree) (wt-tree/index tree 0))
7395 (define (wt-tree/min-datum tree) (wt-tree/index-datum tree 0))
7396 (define (wt-tree/min-pair tree) (wt-tree/index-pair tree 0))
7397 @end example
7398 @end deffn
7399
7400 @deffn {procedure+} wt-tree/delete-min wt-tree
7401 Returns a new tree containing all of the associations in @var{wt-tree}
7402 except the association with the least key under the @var{wt-tree}'s
7403 ordering relation. An error is signalled if the tree is empty. The
7404 average and worst-case times required by this operation are proportional
7405 to the logarithm of the number of associations in the tree. This
7406 operation is equivalent to
7407
7408 @example
7409 (wt-tree/delete @var{wt-tree} (wt-tree/min @var{wt-tree}))
7410 @end example
7411 @end deffn
7412
7413
7414 @deffn {procedure+} wt-tree/delete-min! wt-tree
7415 Removes the association with the least key under the @var{wt-tree}'s
7416 ordering relation. An error is signalled if the tree is empty. The
7417 average and worst-case times required by this operation are proportional
7418 to the logarithm of the number of associations in the tree. This
7419 operation is equivalent to
7420
7421 @example
7422 (wt-tree/delete! @var{wt-tree} (wt-tree/min @var{wt-tree}))
7423 @end example
7424 @end deffn
7425
7426
7427 @node Other Packages, About SLIB, Database Packages, Top
7428 @chapter Other Packages
7429
7430 @menu
7431 * Data Structures:: Various data structures.
7432 * Procedures:: Miscellaneous utility procedures.
7433 * Standards Support:: Support for Scheme Standards.
7434 * Session Support:: REPL and Debugging.
7435 * Extra-SLIB Packages::
7436 @end menu
7437
7438
7439 @node Data Structures, Procedures, Other Packages, Other Packages
7440 @section Data Structures
7441
7442
7443
7444 @menu
7445 * Arrays:: 'array
7446 * Array Mapping:: 'array-for-each
7447 * Association Lists:: 'alist
7448 * Byte:: 'byte
7449 * Portable Image Files:: 'pnm
7450 * Collections:: 'collect
7451 * Dynamic Data Type:: 'dynamic
7452 * Hash Tables:: 'hash-table
7453 * Hashing:: 'hash, 'sierpinski, 'soundex
7454 * Object:: 'object
7455 * Priority Queues:: 'priority-queue
7456 * Queues:: 'queue
7457 * Records:: 'record
7458 * Structures:: 'struct, 'structure
7459 @end menu
7460
7461
7462
7463
7464 @node Arrays, Array Mapping, Data Structures, Data Structures
7465 @subsection Arrays
7466
7467 @code{(require 'array)}
7468 @ftindex array
7469
7470 @defun array? obj
7471 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
7472 @end defun
7473
7474 @defun make-array initial-value bound1 bound2 @dots{}
7475 Creates and returns an array that has as many dimensins as there are
7476 @var{bound}s and fills it with @var{initial-value}.
7477 @end defun
7478
7479 When constructing an array, @var{bound} is either an inclusive range of
7480 indices expressed as a two element list, or an upper bound expressed as
7481 a single integer. So@refill
7482 @lisp
7483 (make-array 'foo 3 3) @equiv{} (make-array 'foo '(0 2) '(0 2))
7484 @end lisp
7485
7486 @defun make-shared-array array mapper bound1 bound2 @dots{}
7487 @code{make-shared-array} can be used to create shared subarrays of other
7488 arrays. The @var{mapper} is a function that translates coordinates in
7489 the new array into coordinates in the old array. A @var{mapper} must be
7490 linear, and its range must stay within the bounds of the old array, but
7491 it can be otherwise arbitrary. A simple example:@refill
7492 @lisp
7493 (define fred (make-array #f 8 8))
7494 (define freds-diagonal
7495 (make-shared-array fred (lambda (i) (list i i)) 8))
7496 (array-set! freds-diagonal 'foo 3)
7497 (array-ref fred 3 3)
7498 @result{} FOO
7499 (define freds-center
7500 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
7501 2 2))
7502 (array-ref freds-center 0 0)
7503 @result{} FOO
7504 @end lisp
7505 @end defun
7506
7507 @defun array-rank obj
7508 Returns the number of dimensions of @var{obj}. If @var{obj} is not an
7509 array, 0 is returned.
7510 @end defun
7511
7512 @defun array-shape array
7513 @code{array-shape} returns a list of inclusive bounds. So:
7514 @lisp
7515 (array-shape (make-array 'foo 3 5))
7516 @result{} ((0 2) (0 4))
7517 @end lisp
7518 @end defun
7519
7520 @defun array-dimensions array
7521 @code{array-dimensions} is similar to @code{array-shape} but replaces
7522 elements with a 0 minimum with one greater than the maximum. So:
7523 @lisp
7524 (array-dimensions (make-array 'foo 3 5))
7525 @result{} (3 5)
7526 @end lisp
7527 @end defun
7528
7529 @deffn Procedure array-in-bounds? array index1 index2 @dots{}
7530 Returns @code{#t} if its arguments would be acceptable to
7531 @code{array-ref}.
7532 @end deffn
7533
7534 @defun array-ref array index1 index2 @dots{}
7535 Returns the element at the @code{(@var{index1}, @var{index2})} element
7536 in @var{array}.
7537 @end defun
7538
7539 @deffn Procedure array-set! array new-value index1 index2 @dots{}
7540 @end deffn
7541
7542 @defun array-1d-ref array index
7543 @defunx array-2d-ref array index1 index2
7544 @defunx array-3d-ref array index1 index2 index3
7545 @end defun
7546
7547 @deffn Procedure array-1d-set! array new-value index
7548 @deffnx Procedure array-2d-set! array new-value index1 index2
7549 @deffnx Procedure array-3d-set! array new-value index1 index2 index3
7550 @end deffn
7551
7552 The functions are just fast versions of @code{array-ref} and
7553 @code{array-set!} that take a fixed number of arguments, and perform no
7554 bounds checking.
7555
7556 If you comment out the bounds checking code, this is about as efficient
7557 as you could ask for without help from the compiler.
7558
7559 An exercise left to the reader: implement the rest of APL.
7560
7561
7562
7563 @node Array Mapping, Association Lists, Arrays, Data Structures
7564 @subsection Array Mapping
7565
7566 @code{(require 'array-for-each)}
7567 @ftindex array-for-each
7568
7569 @defun array-map! array0 proc array1 @dots{}
7570 @var{array1}, @dots{} must have the same number of dimensions as
7571 @var{array0} and have a range for each index which includes the range
7572 for the corresponding index in @var{array0}. @var{proc} is applied to
7573 each tuple of elements of @var{array1} @dots{} and the result is stored
7574 as the corresponding element in @var{array0}. The value returned is
7575 unspecified. The order of application is unspecified.
7576 @end defun
7577
7578 @defun array-for-each @var{proc} @var{array0} @dots{}
7579 @var{proc} is applied to each tuple of elements of @var{array0} @dots{}
7580 in row-major order. The value returned is unspecified.
7581 @end defun
7582
7583 @defun array-indexes @var{array}
7584 Returns an array of lists of indexes for @var{array} such that, if
7585 @var{li} is a list of indexes for which @var{array} is defined, (equal?
7586 @var{li} (apply array-ref (array-indexes @var{array}) @var{li})).
7587 @end defun
7588
7589 @defun array-index-map! array proc
7590 applies @var{proc} to the indices of each element of @var{array} in
7591 turn, storing the result in the corresponding element. The value
7592 returned and the order of application are unspecified.
7593
7594 One can implement @var{array-indexes} as
7595 @example
7596 (define (array-indexes array)
7597 (let ((ra (apply make-array #f (array-shape array))))
7598 (array-index-map! ra (lambda x x))
7599 ra))
7600 @end example
7601 Another example:
7602 @example
7603 (define (apl:index-generator n)
7604 (let ((v (make-uniform-vector n 1)))
7605 (array-index-map! v (lambda (i) i))
7606 v))
7607 @end example
7608 @end defun
7609
7610 @defun array-copy! source destination
7611 Copies every element from vector or array @var{source} to the
7612 corresponding element of @var{destination}. @var{destination} must have
7613 the same rank as @var{source}, and be at least as large in each
7614 dimension. The order of copying is unspecified.
7615 @end defun
7616
7617
7618 @node Association Lists, Byte, Array Mapping, Data Structures
7619 @subsection Association Lists
7620
7621 @code{(require 'alist)}
7622 @ftindex alist
7623
7624 Alist functions provide utilities for treating a list of key-value pairs
7625 as an associative database. These functions take an equality predicate,
7626 @var{pred}, as an argument. This predicate should be repeatable,
7627 symmetric, and transitive.
7628
7629 Alist functions can be used with a secondary index method such as hash
7630 tables for improved performance.
7631
7632 @defun predicate->asso pred
7633 Returns an @dfn{association function} (like @code{assq}, @code{assv}, or
7634 @code{assoc}) corresponding to @var{pred}. The returned function
7635 returns a key-value pair whose key is @code{pred}-equal to its first
7636 argument or @code{#f} if no key in the alist is @var{pred}-equal to the
7637 first argument.
7638 @end defun
7639
7640 @defun alist-inquirer pred
7641 Returns a procedure of 2 arguments, @var{alist} and @var{key}, which
7642 returns the value associated with @var{key} in @var{alist} or @code{#f} if
7643 @var{key} does not appear in @var{alist}.
7644 @end defun
7645
7646 @defun alist-associator pred
7647 Returns a procedure of 3 arguments, @var{alist}, @var{key}, and
7648 @var{value}, which returns an alist with @var{key} and @var{value}
7649 associated. Any previous value associated with @var{key} will be
7650 lost. This returned procedure may or may not have side effects on its
7651 @var{alist} argument. An example of correct usage is:@refill
7652 @lisp
7653 (define put (alist-associator string-ci=?))
7654 (define alist '())
7655 (set! alist (put alist "Foo" 9))
7656 @end lisp
7657 @end defun
7658
7659 @defun alist-remover pred
7660 Returns a procedure of 2 arguments, @var{alist} and @var{key}, which
7661 returns an alist with an association whose @var{key} is key removed.
7662 This returned procedure may or may not have side effects on its
7663 @var{alist} argument. An example of correct usage is:@refill
7664 @lisp
7665 (define rem (alist-remover string-ci=?))
7666 (set! alist (rem alist "foo"))
7667 @end lisp
7668 @end defun
7669
7670 @defun alist-map proc alist
7671 Returns a new association list formed by mapping @var{proc} over the
7672 keys and values of @var{alist}. @var{proc} must be a function of 2
7673 arguments which returns the new value part.
7674 @end defun
7675
7676 @defun alist-for-each proc alist
7677 Applies @var{proc} to each pair of keys and values of @var{alist}.
7678 @var{proc} must be a function of 2 arguments. The returned value is
7679 unspecified.
7680 @end defun
7681
7682 @node Byte, Portable Image Files, Association Lists, Data Structures
7683 @subsection Byte
7684
7685 @code{(require 'byte)}
7686
7687 Some algorithms are expressed in terms of arrays of small integers.
7688 Using Scheme strings to implement these arrays is not portable vis-a-vis
7689 the correspondence between integers and characters and non-ascii
7690 character sets. These functions abstract the notion of a @dfn{byte}.
7691 @cindex byte
7692
7693 @deffn Function byte-ref bytes k
7694 @var{k} must be a valid index of @var{bytes}. @code{byte-ref} returns
7695 byte @var{k} of @var{bytes} using zero-origin indexing.
7696 @findex byte-ref
7697 @end deffn
7698
7699 @deffn Procedure byte-set! bytes k byte
7700 @var{k} must be a valid index of @var{bytes}%, and @var{byte} must be a
7701 small integer. @code{Byte-set!} stores @var{byte} in element @var{k}
7702 of @var{bytes}
7703 @findex byte-set!
7704 and returns an unspecified value. @c <!>
7705
7706 @end deffn
7707
7708 @deffn Function make-bytes k
7709 @deffnx Function make-bytes k byte
7710
7711 @code{Make-bytes} returns a newly allocated byte-array of
7712 @findex make-bytes
7713 length @var{k}. If @var{byte} is given, then all elements of the
7714 byte-array are initialized to @var{byte}, otherwise the contents of the
7715 byte-array are unspecified.
7716
7717 @end deffn
7718
7719 @deffn Function bytes-length bytes
7720
7721 @code{bytes-length} returns length of byte-array @var{bytes}.
7722 @findex bytes-length
7723
7724 @end deffn
7725
7726 @deffn Function write-byte byte
7727 @deffnx Function write-byte byte port
7728
7729 Writes the byte @var{byte} (not an external representation of the
7730 byte) to the given @var{port} and returns an unspecified value. The
7731 @var{port} argument may be omitted, in which case it defaults to the value
7732 returned by @code{current-output-port}.
7733 @findex current-output-port
7734
7735 @end deffn
7736
7737 @deffn Function read-byte
7738 @deffnx Function read-byte port
7739
7740 Returns the next byte available from the input @var{port}, updating
7741 the @var{port} to point to the following byte. If no more bytes
7742 are available, an end of file object is returned. @var{Port} may be
7743 omitted, in which case it defaults to the value returned by
7744 @code{current-input-port}.
7745 @findex current-input-port
7746
7747 @end deffn
7748
7749 @deffn Function bytes byte @dots{}
7750
7751 Returns a newly allocated byte-array composed of the arguments.
7752
7753 @end deffn
7754
7755 @deffn Function bytes->list bytes
7756 @deffnx Function list->bytes bytes
7757
7758 @code{Bytes->list} returns a newly allocated list of the
7759 @findex bytes->list
7760 bytes that make up the given byte-array. @code{List->bytes}
7761 @findex list->bytes
7762 returns a newly allocated byte-array formed from the small integers in
7763 the list @var{bytes}. @code{Bytes->list} and @code{list->bytes} are
7764 @findex list->bytes
7765 @findex bytes->list
7766 inverses so far as @code{equal?} is concerned.
7767 @findex equal?
7768
7769 @end deffn
7770
7771 @node Portable Image Files, Collections, Byte, Data Structures
7772 @subsection Portable Image Files
7773
7774 @code{(require 'pnm)}
7775
7776 @deffn Function pnm:type-dimensions path
7777 The string @var{path} must name a @dfn{portable bitmap graphics} file.
7778 @code{pnm:type-dimensions} returns a list of 4 items:
7779 @enumerate
7780 @item
7781 A symbol describing the type of the file named by @var{path}.
7782 @item
7783 The image width in pixels.
7784 @item
7785 The image height in pixels.
7786 @item
7787 The maximum value of pixels assume in the file.
7788 @end enumerate
7789
7790 The current set of file-type symbols is:
7791 @table @asis
7792 @item pbm
7793 @itemx pbm-raw
7794 Black-and-White image; pixel values are 0 or 1.
7795 @item pgm
7796 @itemx pgm-raw
7797 Gray (monochrome) image; pixel values are from 0 to @var{maxval}
7798 specified in file header.
7799 @item ppm
7800 @itemx ppm-raw
7801 RGB (full color) image; red, green, and blue interleaved pixel values
7802 are from 0 to @var{maxval}
7803 @end table
7804
7805 @end deffn
7806
7807 @deffn Function pnm:image-file->array path array
7808
7809 Reads the @dfn{portable bitmap graphics} file named by @var{path} into
7810 @var{array}. @var{array} must be the correct size and type for
7811 @var{path}. @var{array} is returned.
7812
7813 @deffnx Function pnm:image-file->array path
7814
7815 @code{pnm:image-file->array} creates and returns an array with the
7816 @dfn{portable bitmap graphics} file named by @var{path} read into it.
7817
7818 @end deffn
7819
7820 @deffn Procedure pnm:array-write type array maxval path
7821
7822 Writes the contents of @var{array} to a @var{type} image file named
7823 @var{path}. The file will have pixel values between 0 and @var{maxval},
7824 which must be compatible with @var{type}. For @samp{pbm} files,
7825 @var{maxval} must be @samp{1}.
7826
7827 @end deffn
7828
7829
7830 @node Collections, Dynamic Data Type, Portable Image Files, Data Structures
7831 @subsection Collections
7832
7833 @c Much of the documentation in this section was written by Dave Love
7834 @c (d.love@dl.ac.uk) -- don't blame Ken Dickey for its faults.
7835 @c but we can blame him for not writing it!
7836
7837 @code{(require 'collect)}
7838 @ftindex collect
7839
7840 Routines for managing collections. Collections are aggregate data
7841 structures supporting iteration over their elements, similar to the
7842 Dylan(TM) language, but with a different interface. They have
7843 @dfn{elements} indexed by corresponding @dfn{keys}, although the keys
7844 may be implicit (as with lists).
7845
7846 New types of collections may be defined as YASOS objects (@pxref{Yasos}).
7847 They must support the following operations:
7848 @itemize @bullet
7849 @item
7850 @code{(collection? @var{self})} (always returns @code{#t});
7851
7852 @item
7853 @code{(size @var{self})} returns the number of elements in the collection;
7854
7855 @item
7856 @code{(print @var{self} @var{port})} is a specialized print operation
7857 for the collection which prints a suitable representation on the given
7858 @var{port} or returns it as a string if @var{port} is @code{#t};@refill
7859
7860 @item
7861 @code{(gen-elts @var{self})} returns a thunk which on successive
7862 invocations yields elements of @var{self} in order or gives an error if
7863 it is invoked more than @code{(size @var{self})} times;@refill
7864
7865 @item
7866 @code{(gen-keys @var{self})} is like @code{gen-elts}, but yields the
7867 collection's keys in order.
7868
7869 @end itemize
7870 They might support specialized @code{for-each-key} and
7871 @code{for-each-elt} operations.
7872
7873 @defun collection? obj
7874 A predicate, true initially of lists, vectors and strings. New sorts of
7875 collections must answer @code{#t} to @code{collection?}.
7876 @end defun
7877
7878 @deffn Procedure map-elts proc . collections
7879 @deffnx Procedure do-elts proc . collections
7880 @var{proc} is a procedure taking as many arguments as there are
7881 @var{collections} (at least one). The @var{collections} are iterated
7882 over in their natural order and @var{proc} is applied to the elements
7883 yielded by each iteration in turn. The order in which the arguments are
7884 supplied corresponds to te order in which the @var{collections} appear.
7885 @code{do-elts} is used when only side-effects of @var{proc} are of
7886 interest and its return value is unspecified. @code{map-elts} returns a
7887 collection (actually a vector) of the results of the applications of
7888 @var{proc}.
7889
7890 Example:
7891 @lisp
7892 (map-elts + (list 1 2 3) (vector 1 2 3))
7893 @result{} #(2 4 6)
7894 @end lisp
7895 @end deffn
7896
7897 @deffn Procedure map-keys proc . collections
7898 @deffnx Procedure do-keys proc . collections
7899 These are analogous to @code{map-elts} and @code{do-elts}, but each
7900 iteration is over the @var{collections}' @emph{keys} rather than their
7901 elements.
7902
7903 Example:
7904 @lisp
7905 (map-keys + (list 1 2 3) (vector 1 2 3))
7906 @result{} #(0 2 4)
7907 @end lisp
7908 @end deffn
7909
7910 @deffn Procedure for-each-key collection proc
7911 @deffnx Procedure for-each-elt collection proc
7912 These are like @code{do-keys} and @code{do-elts} but only for a single
7913 collection; they are potentially more efficient.
7914 @end deffn
7915
7916 @defun reduce proc seed . collections
7917 A generalization of the list-based @code{comlist:reduce-init}
7918 (@pxref{Lists as sequences}) to collections which will shadow the
7919 list-based version if @code{(require 'collect)} follows
7920 @ftindex collect
7921 @code{(require 'common-list-functions)} (@pxref{Common List
7922 Functions}).
7923 @ftindex common-list-functions
7924
7925 Examples:
7926 @lisp
7927 (reduce + 0 (vector 1 2 3))
7928 @result{} 6
7929 (reduce union '() '((a b c) (b c d) (d a)))
7930 @result{} (c b d a).
7931 @end lisp
7932 @end defun
7933
7934 @defun any? pred . collections
7935 A generalization of the list-based @code{some} (@pxref{Lists as
7936 sequences}) to collections.
7937
7938 Example:
7939 @lisp
7940 (any? odd? (list 2 3 4 5))
7941 @result{} #t
7942 @end lisp
7943 @end defun
7944
7945 @defun every? pred . collections
7946 A generalization of the list-based @code{every} (@pxref{Lists as
7947 sequences}) to collections.
7948
7949 Example:
7950 @lisp
7951 (every? collection? '((1 2) #(1 2)))
7952 @result{} #t
7953 @end lisp
7954 @end defun
7955
7956 @defun empty? collection
7957 Returns @code{#t} iff there are no elements in @var{collection}.
7958
7959 @code{(empty? @var{collection}) @equiv{} (zero? (size @var{collection}))}
7960 @end defun
7961
7962 @defun size collection
7963 Returns the number of elements in @var{collection}.
7964 @end defun
7965
7966 @defun Setter list-ref
7967 See @ref{Setters} for a definition of @dfn{setter}. N.B.
7968 @code{(setter list-ref)} doesn't work properly for element 0 of a
7969 list.
7970 @end defun
7971
7972 Here is a sample collection: @code{simple-table} which is also a
7973 @code{table}.
7974 @lisp
7975 (define-predicate TABLE?)
7976 (define-operation (LOOKUP table key failure-object))
7977 (define-operation (ASSOCIATE! table key value)) ;; returns key
7978 (define-operation (REMOVE! table key)) ;; returns value
7979
7980 (define (MAKE-SIMPLE-TABLE)
7981 (let ( (table (list)) )
7982 (object
7983 ;; table behaviors
7984 ((TABLE? self) #t)
7985 ((SIZE self) (size table))
7986 ((PRINT self port) (format port "#<SIMPLE-TABLE>"))
7987 ((LOOKUP self key failure-object)
7988 (cond
7989 ((assq key table) => cdr)
7990 (else failure-object)
7991 ))
7992 ((ASSOCIATE! self key value)
7993 (cond
7994 ((assq key table)
7995 => (lambda (bucket) (set-cdr! bucket value) key))
7996 (else
7997 (set! table (cons (cons key value) table))
7998 key)
7999 ))
8000 ((REMOVE! self key);; returns old value
8001 (cond
8002 ((null? table) (slib:error "TABLE:REMOVE! Key not found: " key))
8003 ((eq? key (caar table))
8004 (let ( (value (cdar table)) )
8005 (set! table (cdr table))
8006 value)
8007 )
8008 (else
8009 (let loop ( (last table) (this (cdr table)) )
8010 (cond
8011 ((null? this)
8012 (slib:error "TABLE:REMOVE! Key not found: " key))
8013 ((eq? key (caar this))
8014 (let ( (value (cdar this)) )
8015 (set-cdr! last (cdr this))
8016 value)
8017 )
8018 (else
8019 (loop (cdr last) (cdr this)))
8020 ) ) )
8021 ))
8022 ;; collection behaviors
8023 ((COLLECTION? self) #t)
8024 ((GEN-KEYS self) (collect:list-gen-elts (map car table)))
8025 ((GEN-ELTS self) (collect:list-gen-elts (map cdr table)))
8026 ((FOR-EACH-KEY self proc)
8027 (for-each (lambda (bucket) (proc (car bucket))) table)
8028 )
8029 ((FOR-EACH-ELT self proc)
8030 (for-each (lambda (bucket) (proc (cdr bucket))) table)
8031 )
8032 ) ) )
8033 @end lisp
8034
8035
8036
8037
8038
8039 @node Dynamic Data Type, Hash Tables, Collections, Data Structures
8040 @subsection Dynamic Data Type
8041
8042 @code{(require 'dynamic)}
8043 @ftindex dynamic
8044
8045 @defun make-dynamic obj
8046 Create and returns a new @dfn{dynamic} whose global value is @var{obj}.
8047 @end defun
8048
8049 @defun dynamic? obj
8050 Returns true if and only if @var{obj} is a dynamic. No object
8051 satisfying @code{dynamic?} satisfies any of the other standard type
8052 predicates.
8053 @end defun
8054
8055 @defun dynamic-ref dyn
8056 Return the value of the given dynamic in the current dynamic
8057 environment.
8058 @end defun
8059
8060 @deffn Procedure dynamic-set! dyn obj
8061 Change the value of the given dynamic to @var{obj} in the current
8062 dynamic environment. The returned value is unspecified.
8063 @end deffn
8064
8065 @defun call-with-dynamic-binding dyn obj thunk
8066 Invoke and return the value of the given thunk in a new, nested dynamic
8067 environment in which the given dynamic has been bound to a new location
8068 whose initial contents are the value @var{obj}. This dynamic
8069 environment has precisely the same extent as the invocation of the thunk
8070 and is thus captured by continuations created within that invocation and
8071 re-established by those continuations when they are invoked.
8072 @end defun
8073
8074 The @code{dynamic-bind} macro is not implemented.
8075
8076
8077
8078
8079 @node Hash Tables, Hashing, Dynamic Data Type, Data Structures
8080 @subsection Hash Tables
8081
8082 @code{(require 'hash-table)}
8083 @ftindex hash-table
8084
8085 @defun predicate->hash pred
8086 Returns a hash function (like @code{hashq}, @code{hashv}, or
8087 @code{hash}) corresponding to the equality predicate @var{pred}.
8088 @var{pred} should be @code{eq?}, @code{eqv?}, @code{equal?}, @code{=},
8089 @code{char=?}, @code{char-ci=?}, @code{string=?}, or
8090 @code{string-ci=?}.
8091 @end defun
8092
8093 A hash table is a vector of association lists.
8094
8095 @defun make-hash-table k
8096 Returns a vector of @var{k} empty (association) lists.
8097 @end defun
8098
8099 Hash table functions provide utilities for an associative database.
8100 These functions take an equality predicate, @var{pred}, as an argument.
8101 @var{pred} should be @code{eq?}, @code{eqv?}, @code{equal?}, @code{=},
8102 @code{char=?}, @code{char-ci=?}, @code{string=?}, or
8103 @code{string-ci=?}.
8104
8105 @defun predicate->hash-asso pred
8106 Returns a hash association function of 2 arguments, @var{key} and
8107 @var{hashtab}, corresponding to @var{pred}. The returned function
8108 returns a key-value pair whose key is @var{pred}-equal to its first
8109 argument or @code{#f} if no key in @var{hashtab} is @var{pred}-equal to
8110 the first argument.
8111 @end defun
8112
8113 @defun hash-inquirer pred
8114 Returns a procedure of 3 arguments, @code{hashtab} and @code{key}, which
8115 returns the value associated with @code{key} in @code{hashtab} or
8116 @code{#f} if key does not appear in @code{hashtab}.
8117 @end defun
8118
8119 @defun hash-associator pred
8120 Returns a procedure of 3 arguments, @var{hashtab}, @var{key}, and
8121 @var{value}, which modifies @var{hashtab} so that @var{key} and
8122 @var{value} associated. Any previous value associated with @var{key}
8123 will be lost.
8124 @end defun
8125
8126 @defun hash-remover pred
8127 Returns a procedure of 2 arguments, @var{hashtab} and @var{key}, which
8128 modifies @var{hashtab} so that the association whose key is @var{key} is
8129 removed.
8130 @end defun
8131
8132 @defun hash-map proc hash-table
8133 Returns a new hash table formed by mapping @var{proc} over the
8134 keys and values of @var{hash-table}. @var{proc} must be a function of 2
8135 arguments which returns the new value part.
8136 @end defun
8137
8138 @defun hash-for-each proc hash-table
8139 Applies @var{proc} to each pair of keys and values of @var{hash-table}.
8140 @var{proc} must be a function of 2 arguments. The returned value is
8141 unspecified.
8142 @end defun
8143
8144
8145
8146
8147
8148 @node Hashing, Object, Hash Tables, Data Structures
8149 @subsection Hashing
8150
8151 @code{(require 'hash)}
8152 @ftindex hash
8153
8154 These hashing functions are for use in quickly classifying objects.
8155 Hash tables use these functions.
8156
8157 @defun hashq obj k
8158 @defunx hashv obj k
8159 @defunx hash obj k
8160 Returns an exact non-negative integer less than @var{k}. For each
8161 non-negative integer less than @var{k} there are arguments @var{obj} for
8162 which the hashing functions applied to @var{obj} and @var{k} returns
8163 that integer.
8164
8165 For @code{hashq}, @code{(eq? obj1 obj2)} implies @code{(= (hashq obj1 k)
8166 (hashq obj2))}.
8167
8168 For @code{hashv}, @code{(eqv? obj1 obj2)} implies @code{(= (hashv obj1 k)
8169 (hashv obj2))}.
8170
8171 For @code{hash}, @code{(equal? obj1 obj2)} implies @code{(= (hash obj1 k)
8172 (hash obj2))}.
8173
8174 @code{hash}, @code{hashv}, and @code{hashq} return in time bounded by a
8175 constant. Notice that items having the same @code{hash} implies the
8176 items have the same @code{hashv} implies the items have the same
8177 @code{hashq}.
8178 @end defun
8179
8180
8181 @code{(require 'sierpinski)}
8182 @ftindex sierpinski
8183
8184 @defun make-sierpinski-indexer max-coordinate
8185 Returns a procedure (eg hash-function) of 2 numeric arguments which
8186 preserves @emph{nearness} in its mapping from NxN to N.
8187
8188 @var{max-coordinate} is the maximum coordinate (a positive integer) of a
8189 population of points. The returned procedures is a function that takes
8190 the x and y coordinates of a point, (non-negative integers) and returns
8191 an integer corresponding to the relative position of that point along a
8192 Sierpinski curve. (You can think of this as computing a (pseudo-)
8193 inverse of the Sierpinski spacefilling curve.)
8194
8195 Example use: Make an indexer (hash-function) for integer points lying in
8196 square of integer grid points [0,99]x[0,99]:
8197 @example
8198 (define space-key (make-sierpinski-indexer 100))
8199 @end example
8200 Now let's compute the index of some points:
8201 @example
8202 (space-key 24 78) @result{} 9206
8203 (space-key 23 80) @result{} 9172
8204 @end example
8205
8206 Note that locations (24, 78) and (23, 80) are near in index and
8207 therefore, because the Sierpinski spacefilling curve is continuous, we
8208 know they must also be near in the plane. Nearness in the plane does
8209 not, however, necessarily correspond to nearness in index, although it
8210 @emph{tends} to be so.
8211
8212 Example applications:
8213 @itemize @bullet
8214
8215 @item
8216 Sort points by Sierpinski index to get heuristic solution to
8217 @emph{travelling salesman problem}. For details of performance,
8218 see L. Platzman and J. Bartholdi, "Spacefilling curves and the
8219 Euclidean travelling salesman problem", JACM 36(4):719--737
8220 (October 1989) and references therein.
8221
8222 @item
8223 Use Sierpinski index as key by which to store 2-dimensional data
8224 in a 1-dimensional data structure (such as a table). Then
8225 locations that are near each other in 2-d space will tend to
8226 be near each other in 1-d data structure; and locations that
8227 are near in 1-d data structure will be near in 2-d space. This
8228 can significantly speed retrieval from secondary storage because
8229 contiguous regions in the plane will tend to correspond to
8230 contiguous regions in secondary storage. (This is a standard
8231 technique for managing CAD/CAM or geographic data.)
8232
8233 @end itemize
8234 @end defun
8235
8236
8237
8238 @code{(require 'soundex)}
8239 @ftindex soundex
8240
8241 @defun soundex name
8242 Computes the @emph{soundex} hash of @var{name}. Returns a string of an
8243 initial letter and up to three digits between 0 and 6. Soundex
8244 supposedly has the property that names that sound similar in normal
8245 English pronunciation tend to map to the same key.
8246
8247 Soundex was a classic algorithm used for manual filing of personal
8248 records before the advent of computers. It performs adequately for
8249 English names but has trouble with other languages.
8250
8251 See Knuth, Vol. 3 @cite{Sorting and searching}, pp 391--2
8252
8253 To manage unusual inputs, @code{soundex} omits all non-alphabetic
8254 characters. Consequently, in this implementation:
8255
8256 @example
8257 (soundex <string of blanks>) @result{} ""
8258 (soundex "") @result{} ""
8259 @end example
8260
8261 Examples from Knuth:
8262
8263 @example
8264 (map soundex '("Euler" "Gauss" "Hilbert" "Knuth"
8265 "Lloyd" "Lukasiewicz"))
8266 @result{} ("E460" "G200" "H416" "K530" "L300" "L222")
8267
8268 (map soundex '("Ellery" "Ghosh" "Heilbronn" "Kant"
8269 "Ladd" "Lissajous"))
8270 @result{} ("E460" "G200" "H416" "K530" "L300" "L222")
8271 @end example
8272
8273 Some cases in which the algorithm fails (Knuth):
8274
8275 @example
8276 (map soundex '("Rogers" "Rodgers")) @result{} ("R262" "R326")
8277
8278 (map soundex '("Sinclair" "St. Clair")) @result{} ("S524" "S324")
8279
8280 (map soundex '("Tchebysheff" "Chebyshev")) @result{} ("T212" "C121")
8281 @end example
8282 @end defun
8283
8284
8285 @node Object, Priority Queues, Hashing, Data Structures
8286 @subsection Macroless Object System
8287 @include objdoc.txi
8288
8289
8290 @node Priority Queues, Queues, Object, Data Structures
8291 @subsection Priority Queues
8292
8293 @code{(require 'priority-queue)}
8294 @ftindex priority-queue
8295
8296 @defun make-heap pred<?
8297 Returns a binary heap suitable which can be used for priority queue
8298 operations.
8299 @end defun
8300
8301 @defun heap-length heap
8302 Returns the number of elements in @var{heap}.
8303 @end defun
8304
8305 @deffn Procedure heap-insert! heap item
8306 Inserts @var{item} into @var{heap}. @var{item} can be inserted multiple
8307 times. The value returned is unspecified.
8308 @end deffn
8309
8310 @defun heap-extract-max! heap
8311 Returns the item which is larger than all others according to the
8312 @var{pred<?} argument to @code{make-heap}. If there are no items in
8313 @var{heap}, an error is signaled.
8314 @end defun
8315
8316 The algorithm for priority queues was taken from @cite{Introduction to
8317 Algorithms} by T. Cormen, C. Leiserson, R. Rivest. 1989 MIT Press.
8318
8319
8320
8321 @node Queues, Records, Priority Queues, Data Structures
8322 @subsection Queues
8323
8324 @code{(require 'queue)}
8325 @ftindex queue
8326
8327 A @dfn{queue} is a list where elements can be added to both the front
8328 and rear, and removed from the front (i.e., they are what are often
8329 called @dfn{dequeues}). A queue may also be used like a stack.
8330
8331 @defun make-queue
8332 Returns a new, empty queue.
8333 @end defun
8334
8335 @defun queue? obj
8336 Returns @code{#t} if @var{obj} is a queue.
8337 @end defun
8338
8339 @defun queue-empty? q
8340 Returns @code{#t} if the queue @var{q} is empty.
8341 @end defun
8342
8343 @deffn Procedure queue-push! q datum
8344 Adds @var{datum} to the front of queue @var{q}.
8345 @end deffn
8346
8347 @deffn Procedure enquque! q datum
8348 Adds @var{datum} to the rear of queue @var{q}.
8349 @end deffn
8350
8351 All of the following functions raise an error if the queue @var{q} is
8352 empty.
8353
8354 @defun queue-front q
8355 Returns the datum at the front of the queue @var{q}.
8356 @end defun
8357
8358 @defun queue-rear q
8359 Returns the datum at the rear of the queue @var{q}.
8360 @end defun
8361
8362 @deffn Prcoedure queue-pop! q
8363 @deffnx Procedure dequeue! q
8364 Both of these procedures remove and return the datum at the front of the
8365 queue. @code{queue-pop!} is used to suggest that the queue is being
8366 used like a stack.
8367 @end deffn
8368
8369
8370
8371
8372
8373 @node Records, Structures, Queues, Data Structures
8374 @subsection Records
8375
8376 @code{(require 'record)}
8377 @ftindex record
8378
8379 The Record package provides a facility for user to define their own
8380 record data types.
8381
8382 @defun make-record-type type-name field-names
8383 Returns a @dfn{record-type descriptor}, a value representing a new data
8384 type disjoint from all others. The @var{type-name} argument must be a
8385 string, but is only used for debugging purposes (such as the printed
8386 representation of a record of the new type). The @var{field-names}
8387 argument is a list of symbols naming the @dfn{fields} of a record of the
8388 new type. It is an error if the list contains any duplicates. It is
8389 unspecified how record-type descriptors are represented.
8390 @end defun
8391
8392 @c @defun make-record-sub-type type-name field-names rtd
8393 @c Returns a @dfn{record-type descriptor}, a value representing a new data
8394 @c type, disjoint from all others. The @var{type-name} argument must be a
8395 @c string. The @var{field-names} argument is a list of symbols naming the
8396 @c additional @dfn{fields} to be appended to @var{field-names} of
8397 @c @var{rtd}. It is an error if the combinded list contains any
8398 @c duplicates.
8399 @c
8400 @c Record-modifiers and record-accessors for @var{rtd} work for the new
8401 @c record-sub-type as well. But record-modifiers and record-accessors for
8402 @c the new record-sub-type will not neccessarily work for @var{rtd}.
8403 @c @end defun
8404
8405 @defun record-constructor rtd [field-names]
8406 Returns a procedure for constructing new members of the type represented
8407 by @var{rtd}. The returned procedure accepts exactly as many arguments
8408 as there are symbols in the given list, @var{field-names}; these are
8409 used, in order, as the initial values of those fields in a new record,
8410 which is returned by the constructor procedure. The values of any
8411 fields not named in that list are unspecified. The @var{field-names}
8412 argument defaults to the list of field names in the call to
8413 @code{make-record-type} that created the type represented by @var{rtd};
8414 if the @var{field-names} argument is provided, it is an error if it
8415 contains any duplicates or any symbols not in the default list.
8416 @end defun
8417
8418 @defun record-predicate rtd
8419 Returns a procedure for testing membership in the type represented by
8420 @var{rtd}. The returned procedure accepts exactly one argument and
8421 returns a true value if the argument is a member of the indicated record
8422 type; it returns a false value otherwise.
8423 @end defun
8424
8425 @c @defun record-sub-predicate rtd
8426 @c Returns a procedure for testing membership in the type represented by
8427 @c @var{rtd} or its parents. The returned procedure accepts exactly one
8428 @c argument and returns a true value if the argument is a member of the
8429 @c indicated record type or its parents; it returns a false value
8430 @c otherwise.
8431 @c @end defun
8432
8433 @defun record-accessor rtd field-name
8434 Returns a procedure for reading the value of a particular field of a
8435 member of the type represented by @var{rtd}. The returned procedure
8436 accepts exactly one argument which must be a record of the appropriate
8437 type; it returns the current value of the field named by the symbol
8438 @var{field-name} in that record. The symbol @var{field-name} must be a
8439 member of the list of field-names in the call to @code{make-record-type}
8440 that created the type represented by @var{rtd}.
8441 @end defun
8442
8443
8444 @defun record-modifier rtd field-name
8445 Returns a procedure for writing the value of a particular field of a
8446 member of the type represented by @var{rtd}. The returned procedure
8447 accepts exactly two arguments: first, a record of the appropriate type,
8448 and second, an arbitrary Scheme value; it modifies the field named by
8449 the symbol @var{field-name} in that record to contain the given value.
8450 The returned value of the modifier procedure is unspecified. The symbol
8451 @var{field-name} must be a member of the list of field-names in the call
8452 to @code{make-record-type} that created the type represented by
8453 @var{rtd}.
8454 @end defun
8455
8456 In May of 1996, as a product of discussion on the @code{rrrs-authors}
8457 mailing list, I rewrote @file{record.scm} to portably implement type
8458 disjointness for record data types.
8459
8460 As long as an implementation's procedures are opaque and the
8461 @code{record} code is loaded before other programs, this will give
8462 disjoint record types which are unforgeable and incorruptible by R4RS
8463 procedures.
8464
8465 As a consequence, the procedures @code{record?},
8466 @code{record-type-descriptor}, @code{record-type-name}.and
8467 @code{record-type-field-names} are no longer supported.
8468
8469 @ignore
8470 @defun record? obj
8471 Returns a true value if @var{obj} is a record of any type and a false
8472 value otherwise. Note that @code{record?} may be true of any Scheme
8473 value; of course, if it returns true for some particular value, then
8474 @code{record-type-descriptor} is applicable to that value and returns an
8475 appropriate descriptor.
8476 @end defun
8477
8478 @defun record-type-descriptor record
8479 Returns a record-type descriptor representing the type of the given
8480 record. That is, for example, if the returned descriptor were passed to
8481 @code{record-predicate}, the resulting predicate would return a true
8482 value when passed the given record. Note that it is not necessarily the
8483 case that the returned descriptor is the one that was passed to
8484 @code{record-constructor} in the call that created the constructor
8485 procedure that created the given record.
8486 @end defun
8487
8488 @defun record-type-name rtd
8489 Returns the type-name associated with the type represented by rtd. The
8490 returned value is @code{eqv?} to the @var{type-name} argument given in
8491 the call to @code{make-record-type} that created the type represented by
8492 @var{rtd}.
8493 @end defun
8494
8495 @defun record-type-field-names rtd
8496 Returns a list of the symbols naming the fields in members of the type
8497 represented by @var{rtd}. The returned value is @code{equal?} to the
8498 field-names argument given in the call to @code{make-record-type} that
8499 created the type represented by @var{rtd}.
8500 @end defun
8501 @end ignore
8502
8503
8504 @node Structures, , Records, Data Structures
8505 @subsection Structures
8506
8507 @code{(require 'struct)} (uses defmacros)
8508 @ftindex struct
8509
8510 @code{defmacro}s which implement @dfn{records} from the book
8511 @cite{Essentials of Programming Languages} by Daniel P. Friedman, M.
8512 Wand and C.T. Haynes. Copyright 1992 Jeff Alexander, Shinnder Lee, and
8513 Lewis Patterson@refill
8514
8515 Matthew McDonald <mafm@@cs.uwa.edu.au> added field setters.
8516
8517 @defmac define-record tag (var1 var2 @dots{})
8518 Defines several functions pertaining to record-name @var{tag}:
8519
8520 @defun make-@var{tag} var1 var2 @dots{}
8521 @end defun
8522 @defun @var{tag}? obj
8523 @end defun
8524 @defun @var{tag}->var1 obj
8525 @end defun
8526 @defun @var{tag}->var2 obj
8527 @end defun
8528 @dots{}
8529 @defun set-@var{tag}-var1! obj val
8530 @end defun
8531 @defun set-@var{tag}-var2! obj val
8532 @end defun
8533 @dots{}
8534
8535 Here is an example of its use.
8536
8537 @example
8538 (define-record term (operator left right))
8539 @result{} #<unspecified>
8540 (define foo (make-term 'plus 1 2))
8541 @result{} foo
8542 (term->left foo)
8543 @result{} 1
8544 (set-term-left! foo 2345)
8545 @result{} #<unspecified>
8546 (term->left foo)
8547 @result{} 2345
8548 @end example
8549 @end defmac
8550
8551 @defmac variant-case exp (tag (var1 var2 @dots{}) body) @dots{}
8552 executes the following for the matching clause:
8553
8554 @example
8555 ((lambda (@var{var1} @var{var} @dots{}) @var{body})
8556 (@var{tag->var1} @var{exp})
8557 (@var{tag->var2} @var{exp}) @dots{})
8558 @end example
8559 @end defmac
8560
8561
8562 @node Procedures, Standards Support, Data Structures, Other Packages
8563 @section Procedures
8564
8565 Anything that doesn't fall neatly into any of the other categories winds
8566 up here.
8567
8568 @menu
8569 * Common List Functions:: 'common-list-functions
8570 * Tree Operations:: 'tree
8571 * Type Coercion:: 'coerce
8572 * Chapter Ordering:: 'chapter-order
8573 * Sorting:: 'sort
8574 * Topological Sort:: Keep your socks on.
8575 * String-Case:: 'string-case
8576 * String Ports:: 'string-port
8577 * String Search:: Also Search from a Port.
8578 * Line I/O:: 'line-i/o
8579 * Multi-Processing:: 'process
8580 * Metric Units:: Portable manifest types for numeric values.
8581 @end menu
8582
8583
8584 @node Common List Functions, Tree Operations, Procedures, Procedures
8585 @subsection Common List Functions
8586
8587 @code{(require 'common-list-functions)}
8588 @ftindex common-list-functions
8589
8590 The procedures below follow the Common LISP equivalents apart from
8591 optional arguments in some cases.
8592
8593 @menu
8594 * List construction::
8595 * Lists as sets::
8596 * Lists as sequences::
8597 * Destructive list operations::
8598 * Non-List functions::
8599 @end menu
8600
8601
8602 @node List construction, Lists as sets, Common List Functions, Common List Functions
8603 @subsubsection List construction
8604
8605 @defun make-list k . init
8606 @code{make-list} creates and returns a list of @var{k} elements. If
8607 @var{init} is included, all elements in the list are initialized to
8608 @var{init}.
8609
8610 Example:
8611 @lisp
8612 (make-list 3)
8613 @result{} (#<unspecified> #<unspecified> #<unspecified>)
8614 (make-list 5 'foo)
8615 @result{} (foo foo foo foo foo)
8616 @end lisp
8617 @end defun
8618
8619
8620 @defun list* x . y
8621 Works like @code{list} except that the cdr of the last pair is the last
8622 argument unless there is only one argument, when the result is just that
8623 argument. Sometimes called @code{cons*}. E.g.:@refill
8624 @lisp
8625 (list* 1)
8626 @result{} 1
8627 (list* 1 2 3)
8628 @result{} (1 2 . 3)
8629 (list* 1 2 '(3 4))
8630 @result{} (1 2 3 4)
8631 (list* @var{args} '())
8632 @equiv{} (list @var{args})
8633 @end lisp
8634 @end defun
8635
8636 @defun copy-list lst
8637 @code{copy-list} makes a copy of @var{lst} using new pairs and returns
8638 it. Only the top level of the list is copied, i.e., pairs forming
8639 elements of the copied list remain @code{eq?} to the corresponding
8640 elements of the original; the copy is, however, not @code{eq?} to the
8641 original, but is @code{equal?} to it.
8642
8643 Example:
8644 @lisp
8645 (copy-list '(foo foo foo))
8646 @result{} (foo foo foo)
8647 (define q '(foo bar baz bang))
8648 (define p q)
8649 (eq? p q)
8650 @result{} #t
8651 (define r (copy-list q))
8652 (eq? q r)
8653 @result{} #f
8654 (equal? q r)
8655 @result{} #t
8656 (define bar '(bar))
8657 (eq? bar (car (copy-list (list bar 'foo))))
8658 @result{} #t
8659 @end lisp
8660 @end defun
8661
8662
8663
8664
8665
8666
8667 @node Lists as sets, Lists as sequences, List construction, Common List Functions
8668 @subsubsection Lists as sets
8669
8670 @code{eqv?} is used to test for membership by procedures which treat
8671 lists as sets.
8672
8673 @defun adjoin e l
8674 @code{adjoin} returns the adjoint of the element @var{e} and the list
8675 @var{l}. That is, if @var{e} is in @var{l}, @code{adjoin} returns
8676 @var{l}, otherwise, it returns @code{(cons @var{e} @var{l})}.
8677
8678 Example:
8679 @lisp
8680 (adjoin 'baz '(bar baz bang))
8681 @result{} (bar baz bang)
8682 (adjoin 'foo '(bar baz bang))
8683 @result{} (foo bar baz bang)
8684 @end lisp
8685 @end defun
8686
8687 @defun union l1 l2
8688 @code{union} returns the combination of @var{l1} and @var{l2}.
8689 Duplicates between @var{l1} and @var{l2} are culled. Duplicates within
8690 @var{l1} or within @var{l2} may or may not be removed.
8691
8692 Example:
8693 @lisp
8694 (union '(1 2 3 4) '(5 6 7 8))
8695 @result{} (4 3 2 1 5 6 7 8)
8696 (union '(1 2 3 4) '(3 4 5 6))
8697 @result{} (2 1 3 4 5 6)
8698 @end lisp
8699 @end defun
8700
8701 @defun intersection l1 l2
8702 @code{intersection} returns all elements that are in both @var{l1} and
8703 @var{l2}.
8704
8705 Example:
8706 @lisp
8707 (intersection '(1 2 3 4) '(3 4 5 6))
8708 @result{} (4 3)
8709 (intersection '(1 2 3 4) '(5 6 7 8))
8710 @result{} ()
8711 @end lisp
8712 @end defun
8713
8714 @defun set-difference l1 l2
8715 @code{set-difference} returns all elements that are in @var{l1} but not
8716 in @var{l2}.
8717
8718 Example:
8719 @lisp
8720 (set-difference '(1 2 3 4) '(3 4 5 6))
8721 @result{} (2 1)
8722 (set-difference '(1 2 3 4) '(1 2 3 4 5 6))
8723 @result{} ()
8724 @end lisp
8725 @end defun
8726
8727 @defun member-if pred lst
8728 @code{member-if} returns @var{lst} if @code{(@var{pred} @var{element})}
8729 is @code{#t} for any @var{element} in @var{lst}. Returns @code{#f} if
8730 @var{pred} does not apply to any @var{element} in @var{lst}.
8731
8732 Example:
8733 @lisp
8734 (member-if vector? '(1 2 3 4))
8735 @result{} #f
8736 (member-if number? '(1 2 3 4))
8737 @result{} (1 2 3 4)
8738 @end lisp
8739 @end defun
8740
8741 @defun some pred lst . more-lsts
8742 @var{pred} is a boolean function of as many arguments as there are list
8743 arguments to @code{some} i.e., @var{lst} plus any optional arguments.
8744 @var{pred} is applied to successive elements of the list arguments in
8745 order. @code{some} returns @code{#t} as soon as one of these
8746 applications returns @code{#t}, and is @code{#f} if none returns
8747 @code{#t}. All the lists should have the same length.
8748
8749
8750 Example:
8751 @lisp
8752 (some odd? '(1 2 3 4))
8753 @result{} #t
8754
8755 (some odd? '(2 4 6 8))
8756 @result{} #f
8757
8758 (some > '(2 3) '(1 4))
8759 @result{} #f
8760 @end lisp
8761 @end defun
8762
8763 @defun every pred lst . more-lsts
8764 @code{every} is analogous to @code{some} except it returns @code{#t} if
8765 every application of @var{pred} is @code{#t} and @code{#f}
8766 otherwise.
8767
8768 Example:
8769 @lisp
8770 (every even? '(1 2 3 4))
8771 @result{} #f
8772
8773 (every even? '(2 4 6 8))
8774 @result{} #t
8775
8776 (every > '(2 3) '(1 4))
8777 @result{} #f
8778 @end lisp
8779 @end defun
8780
8781 @defun notany pred . lst
8782 @code{notany} is analogous to @code{some} but returns @code{#t} if no
8783 application of @var{pred} returns @code{#t} or @code{#f} as soon as any
8784 one does.
8785 @end defun
8786
8787 @defun notevery pred . lst
8788 @code{notevery} is analogous to @code{some} but returns @code{#t} as soon
8789 as an application of @var{pred} returns @code{#f}, and @code{#f}
8790 otherwise.
8791
8792 Example:
8793 @lisp
8794 (notevery even? '(1 2 3 4))
8795 @result{} #t
8796
8797 (notevery even? '(2 4 6 8))
8798 @result{} #f
8799 @end lisp
8800 @end defun
8801
8802
8803 @defun list-of?? predicate
8804 Returns a predicate which returns true if its argument is a list every
8805 element of which satisfies @var{predicate}.
8806
8807 @defunx list-of?? predicate low-bound high-bound
8808 @var{low-bound} and @var{high-bound} are non-negative integers.
8809 @code{list-of??} returns a predicate which returns true if its argument
8810 is a list of length between @var{low-bound} and @var{high-bound}
8811 (inclusive); every element of which satisfies @var{predicate}.
8812
8813 @defunx list-of?? predicate bound
8814 @var{bound} is an integer. If @var{bound} is negative, @code{list-of??}
8815 returns a predicate which returns true if its argument is a list of
8816 length greater than @code{(- @var{bound})}; every element of which
8817 satisfies @var{predicate}. Otherwise, @code{list-of??} returns a
8818 predicate which returns true if its argument is a list of length less
8819 than or equal to @var{bound}; every element of which satisfies
8820 @var{predicate}.
8821 @end defun
8822
8823
8824 @defun find-if pred lst
8825 @code{find-if} searches for the first @var{element} in @var{lst} such
8826 that @code{(@var{pred} @var{element})} returns @code{#t}. If it finds
8827 any such @var{element} in @var{lst}, @var{element} is returned.
8828 Otherwise, @code{#f} is returned.
8829
8830 Example:
8831 @lisp
8832 (find-if number? '(foo 1 bar 2))
8833 @result{} 1
8834
8835 (find-if number? '(foo bar baz bang))
8836 @result{} #f
8837
8838 (find-if symbol? '(1 2 foo bar))
8839 @result{} foo
8840 @end lisp
8841 @end defun
8842
8843 @defun remove elt lst
8844 @code{remove} removes all occurrences of @var{elt} from @var{lst} using
8845 @code{eqv?} to test for equality and returns everything that's left.
8846 N.B.: other implementations (Chez, Scheme->C and T, at least) use
8847 @code{equal?} as the equality test.
8848
8849 Example:
8850 @lisp
8851 (remove 1 '(1 2 1 3 1 4 1 5))
8852 @result{} (5 4 3 2)
8853
8854 (remove 'foo '(bar baz bang))
8855 @result{} (bang baz bar)
8856 @end lisp
8857 @end defun
8858
8859 @defun remove-if pred lst
8860 @code{remove-if} removes all @var{element}s from @var{lst} where
8861 @code{(@var{pred} @var{element})} is @code{#t} and returns everything
8862 that's left.
8863
8864 Example:
8865 @lisp
8866 (remove-if number? '(1 2 3 4))
8867 @result{} ()
8868
8869 (remove-if even? '(1 2 3 4 5 6 7 8))
8870 @result{} (7 5 3 1)
8871 @end lisp
8872 @end defun
8873
8874 @defun remove-if-not pred lst
8875 @code{remove-if-not} removes all @var{element}s from @var{lst} for which
8876 @code{(@var{pred} @var{element})} is @code{#f} and returns everything that's
8877 left.
8878
8879 Example:
8880 @lisp
8881 (remove-if-not number? '(foo bar baz))
8882 @result{} ()
8883 (remove-if-not odd? '(1 2 3 4 5 6 7 8))
8884 @result{} (7 5 3 1)
8885 @end lisp
8886 @end defun
8887
8888 @defun has-duplicates? lst
8889 returns @code{#t} if 2 members of @var{lst} are @code{equal?}, @code{#f}
8890 otherwise.
8891
8892 Example:
8893 @lisp
8894 (has-duplicates? '(1 2 3 4))
8895 @result{} #f
8896
8897 (has-duplicates? '(2 4 3 4))
8898 @result{} #t
8899 @end lisp
8900 @end defun
8901
8902 The procedure @code{remove-duplicates} uses @code{member} (rather than
8903 @code{memv}).
8904
8905 @defun remove-duplicates lst
8906 returns a copy of @var{lst} with its duplicate members removed.
8907 Elements are considered duplicate if they are @code{equal?}.
8908
8909 Example:
8910 @lisp
8911 (remove-duplicates '(1 2 3 4))
8912 @result{} (4 3 2 1)
8913
8914 (remove-duplicates '(2 4 3 4))
8915 @result{} (3 4 2)
8916 @end lisp
8917 @end defun
8918
8919
8920 @node Lists as sequences, Destructive list operations, Lists as sets, Common List Functions
8921 @subsubsection Lists as sequences
8922
8923 @defun position obj lst
8924 @code{position} returns the 0-based position of @var{obj} in @var{lst},
8925 or @code{#f} if @var{obj} does not occur in @var{lst}.
8926
8927 Example:
8928 @lisp
8929 (position 'foo '(foo bar baz bang))
8930 @result{} 0
8931 (position 'baz '(foo bar baz bang))
8932 @result{} 2
8933 (position 'oops '(foo bar baz bang))
8934 @result{} #f
8935 @end lisp
8936 @end defun
8937
8938 @defun reduce p lst
8939 @code{reduce} combines all the elements of a sequence using a binary
8940 operation (the combination is left-associative). For example, using
8941 @code{+}, one can add up all the elements. @code{reduce} allows you to
8942 apply a function which accepts only two arguments to more than 2
8943 objects. Functional programmers usually refer to this as @dfn{foldl}.
8944 @code{collect:reduce} (@pxref{Collections}) provides a version of
8945 @code{collect} generalized to collections.
8946
8947 Example:
8948 @lisp
8949 (reduce + '(1 2 3 4))
8950 @result{} 10
8951 (define (bad-sum . l) (reduce + l))
8952 (bad-sum 1 2 3 4)
8953 @equiv{} (reduce + (1 2 3 4))
8954 @equiv{} (+ (+ (+ 1 2) 3) 4)
8955 @result{} 10
8956 (bad-sum)
8957 @equiv{} (reduce + ())
8958 @result{} ()
8959 (reduce string-append '("hello" "cruel" "world"))
8960 @equiv{} (string-append (string-append "hello" "cruel") "world")
8961 @result{} "hellocruelworld"
8962 (reduce anything '())
8963 @result{} ()
8964 (reduce anything '(x))
8965 @result{} x
8966 @end lisp
8967
8968 What follows is a rather non-standard implementation of @code{reverse}
8969 in terms of @code{reduce} and a combinator elsewhere called
8970 @dfn{C}.
8971
8972 @lisp
8973 ;;; Contributed by Jussi Piitulainen (jpiitula@@ling.helsinki.fi)
8974
8975 (define commute
8976 (lambda (f)
8977 (lambda (x y)
8978 (f y x))))
8979
8980 (define reverse
8981 (lambda (args)
8982 (reduce-init (commute cons) '() args)))
8983 @end lisp
8984 @end defun
8985
8986 @defun reduce-init p init lst
8987 @code{reduce-init} is the same as reduce, except that it implicitly
8988 inserts @var{init} at the start of the list. @code{reduce-init} is
8989 preferred if you want to handle the null list, the one-element, and
8990 lists with two or more elements consistently. It is common to use the
8991 operator's idempotent as the initializer. Functional programmers
8992 usually call this @dfn{foldl}.
8993
8994 Example:
8995 @lisp
8996 (define (sum . l) (reduce-init + 0 l))
8997 (sum 1 2 3 4)
8998 @equiv{} (reduce-init + 0 (1 2 3 4))
8999 @equiv{} (+ (+ (+ (+ 0 1) 2) 3) 4)
9000 @result{} 10
9001 (sum)
9002 @equiv{} (reduce-init + 0 '())
9003 @result{} 0
9004
9005 (reduce-init string-append "@@" '("hello" "cruel" "world"))
9006 @equiv{}
9007 (string-append (string-append (string-append "@@" "hello")
9008 "cruel")
9009 "world")
9010 @result{} "@@hellocruelworld"
9011 @end lisp
9012
9013 Given a differentiation of 2 arguments, @code{diff}, the following will
9014 differentiate by any number of variables.
9015 @lisp
9016 (define (diff* exp . vars)
9017 (reduce-init diff exp vars))
9018 @end lisp
9019
9020 Example:
9021 @lisp
9022 ;;; Real-world example: Insertion sort using reduce-init.
9023
9024 (define (insert l item)
9025 (if (null? l)
9026 (list item)
9027 (if (< (car l) item)
9028 (cons (car l) (insert (cdr l) item))
9029 (cons item l))))
9030 (define (insertion-sort l) (reduce-init insert '() l))
9031
9032 (insertion-sort '(3 1 4 1 5)
9033 @equiv{} (reduce-init insert () (3 1 4 1 5))
9034 @equiv{} (insert (insert (insert (insert (insert () 3) 1) 4) 1) 5)
9035 @equiv{} (insert (insert (insert (insert (3)) 1) 4) 1) 5)
9036 @equiv{} (insert (insert (insert (1 3) 4) 1) 5)
9037 @equiv{} (insert (insert (1 3 4) 1) 5)
9038 @equiv{} (insert (1 1 3 4) 5)
9039 @result{} (1 1 3 4 5)
9040 @end lisp
9041 @end defun
9042
9043 @defun last lst n
9044 @code{last} returns the last @var{n} elements of @var{lst}. @var{n}
9045 must be a non-negative integer.
9046
9047 Example:
9048 @lisp
9049 (last '(foo bar baz bang) 2)
9050 @result{} (baz bang)
9051 (last '(1 2 3) 0)
9052 @result{} 0
9053 @end lisp
9054 @end defun
9055
9056 @defun butlast lst n
9057 @code{butlast} returns all but the last @var{n} elements of
9058 @var{lst}.
9059
9060 Example:
9061 @lisp
9062 (butlast '(a b c d) 3)
9063 @result{} (a)
9064 (butlast '(a b c d) 4)
9065 @result{} ()
9066 @end lisp
9067 @end defun
9068
9069 @noindent
9070 @code{last} and @code{butlast} split a list into two parts when given
9071 identical arugments.
9072 @example
9073 (last '(a b c d e) 2)
9074 @result{} (d e)
9075 (butlast '(a b c d e) 2)
9076 @result{} (a b c)
9077 @end example
9078
9079 @defun nthcdr n lst
9080 @code{nthcdr} takes @var{n} @code{cdr}s of @var{lst} and returns the
9081 result. Thus @code{(nthcdr 3 @var{lst})} @equiv{} @code{(cdddr
9082 @var{lst})}
9083
9084 Example:
9085 @lisp
9086 (nthcdr 2 '(a b c d))
9087 @result{} (c d)
9088 (nthcdr 0 '(a b c d))
9089 @result{} (a b c d)
9090 @end lisp
9091 @end defun
9092
9093 @defun butnthcdr n lst
9094 @code{butnthcdr} returns all but the nthcdr @var{n} elements of
9095 @var{lst}.
9096
9097 Example:
9098 @lisp
9099 (butnthcdr 3 '(a b c d))
9100 @result{} (a b c)
9101 (butnthcdr 4 '(a b c d))
9102 @result{} (a b c d)
9103 @end lisp
9104 @end defun
9105
9106 @noindent
9107 @code{nthcdr} and @code{butnthcdr} split a list into two parts when
9108 given identical arugments.
9109 @example
9110 (nthcdr 2 '(a b c d e))
9111 @result{} (c d e)
9112 (butnthcdr 2 '(a b c d e))
9113 @result{} (a b)
9114 @end example
9115
9116
9117
9118 @node Destructive list operations, Non-List functions, Lists as sequences, Common List Functions
9119 @subsubsection Destructive list operations
9120
9121 These procedures may mutate the list they operate on, but any such
9122 mutation is undefined.
9123
9124 @deffn Procedure nconc args
9125 @code{nconc} destructively concatenates its arguments. (Compare this
9126 with @code{append}, which copies arguments rather than destroying them.)
9127 Sometimes called @code{append!} (@pxref{Rev2 Procedures}).
9128
9129 Example: You want to find the subsets of a set. Here's the obvious way:
9130
9131 @lisp
9132 (define (subsets set)
9133 (if (null? set)
9134 '(())
9135 (append (mapcar (lambda (sub) (cons (car set) sub))
9136 (subsets (cdr set)))
9137 (subsets (cdr set)))))
9138 @end lisp
9139 But that does way more consing than you need. Instead, you could
9140 replace the @code{append} with @code{nconc}, since you don't have any
9141 need for all the intermediate results.
9142
9143 Example:
9144 @lisp
9145 (define x '(a b c))
9146 (define y '(d e f))
9147 (nconc x y)
9148 @result{} (a b c d e f)
9149 x
9150 @result{} (a b c d e f)
9151 @end lisp
9152
9153 @code{nconc} is the same as @code{append!} in @file{sc2.scm}.
9154 @end deffn
9155
9156 @deffn Procedure nreverse lst
9157 @code{nreverse} reverses the order of elements in @var{lst} by mutating
9158 @code{cdr}s of the list. Sometimes called @code{reverse!}.
9159
9160 Example:
9161 @lisp
9162 (define foo '(a b c))
9163 (nreverse foo)
9164 @result{} (c b a)
9165 foo
9166 @result{} (a)
9167 @end lisp
9168
9169 Some people have been confused about how to use @code{nreverse},
9170 thinking that it doesn't return a value. It needs to be pointed out
9171 that@refill
9172 @lisp
9173 (set! lst (nreverse lst))
9174 @end lisp
9175 @noindent
9176 is the proper usage, not
9177 @lisp
9178 (nreverse lst)
9179 @end lisp
9180 The example should suffice to show why this is the case.
9181 @end deffn
9182
9183 @deffn Procedure delete elt lst
9184 @deffnx Procedure delete-if pred lst
9185 @deffnx Procedure delete-if-not pred lst
9186 Destructive versions of @code{remove} @code{remove-if}, and
9187 @code{remove-if-not}.
9188
9189 Example:
9190 @lisp
9191 (define lst '(foo bar baz bang))
9192 (delete 'foo lst)
9193 @result{} (bar baz bang)
9194 lst
9195 @result{} (foo bar baz bang)
9196
9197 (define lst '(1 2 3 4 5 6 7 8 9))
9198 (delete-if odd? lst)
9199 @result{} (2 4 6 8)
9200 lst
9201 @result{} (1 2 4 6 8)
9202 @end lisp
9203
9204 Some people have been confused about how to use @code{delete},
9205 @code{delete-if}, and @code{delete-if}, thinking that they dont' return
9206 a value. It needs to be pointed out that@refill
9207 @lisp
9208 (set! lst (delete el lst))
9209 @end lisp
9210 @noindent
9211 is the proper usage, not
9212 @lisp
9213 (delete el lst)
9214 @end lisp
9215 The examples should suffice to show why this is the case.
9216 @end deffn
9217
9218
9219
9220 @node Non-List functions, , Destructive list operations, Common List Functions
9221 @subsubsection Non-List functions
9222
9223 @defun and? . args
9224 @code{and?} checks to see if all its arguments are true. If they are,
9225 @code{and?} returns @code{#t}, otherwise, @code{#f}. (In contrast to
9226 @code{and}, this is a function, so all arguments are always evaluated
9227 and in an unspecified order.)@refill
9228
9229 Example:
9230 @lisp
9231 (and? 1 2 3)
9232 @result{} #t
9233 (and #f 1 2)
9234 @result{} #f
9235 @end lisp
9236 @end defun
9237
9238 @defun or? . args
9239 @code{or?} checks to see if any of its arguments are true. If any is
9240 true, @code{or?} returns @code{#t}, and @code{#f} otherwise. (To
9241 @code{or} as @code{and?} is to @code{and}.)@refill
9242
9243 Example:
9244 @lisp
9245 (or? 1 2 #f)
9246 @result{} #t
9247 (or? #f #f #f)
9248 @result{} #f
9249 @end lisp
9250 @end defun
9251
9252 @defun atom? object
9253 Returns @code{#t} if @var{object} is not a pair and @code{#f} if it is
9254 pair. (Called @code{atom} in Common LISP.)
9255 @lisp
9256 (atom? 1)
9257 @result{} #t
9258 (atom? '(1 2))
9259 @result{} #f
9260 (atom? #(1 2)) ; dubious!
9261 @result{} #t
9262 @end lisp
9263 @end defun
9264
9265
9266 @node Tree Operations, Type Coercion, Common List Functions, Procedures
9267 @subsection Tree operations
9268
9269 @code{(require 'tree)}
9270 @ftindex tree
9271
9272 These are operations that treat lists a representations of trees.
9273
9274 @defun subst new old tree
9275 @defunx substq new old tree
9276 @defunx substv new old tree
9277 @code{subst} makes a copy of @var{tree}, substituting @var{new} for
9278 every subtree or leaf of @var{tree} which is @code{equal?} to @var{old}
9279 and returns a modified tree. The original @var{tree} is unchanged, but
9280 may share parts with the result.
9281
9282 @code{substq} and @code{substv} are similar, but test against @var{old}
9283 using @code{eq?} and @code{eqv?} respectively.
9284
9285 Examples:
9286 @lisp
9287 (substq 'tempest 'hurricane '(shakespeare wrote (the hurricane)))
9288 @result{} (shakespeare wrote (the tempest))
9289 (substq 'foo '() '(shakespeare wrote (twelfth night)))
9290 @result{} (shakespeare wrote (twelfth night . foo) . foo)
9291 (subst '(a . cons) '(old . pair)
9292 '((old . spice) ((old . shoes) old . pair) (old . pair)))
9293 @result{} ((old . spice) ((old . shoes) a . cons) (a . cons))
9294 @end lisp
9295 @end defun
9296
9297 @defun copy-tree tree
9298 Makes a copy of the nested list structure @var{tree} using new pairs and
9299 returns it. All levels are copied, so that none of the pairs in the
9300 tree are @code{eq?} to the original ones -- only the leaves are.
9301
9302 Example:
9303 @lisp
9304 (define bar '(bar))
9305 (copy-tree (list bar 'foo))
9306 @result{} ((bar) foo)
9307 (eq? bar (car (copy-tree (list bar 'foo))))
9308 @result{} #f
9309 @end lisp
9310 @end defun
9311
9312
9313 @node Type Coercion, Chapter Ordering, Tree Operations, Procedures
9314 @subsection Type Coercion
9315 @code{(require 'coerce)}
9316 @ftindex coerce
9317
9318 @include coerce.txi
9319
9320
9321 @node Chapter Ordering, Sorting, Type Coercion, Procedures
9322 @subsection Chapter Ordering
9323
9324 @code{(require 'chapter-order)}
9325 @ftindex chapter-order
9326
9327 The @samp{chap:} functions deal with strings which are ordered like
9328 chapter numbers (or letters) in a book. Each section of the string
9329 consists of consecutive numeric or consecutive aphabetic characters of
9330 like case.
9331
9332 @defun chap:string<? string1 string2
9333 Returns #t if the first non-matching run of alphabetic upper-case or the
9334 first non-matching run of alphabetic lower-case or the first
9335 non-matching run of numeric characters of @var{string1} is
9336 @code{string<?} than the corresponding non-matching run of characters of
9337 @var{string2}.
9338
9339 @example
9340 (chap:string<? "a.9" "a.10") @result{} #t
9341 (chap:string<? "4c" "4aa") @result{} #t
9342 (chap:string<? "Revised^@{3.99@}" "Revised^@{4@}") @result{} #t
9343 @end example
9344
9345 @defunx chap:string>? string1 string2
9346 @defunx chap:string<=? string1 string2
9347 @defunx chap:string>=? string1 string2
9348 Implement the corresponding chapter-order predicates.
9349 @end defun
9350
9351 @defun chap:next-string string
9352 Returns the next string in the @emph{chapter order}. If @var{string}
9353 has no alphabetic or numeric characters,
9354 @code{(string-append @var{string} "0")} is returnd. The argument to
9355 chap:next-string will always be @code{chap:string<?} than the result.
9356
9357 @example
9358 (chap:next-string "a.9") @result{} "a.10"
9359 (chap:next-string "4c") @result{} "4d"
9360 (chap:next-string "4z") @result{} "4aa"
9361 (chap:next-string "Revised^@{4@}") @result{} "Revised^@{5@}"
9362
9363 @end example
9364 @end defun
9365
9366
9367 @node Sorting, Topological Sort, Chapter Ordering, Procedures
9368 @subsection Sorting
9369
9370 @code{(require 'sort)}
9371 @ftindex sort
9372
9373 Many Scheme systems provide some kind of sorting functions. They do
9374 not, however, always provide the @emph{same} sorting functions, and
9375 those that I have had the opportunity to test provided inefficient ones
9376 (a common blunder is to use quicksort which does not perform well).
9377
9378 Because @code{sort} and @code{sort!} are not in the standard, there is
9379 very little agreement about what these functions look like. For
9380 example, Dybvig says that Chez Scheme provides
9381 @lisp
9382 (merge predicate list1 list2)
9383 (merge! predicate list1 list2)
9384 (sort predicate list)
9385 (sort! predicate list)
9386 @end lisp
9387 @noindent
9388 while MIT Scheme 7.1, following Common LISP, offers unstable
9389 @lisp
9390 (sort list predicate)
9391 @end lisp
9392 @noindent
9393 TI PC Scheme offers
9394 @lisp
9395 (sort! list/vector predicate?)
9396 @end lisp
9397 @noindent
9398 and Elk offers
9399 @lisp
9400 (sort list/vector predicate?)
9401 (sort! list/vector predicate?)
9402 @end lisp
9403
9404 Here is a comprehensive catalogue of the variations I have found.
9405
9406 @enumerate
9407 @item
9408 Both @code{sort} and @code{sort!} may be provided.
9409 @item
9410 @code{sort} may be provided without @code{sort!}.
9411 @item
9412 @code{sort!} may be provided without @code{sort}.
9413 @item
9414 Neither may be provided.
9415 @item
9416 The sequence argument may be either a list or a vector.
9417 @item
9418 The sequence argument may only be a list.
9419 @item
9420 The sequence argument may only be a vector.
9421 @item
9422 The comparison function may be expected to behave like @code{<}.
9423 @item
9424 The comparison function may be expected to behave like @code{<=}.
9425 @item
9426 The interface may be @code{(sort predicate? sequence)}.
9427 @item
9428 The interface may be @code{(sort sequence predicate?)}.
9429 @item
9430 The interface may be @code{(sort sequence &optional (predicate? <))}.
9431 @item
9432 The sort may be stable.
9433 @item
9434 The sort may be unstable.
9435 @end enumerate
9436
9437 All of this variation really does not help anybody. A nice simple merge
9438 sort is both stable and fast (quite a lot faster than @emph{quick} sort).
9439
9440 I am providing this source code with no restrictions at all on its use
9441 (but please retain D.H.D.Warren's credit for the original idea). You
9442 may have to rename some of these functions in order to use them in a
9443 system which already provides incompatible or inferior sorts. For each
9444 of the functions, only the top-level define needs to be edited to do
9445 that.
9446
9447 I could have given these functions names which would not clash with any
9448 Scheme that I know of, but I would like to encourage implementors to
9449 converge on a single interface, and this may serve as a hint. The
9450 argument order for all functions has been chosen to be as close to
9451 Common LISP as made sense, in order to avoid NIH-itis.
9452
9453 Each of the five functions has a required @emph{last} parameter which is
9454 a comparison function. A comparison function @code{f} is a function of
9455 2 arguments which acts like @code{<}. For example,@refill
9456
9457 @lisp
9458 (not (f x x))
9459 (and (f x y) (f y z)) @equiv{} (f x z)
9460 @end lisp
9461
9462 The standard functions @code{<}, @code{>}, @code{char<?}, @code{char>?},
9463 @code{char-ci<?}, @code{char-ci>?}, @code{string<?}, @code{string>?},
9464 @code{string-ci<?}, and @code{string-ci>?} are suitable for use as
9465 comparison functions. Think of @code{(less? x y)} as saying when
9466 @code{x} must @emph{not} precede @code{y}.
9467
9468 @defun sorted? sequence less?
9469 Returns @code{#t} when the sequence argument is in non-decreasing order
9470 according to @var{less?} (that is, there is no adjacent pair @code{@dots{} x
9471 y @dots{}} for which @code{(less? y x)}).
9472
9473 Returns @code{#f} when the sequence contains at least one out-of-order
9474 pair. It is an error if the sequence is neither a list nor a vector.
9475 @end defun
9476
9477 @defun merge list1 list2 less?
9478 This merges two lists, producing a completely new list as result. I
9479 gave serious consideration to producing a Common-LISP-compatible
9480 version. However, Common LISP's @code{sort} is our @code{sort!} (well,
9481 in fact Common LISP's @code{stable-sort} is our @code{sort!}, merge sort
9482 is @emph{fast} as well as stable!) so adapting CL code to Scheme takes a
9483 bit of work anyway. I did, however, appeal to CL to determine the
9484 @emph{order} of the arguments.
9485 @end defun
9486
9487 @deffn Procedure merge! list1 list2 less?
9488 Merges two lists, re-using the pairs of @var{list1} and @var{list2} to
9489 build the result. If the code is compiled, and @var{less?} constructs
9490 no new pairs, no pairs at all will be allocated. The first pair of the
9491 result will be either the first pair of @var{list1} or the first pair of
9492 @var{list2}, but you can't predict which.
9493
9494 The code of @code{merge} and @code{merge!} could have been quite a bit
9495 simpler, but they have been coded to reduce the amount of work done per
9496 iteration. (For example, we only have one @code{null?} test per
9497 iteration.)@refill
9498 @end deffn
9499
9500 @defun sort sequence less?
9501 Accepts either a list or a vector, and returns a new sequence which is
9502 sorted. The new sequence is the same type as the input. Always
9503 @code{(sorted? (sort sequence less?) less?)}. The original sequence is
9504 not altered in any way. The new sequence shares its @emph{elements}
9505 with the old one; no elements are copied.
9506 @end defun
9507
9508 @deffn Procedure sort! sequence less?
9509 Returns its sorted result in the original boxes. If the original
9510 sequence is a list, no new storage is allocated at all. If the original
9511 sequence is a vector, the sorted elements are put back in the same
9512 vector.
9513
9514 Some people have been confused about how to use @code{sort!}, thinking
9515 that it doesn't return a value. It needs to be pointed out that
9516 @lisp
9517 (set! slist (sort! slist <))
9518 @end lisp
9519 @noindent
9520 is the proper usage, not
9521 @lisp
9522 (sort! slist <)
9523 @end lisp
9524 @end deffn
9525
9526 Note that these functions do @emph{not} accept a CL-style @samp{:key}
9527 argument. A simple device for obtaining the same expressiveness is to
9528 define@refill
9529 @lisp
9530 (define (keyed less? key)
9531 (lambda (x y) (less? (key x) (key y))))
9532 @end lisp
9533 @noindent
9534 and then, when you would have written
9535 @lisp
9536 (sort a-sequence #'my-less :key #'my-key)
9537 @end lisp
9538 @noindent
9539 in Common LISP, just write
9540 @lisp
9541 (sort! a-sequence (keyed my-less? my-key))
9542 @end lisp
9543 @noindent
9544 in Scheme.
9545
9546 @node Topological Sort, String-Case, Sorting, Procedures
9547 @subsection Topological Sort
9548
9549 @code{(require 'topological-sort)} or @code{(require 'tsort)}
9550 @ftindex topological-sort
9551 @ftindex tsort
9552
9553 @noindent
9554 The algorithm is inspired by Cormen, Leiserson and Rivest (1990)
9555 @cite{Introduction to Algorithms}, chapter 23.
9556
9557 @defun tsort dag pred
9558 @defunx topological-sort dag pred
9559 where
9560 @table @var
9561 @item dag
9562 is a list of sublists. The car of each sublist is a vertex. The cdr is
9563 the adjacency list of that vertex, i.e. a list of all vertices to which
9564 there exists an edge from the car vertex.
9565 @item pred
9566 is one of @code{eq?}, @code{eqv?}, @code{equal?}, @code{=},
9567 @code{char=?}, @code{char-ci=?}, @code{string=?}, or @code{string-ci=?}.
9568 @end table
9569
9570 Sort the directed acyclic graph @var{dag} so that for every edge from
9571 vertex @var{u} to @var{v}, @var{u} will come before @var{v} in the
9572 resulting list of vertices.
9573
9574 Time complexity: O (|V| + |E|)
9575
9576 Example (from Cormen):
9577 @quotation
9578 Prof. Bumstead topologically sorts his clothing when getting
9579 dressed. The first argument to `tsort' describes which
9580 garments he needs to put on before others. (For example,
9581 Prof Bumstead needs to put on his shirt before he puts on his
9582 tie or his belt.) `tsort' gives the correct order of dressing:
9583 @end quotation
9584
9585 @example
9586 (require 'tsort)
9587 @ftindex tsort
9588 (tsort '((shirt tie belt)
9589 (tie jacket)
9590 (belt jacket)
9591 (watch)
9592 (pants shoes belt)
9593 (undershorts pants shoes)
9594 (socks shoes))
9595 eq?)
9596 @result{}
9597 (socks undershorts pants shoes watch shirt belt tie jacket)
9598 @end example
9599 @end defun
9600
9601
9602
9603 @node String-Case, String Ports, Topological Sort, Procedures
9604 @subsection String-Case
9605
9606 @code{(require 'string-case)}
9607 @ftindex string-case
9608
9609 @deffn Procedure string-upcase str
9610 @deffnx Procedure string-downcase str
9611 @deffnx Procedure string-capitalize str
9612 The obvious string conversion routines. These are non-destructive.
9613 @end deffn
9614
9615 @defun string-upcase! str
9616 @defunx string-downcase! str
9617 @defunx string-captialize! str
9618 The destructive versions of the functions above.
9619 @end defun
9620
9621 @defun string-ci->symbol str
9622 Converts string @var{str} to a symbol having the same case as if the
9623 symbol had been @code{read}.
9624 @end defun
9625
9626 @defun symbol-append obj1 @dots{}
9627 Converts @var{obj1} @dots{} to strings, appends them, and converts to a
9628 symbol which is returned. Strings and numbers are converted to read's
9629 symbol case; the case of symbol characters is not changed. #f is
9630 converted to the empty string (symbol).
9631 @end defun
9632
9633
9634
9635 @node String Ports, String Search, String-Case, Procedures
9636 @subsection String Ports
9637
9638 @code{(require 'string-port)}
9639 @ftindex string-port
9640
9641 @deffn Procedure call-with-output-string proc
9642 @var{proc} must be a procedure of one argument. This procedure calls
9643 @var{proc} with one argument: a (newly created) output port. When the
9644 function returns, the string composed of the characters written into the
9645 port is returned.
9646 @end deffn
9647
9648 @deffn Procedure call-with-input-string string proc
9649 @var{proc} must be a procedure of one argument. This procedure calls
9650 @var{proc} with one argument: an (newly created) input port from which
9651 @var{string}'s contents may be read. When @var{proc} returns, the port
9652 is closed and the value yielded by the procedure @var{proc} is
9653 returned.
9654 @end deffn
9655
9656
9657 @node String Search, Line I/O, String Ports, Procedures
9658 @subsection String Search
9659
9660 @code{(require 'string-search)}
9661 @ftindex string-search
9662
9663 @deffn Procedure string-index string char
9664 @deffnx Procedure string-index-ci string char
9665 Returns the index of the first occurence of @var{char} within
9666 @var{string}, or @code{#f} if the @var{string} does not contain a
9667 character @var{char}.
9668 @end deffn
9669
9670 @deffn Procedure string-reverse-index string char
9671 @deffnx Procedure string-reverse-index-ci string char
9672 Returns the index of the last occurence of @var{char} within
9673 @var{string}, or @code{#f} if the @var{string} does not contain a
9674 character @var{char}.
9675 @end deffn
9676
9677 @deffn procedure substring? pattern string
9678 @deffnx procedure substring-ci? pattern string
9679 Searches @var{string} to see if some substring of @var{string} is equal
9680 to @var{pattern}. @code{substring?} returns the index of the first
9681 character of the first substring of @var{string} that is equal to
9682 @var{pattern}; or @code{#f} if @var{string} does not contain
9683 @var{pattern}.
9684
9685 @example
9686 (substring? "rat" "pirate") @result{} 2
9687 (substring? "rat" "outrage") @result{} #f
9688 (substring? "" any-string) @result{} 0
9689 @end example
9690 @end deffn
9691
9692 @deffn Procedure find-string-from-port? str in-port max-no-chars
9693 Looks for a string @var{str} within the first @var{max-no-chars} chars
9694 of the input port @var{in-port}.
9695
9696 @deffnx Procedure find-string-from-port? str in-port
9697 When called with two arguments, the search span is limited by the end of
9698 the input stream.
9699
9700 @deffnx Procedure find-string-from-port? str in-port char
9701 Searches up to the first occurrence of character @var{char} in
9702 @var{str}.
9703
9704 @deffnx Procedure find-string-from-port? str in-port proc
9705 Searches up to the first occurrence of the procedure @var{proc}
9706 returning non-false when called with a character (from @var{in-port})
9707 argument.
9708
9709 When the @var{str} is found, @code{find-string-from-port?} returns the
9710 number of characters it has read from the port, and the port is set to
9711 read the first char after that (that is, after the @var{str}) The
9712 function returns @code{#f} when the @var{str} isn't found.
9713
9714 @code{find-string-from-port?} reads the port @emph{strictly}
9715 sequentially, and does not perform any buffering. So
9716 @code{find-string-from-port?} can be used even if the @var{in-port} is
9717 open to a pipe or other communication channel.
9718 @end deffn
9719
9720 @defun string-subst txt old1 new1 @dots{}
9721 Returns a copy of string @var{txt} with all occurrences of string
9722 @var{old1} in @var{txt} replaced with @var{new1}, @var{old2} replaced
9723 with @var{new2} @dots{}.
9724 @end defun
9725
9726 @node Line I/O, Multi-Processing, String Search, Procedures
9727 @subsection Line I/O
9728
9729 @code{(require 'line-i/o)}
9730 @ftindex line-i
9731
9732 @include lineio.txi
9733
9734
9735 @node Multi-Processing, Metric Units, Line I/O, Procedures
9736 @subsection Multi-Processing
9737
9738 @code{(require 'process)}
9739 @ftindex process
9740
9741 This module implements asynchronous (non-polled) time-sliced
9742 multi-processing in the SCM Scheme implementation using procedures
9743 @code{alarm} and @code{alarm-interrupt}.
9744 @findex alarm
9745 @findex alarm-interrupt
9746 Until this is ported to another implementation, consider it an example
9747 of writing schedulers in Scheme.
9748
9749 @deffn Procedure add-process! proc
9750 Adds proc, which must be a procedure (or continuation) capable of
9751 accepting accepting one argument, to the @code{process:queue}. The
9752 value returned is unspecified. The argument to @var{proc} should be
9753 ignored. If @var{proc} returns, the process is killed.
9754 @end deffn
9755
9756 @deffn Procedure process:schedule!
9757 Saves the current process on @code{process:queue} and runs the next
9758 process from @code{process:queue}. The value returned is
9759 unspecified.
9760 @end deffn
9761
9762 @deffn Procedure kill-process!
9763 Kills the current process and runs the next process from
9764 @code{process:queue}. If there are no more processes on
9765 @code{process:queue}, @code{(slib:exit)} is called (@pxref{System}).
9766 @end deffn
9767
9768
9769 @node Metric Units, , Multi-Processing, Procedures
9770 @subsection Metric Units
9771
9772 @code{(require 'metric-units)}
9773 @ftindex metric-units
9774
9775 @url{http://swissnet.ai.mit.edu/~jaffer/MIXF.html}
9776
9777 @dfn{Metric Interchange Format} is a character string encoding for
9778 numerical values and units which:
9779
9780 @itemize @bullet
9781 @item
9782 is unambiguous in all locales;
9783
9784 @item
9785 uses only [TOG] "Portable Character Set" characters matching "Basic
9786 Latin" characters in Plane 0 of the Universal Character Set [UCS];
9787
9788 @item
9789 is transparent to [UTF-7] and [UTF-8] UCS transformation formats;
9790
9791 @item
9792 is human readable and writable;
9793
9794 @item
9795 is machine readable and writable;
9796
9797 @item
9798 incorporates SI prefixes and units;
9799
9800 @item
9801 incorporates [ISO 6093] numbers; and
9802
9803 @item
9804 incorporates [IEC 60027-2] binary prefixes.
9805 @end itemize
9806
9807 In the expression for the value of a quantity, the unit symbol is placed
9808 after the numerical value. A dot (PERIOD, @samp{.}) is placed between
9809 the numerical value and the unit symbol.
9810
9811 Within a compound unit, each of the base and derived symbols can
9812 optionally have an attached SI prefix.
9813
9814 Unit symbols formed from other unit symbols by multiplication are
9815 indicated by means of a dot (PERIOD, @samp{.}) placed between them.
9816
9817 Unit symbols formed from other unit symbols by division are indicated by
9818 means of a SOLIDUS (@samp{/}) or negative exponents. The SOLIDUS must
9819 not be repeated in the same compound unit unless contained within a
9820 parenthesized subexpression.
9821
9822 The grouping formed by a prefix symbol attached to a unit symbol
9823 constitutes a new inseparable symbol (forming a multiple or submultiple
9824 of the unit concerned) which can be raised to a positive or negative
9825 power and which can be combined with other unit symbols to form compound
9826 unit symbols.
9827
9828 The grouping formed by surrounding compound unit symbols with
9829 parentheses (@samp{(} and @samp{)}) constitutes a new inseparable symbol
9830 which can be raised to a positive or negative power and which can be
9831 combined with other unit symbols to form compound unit symbols.
9832
9833 Compound prefix symbols, that is, prefix symbols formed by the
9834 juxtaposition of two or more prefix symbols, are not permitted.
9835
9836 Prefix symbols are not used with the time-related unit symbols min
9837 (minute), h (hour), d (day). No prefix symbol may be used with dB
9838 (decibel). Only submultiple prefix symbols may be used with the unit
9839 symbols L (liter), Np (neper), o (degree), oC (degree Celsius), rad
9840 (radian), and sr (steradian). Submultiple prefix symbols may not be
9841 used with the unit symbols t (metric ton), r (revolution), or Bd (baud).
9842
9843 A unit exponent follows the unit, separated by a CIRCUMFLEX (@samp{^}).
9844 Exponents may be positive or negative. Fractional exponents must be
9845 parenthesized.
9846
9847 @subsubheading SI Prefixes
9848 @example
9849 Factor Name Symbol | Factor Name Symbol
9850 ====== ==== ====== | ====== ==== ======
9851 1e24 yotta Y | 1e-1 deci d
9852 1e21 zetta Z | 1e-2 centi c
9853 1e18 exa E | 1e-3 milli m
9854 1e15 peta P | 1e-6 micro u
9855 1e12 tera T | 1e-9 nano n
9856 1e9 giga G | 1e-12 pico p
9857 1e6 mega M | 1e-15 femto f
9858 1e3 kilo k | 1e-18 atto a
9859 1e2 hecto h | 1e-21 zepto z
9860 1e1 deka da | 1e-24 yocto y
9861 @end example
9862
9863 @subsubheading Binary Prefixes
9864
9865 These binary prefixes are valid only with the units B (byte) and bit.
9866 However, decimal prefixes can also be used with bit; and decimal
9867 multiple (not submultiple) prefixes can also be used with B (byte).
9868
9869 @example
9870 Factor (power-of-2) Name Symbol
9871 ====== ============ ==== ======
9872 1.152921504606846976e18 (2^60) exbi Ei
9873 1.125899906842624e15 (2^50) pebi Pi
9874 1.099511627776e12 (2^40) tebi Ti
9875 1.073741824e9 (2^30) gibi Gi
9876 1.048576e6 (2^20) mebi Mi
9877 1.024e3 (2^10) kibi Ki
9878 @end example
9879
9880 @subsubheading Unit Symbols
9881
9882 @example
9883 Type of Quantity Name Symbol Equivalent
9884 ================ ==== ====== ==========
9885 time second s
9886 time minute min = 60.s
9887 time hour h = 60.min
9888 time day d = 24.h
9889 frequency hertz Hz s^-1
9890 signaling rate baud Bd s^-1
9891 length meter m
9892 volume liter L dm^3
9893 plane angle radian rad
9894 solid angle steradian sr rad^2
9895 plane angle revolution * r = 6.283185307179586.rad
9896 plane angle degree * o = 2.777777777777778e-3.r
9897 information capacity bit bit
9898 information capacity byte, octet B = 8.bit
9899 mass gram g
9900 mass ton t Mg
9901 mass unified atomic mass unit u = 1.66053873e-27.kg
9902 amount of substance mole mol
9903 catalytic activity katal kat mol/s
9904 thermodynamic temperature kelvin K
9905 centigrade temperature degree Celsius oC
9906 luminous intensity candela cd
9907 luminous flux lumen lm cd.sr
9908 illuminance lux lx lm/m^2
9909 force newton N m.kg.s^-2
9910 pressure, stress pascal Pa N/m^2
9911 energy, work, heat joule J N.m
9912 energy electronvolt eV = 1.602176462e-19.J
9913 power, radiant flux watt W J/s
9914 logarithm of power ratio neper Np
9915 logarithm of power ratio decibel * dB = 0.1151293.Np
9916 electric current ampere A
9917 electric charge coulomb C s.A
9918 electric potential, EMF volt V W/A
9919 capacitance farad F C/V
9920 electric resistance ohm Ohm V/A
9921 electric conductance siemens S A/V
9922 magnetic flux weber Wb V.s
9923 magnetic flux density tesla T Wb/m^2
9924 inductance henry H Wb/A
9925 radionuclide activity becquerel Bq s^-1
9926 absorbed dose energy gray Gy m^2.s^-2
9927 dose equivalent sievert Sv m^2.s^-2
9928 @end example
9929
9930 * The formulas are:
9931
9932 @itemize @bullet
9933 @item
9934 r/rad = 8 * atan(1)
9935 @item
9936 o/r = 1 / 360
9937 @item
9938 db/Np = ln(10) / 20
9939 @end itemize
9940
9941 @defun si:conversion-factor to-unit from-unit
9942 If the strings @var{from-unit} and @var{to-unit} express valid unit
9943 expressions for quantities of the same unit-dimensions, then the value
9944 returned by @code{si:conversion-factor} will be such that multiplying a
9945 numerical value expressed in @var{from-unit}s by the returned conversion
9946 factor yields the numerical value expressed in @var{to-unit}s.
9947
9948 Otherwise, @code{si:conversion-factor} returns:
9949
9950 @table @asis
9951 @item -3
9952 if neither @var{from-unit} nor @var{to-unit} is a syntactically valid
9953 unit.
9954 @item -2
9955 if @var{from-unit} is not a syntactically valid unit.
9956 @item -1
9957 if @var{to-unit} is not a syntactically valid unit.
9958 @item 0
9959 if linear conversion (by a factor) is not possible.
9960 @end table
9961
9962 @end defun
9963
9964 @example
9965 (si:conversion-factor "km/s" "m/s" ) @result{} 0.001
9966 (si:conversion-factor "N" "m/s" ) @result{} 0
9967 (si:conversion-factor "moC" "oC" ) @result{} 1000
9968 (si:conversion-factor "mK" "oC" ) @result{} 0
9969 (si:conversion-factor "rad" "o" ) @result{} 0.0174533
9970 (si:conversion-factor "K" "o" ) @result{} 0
9971 (si:conversion-factor "K" "K" ) @result{} 1
9972 (si:conversion-factor "oK" "oK" ) @result{} -3
9973 (si:conversion-factor "" "s/s" ) @result{} 1
9974 (si:conversion-factor "km/h" "mph" ) @result{} -2
9975 @end example
9976
9977
9978 @node Standards Support, Session Support, Procedures, Other Packages
9979 @section Standards Support
9980
9981
9982
9983 @menu
9984 * With-File:: 'with-file
9985 * Transcripts:: 'transcript
9986 * Rev2 Procedures:: 'rev2-procedures
9987 * Rev4 Optional Procedures:: 'rev4-optional-procedures
9988 * Multi-argument / and -:: 'multiarg/and-
9989 * Multi-argument Apply:: 'multiarg-apply
9990 * Rationalize:: 'rationalize
9991 * Promises:: 'promise
9992 * Dynamic-Wind:: 'dynamic-wind
9993 * Eval:: 'eval
9994 * Values:: 'values
9995 @end menu
9996
9997 @node With-File, Transcripts, Standards Support, Standards Support
9998 @subsection With-File
9999
10000 @code{(require 'with-file)}
10001 @ftindex with-file
10002
10003 @defun with-input-from-file file thunk
10004 @defunx with-output-to-file file thunk
10005 Description found in R4RS.
10006 @end defun
10007
10008 @node Transcripts, Rev2 Procedures, With-File, Standards Support
10009 @subsection Transcripts
10010
10011 @code{(require 'transcript)}
10012 @ftindex transcript
10013
10014 @defun transcript-on filename
10015 @defunx transcript-off filename
10016 Redefines @code{read-char}, @code{read}, @code{write-char},
10017 @code{write}, @code{display}, and @code{newline}.
10018 @end defun
10019
10020
10021
10022
10023
10024 @node Rev2 Procedures, Rev4 Optional Procedures, Transcripts, Standards Support
10025 @subsection Rev2 Procedures
10026
10027 @code{(require 'rev2-procedures)}
10028 @ftindex rev2-procedures
10029
10030 The procedures below were specified in the @cite{Revised^2 Report on
10031 Scheme}. @strong{N.B.}: The symbols @code{1+} and @code{-1+} are not
10032 @cite{R4RS} syntax. Scheme->C, for instance, barfs on this
10033 module.
10034
10035 @deffn Procedure substring-move-left! string1 start1 end1 string2 start2
10036 @deffnx Procedure substring-move-right! string1 start1 end1 string2 start2
10037 @var{string1} and @var{string2} must be a strings, and @var{start1},
10038 @var{start2} and @var{end1} must be exact integers satisfying@refill
10039
10040 @display
10041 0 <= @var{start1} <= @var{end1} <= (string-length @var{string1})
10042 0 <= @var{start2} <= @var{end1} - @var{start1} + @var{start2} <= (string-length @var{string2})
10043 @end display
10044
10045 @code{substring-move-left!} and @code{substring-move-right!} store
10046 characters of @var{string1} beginning with index @var{start1}
10047 (inclusive) and ending with index @var{end1} (exclusive) into
10048 @var{string2} beginning with index @var{start2} (inclusive).
10049
10050 @code{substring-move-left!} stores characters in time order of
10051 increasing indices. @code{substring-move-right!} stores characters in
10052 time order of increasing indeces.
10053 @end deffn
10054
10055 @deffn Procedure substring-fill! string start end char
10056 Fills the elements @var{start}--@var{end} of @var{string} with the
10057 character @var{char}.
10058 @end deffn
10059
10060 @defun string-null? str
10061 @equiv{} @code{(= 0 (string-length @var{str}))}
10062 @end defun
10063
10064 @deffn Procedure append! . pairs
10065 Destructively appends its arguments. Equivalent to @code{nconc}.
10066 @end deffn
10067
10068 @defun 1+ n
10069 Adds 1 to @var{n}.
10070 @end defun
10071
10072 @defun -1+ n
10073 Subtracts 1 from @var{n}.
10074 @end defun
10075
10076 @defun <?
10077 @defunx <=?
10078 @defunx =?
10079 @defunx >?
10080 @defunx >=?
10081 These are equivalent to the procedures of the same name but without the
10082 trailing @samp{?}.
10083 @end defun
10084
10085
10086
10087 @node Rev4 Optional Procedures, Multi-argument / and -, Rev2 Procedures, Standards Support
10088 @subsection Rev4 Optional Procedures
10089
10090 @code{(require 'rev4-optional-procedures)}
10091 @ftindex rev4-optional-procedures
10092
10093 For the specification of these optional procedures,
10094 @xref{Standard procedures, , ,r4rs, Revised(4) Scheme}.
10095
10096 @defun list-tail l p
10097 @end defun
10098
10099 @defun string->list s
10100 @end defun
10101
10102 @defun list->string l
10103 @end defun
10104
10105 @defun string-copy
10106 @end defun
10107
10108 @deffn Procedure string-fill! s obj
10109 @end deffn
10110
10111 @defun list->vector l
10112 @end defun
10113
10114 @defun vector->list s
10115 @end defun
10116
10117 @deffn Procedure vector-fill! s obj
10118 @end deffn
10119
10120
10121
10122
10123
10124 @node Multi-argument / and -, Multi-argument Apply, Rev4 Optional Procedures, Standards Support
10125 @subsection Multi-argument / and -
10126
10127 @code{(require 'mutliarg/and-)}
10128 @ftindex mutliarg
10129
10130 For the specification of these optional forms, @xref{Numerical
10131 operations, , ,r4rs, Revised(4) Scheme}. The @code{two-arg:}* forms are
10132 only defined if the implementation does not support the many-argument
10133 forms.
10134
10135 @defun two-arg:/ n1 n2
10136 The original two-argument version of @code{/}.
10137 @end defun
10138
10139 @defun / divident . divisors
10140 @end defun
10141
10142 @defun two-arg:- n1 n2
10143 The original two-argument version of @code{-}.
10144 @end defun
10145
10146 @defun - minuend . subtrahends
10147 @end defun
10148
10149
10150
10151
10152
10153 @node Multi-argument Apply, Rationalize, Multi-argument / and -, Standards Support
10154 @subsection Multi-argument Apply
10155
10156 @code{(require 'multiarg-apply)}
10157 @ftindex multiarg-apply
10158
10159 @noindent
10160 For the specification of this optional form,
10161 @xref{Control features, , ,r4rs, Revised(4) Scheme}.
10162
10163 @defun two-arg:apply proc l
10164 The implementation's native @code{apply}. Only defined for
10165 implementations which don't support the many-argument version.
10166 @end defun
10167
10168 @defun apply proc . args
10169 @end defun
10170
10171
10172
10173
10174
10175 @node Rationalize, Promises, Multi-argument Apply, Standards Support
10176 @subsection Rationalize
10177
10178 @code{(require 'rationalize)}
10179 @ftindex rationalize
10180
10181 The procedure @dfn{rationalize} is interesting because most programming
10182 languages do not provide anything analogous to it. Thanks to Alan
10183 Bawden for contributing this algorithm.
10184
10185 @defun rationalize x y
10186 Computes the correct result for exact arguments (provided the
10187 implementation supports exact rational numbers of unlimited precision);
10188 and produces a reasonable answer for inexact arguments when inexact
10189 arithmetic is implemented using floating-point.
10190 @end defun
10191
10192 @code{Rationalize} has limited use in implementations lacking exact
10193 (non-integer) rational numbers. The following procedures return a list
10194 of the numerator and denominator.
10195
10196 @defun find-ratio x y
10197 @code{find-ratio} returns the list of the @emph{simplest}
10198 numerator and denominator whose quotient differs from @var{x} by no more
10199 than @var{y}.
10200
10201 @format
10202 @t{(find-ratio 3/97 .0001) @result{} (3 97)
10203 (find-ratio 3/97 .001) @result{} (1 32)
10204 }
10205 @end format
10206 @end defun
10207
10208 @defun find-ratio-between x y
10209 @code{find-ratio-between} returns the list of the @emph{simplest}
10210 numerator and denominator between @var{x} and @var{y}.
10211
10212 @format
10213 @t{(find-ratio-between 2/7 3/5) @result{} (1 2)
10214 (find-ratio-between -3/5 -2/7) @result{} (-1 2)
10215 }
10216 @end format
10217 @end defun
10218
10219
10220 @node Promises, Dynamic-Wind, Rationalize, Standards Support
10221 @subsection Promises
10222
10223 @code{(require 'promise)}
10224 @ftindex promise
10225
10226 @defun make-promise proc
10227 @end defun
10228
10229 Change occurrences of @code{(delay @var{expression})} to
10230 @code{(make-promise (lambda () @var{expression}))} and @code{(define
10231 force promise:force)} to implement promises if your implementation
10232 doesn't support them
10233 (@pxref{Control features, , ,r4rs, Revised(4) Scheme}).
10234
10235
10236
10237
10238 @node Dynamic-Wind, Eval, Promises, Standards Support
10239 @subsection Dynamic-Wind
10240
10241 @code{(require 'dynamic-wind)}
10242 @ftindex dynamic-wind
10243
10244 This facility is a generalization of Common LISP @code{unwind-protect},
10245 designed to take into account the fact that continuations produced by
10246 @code{call-with-current-continuation} may be reentered.
10247
10248 @deffn Procedure dynamic-wind thunk1 thunk2 thunk3
10249 The arguments @var{thunk1}, @var{thunk2}, and @var{thunk3} must all be
10250 procedures of no arguments (thunks).
10251
10252 @code{dynamic-wind} calls @var{thunk1}, @var{thunk2}, and then
10253 @var{thunk3}. The value returned by @var{thunk2} is returned as the
10254 result of @code{dynamic-wind}. @var{thunk3} is also called just before
10255 control leaves the dynamic context of @var{thunk2} by calling a
10256 continuation created outside that context. Furthermore, @var{thunk1} is
10257 called before reentering the dynamic context of @var{thunk2} by calling
10258 a continuation created inside that context. (Control is inside the
10259 context of @var{thunk2} if @var{thunk2} is on the current return stack).
10260
10261 @strong{Warning:} There is no provision for dealing with errors or
10262 interrupts. If an error or interrupt occurs while using
10263 @code{dynamic-wind}, the dynamic environment will be that in effect at
10264 the time of the error or interrupt.
10265 @end deffn
10266
10267
10268 @node Eval, Values, Dynamic-Wind, Standards Support
10269 @subsection Eval
10270
10271 @code{(require 'eval)}
10272
10273 @defun eval expression environment-specifier
10274
10275 Evaluates @var{expression} in the specified environment and returns its
10276 value. @var{Expression} must be a valid Scheme expression represented
10277 as data, and @var{environment-specifier} must be a value returned by one
10278 of the three procedures described below. Implementations may extend
10279 @code{eval} to allow non-expression programs (definitions) as the first
10280 argument and to allow other values as environments, with the restriction
10281 that @code{eval} is not allowed to create new bindings in the
10282 environments associated with @code{null-environment} or
10283 @code{scheme-report-environment}.
10284
10285 @lisp
10286 (eval '(* 7 3) (scheme-report-environment 5))
10287 @result{} 21
10288
10289 (let ((f (eval '(lambda (f x) (f x x))
10290 (null-environment))))
10291 (f + 10))
10292 @result{} 20
10293 @end lisp
10294 @end defun
10295
10296 @defun scheme-report-environment version
10297 @defunx null-environment version
10298 @defunx null-environment
10299
10300 @var{Version} must be an exact non-negative integer @var{n}
10301 corresponding to a version of one of the Revised^@var{n} Reports on
10302 Scheme. @code{Scheme-report-environment} returns a specifier for an
10303 environment that contains the set of bindings specified in the
10304 corresponding report that the implementation supports.
10305 @code{Null-environment} returns a specifier for an environment that
10306 contains only the (syntactic) bindings for all the syntactic keywords
10307 defined in the given version of the report.
10308
10309 Not all versions may be available in all implementations at all times.
10310 However, an implementation that conforms to version @var{n} of the
10311 Revised^@var{n} Reports on Scheme must accept version @var{n}. An error
10312 is signalled if the specified version is not available.
10313
10314 The effect of assigning (through the use of @code{eval}) a variable
10315 bound in a @code{scheme-report-environment} (for example @code{car}) is
10316 unspecified. Thus the environments specified by
10317 @code{scheme-report-environment} may be immutable.
10318
10319 @end defun
10320
10321 @defun interaction-environment
10322
10323 This optional procedure returns a specifier for the environment that
10324 contains implementation-defined bindings, typically a superset of those
10325 listed in the report. The intent is that this procedure will return the
10326 environment in which the implementation would evaluate expressions
10327 dynamically typed by the user.
10328 @end defun
10329
10330 @noindent
10331 Here are some more @code{eval} examples:
10332
10333 @example
10334 (require 'eval)
10335 @result{} #<unspecified>
10336 (define car 'volvo)
10337 @result{} #<unspecified>
10338 car
10339 @result{} volvo
10340 (eval 'car (interaction-environment))
10341 @result{} volvo
10342 (eval 'car (scheme-report-environment 5))
10343 @result{} #<primitive-procedure car>
10344 (eval '(eval 'car (interaction-environment))
10345 (scheme-report-environment 5))
10346 @result{} volvo
10347 (eval '(eval '(set! car 'buick) (interaction-environment))
10348 (scheme-report-environment 5))
10349 @result{} #<unspecified>
10350 car
10351 @result{} buick
10352 (eval 'car (scheme-report-environment 5))
10353 @result{} #<primitive-procedure car>
10354 (eval '(eval 'car (interaction-environment))
10355 (scheme-report-environment 5))
10356 @result{} buick
10357 @end example
10358
10359
10360 @node Values, , Eval, Standards Support
10361 @subsection Values
10362
10363 @code{(require 'values)}
10364 @ftindex values
10365
10366 @defun values obj @dots{}
10367 @code{values} takes any number of arguments, and passes (returns) them
10368 to its continuation.
10369 @end defun
10370
10371
10372 @defun call-with-values thunk proc
10373 @var{thunk} must be a procedure of no arguments, and @var{proc} must be
10374 a procedure. @code{call-with-values} calls @var{thunk} with a
10375 continuation that, when passed some values, calls @var{proc} with those
10376 values as arguments.
10377
10378 Except for continuations created by the @code{call-with-values}
10379 procedure, all continuations take exactly one value, as now; the effect
10380 of passing no value or more than one value to continuations that were
10381 not created by the @code{call-with-values} procedure is
10382 unspecified.
10383 @end defun
10384
10385
10386 @node Session Support, Extra-SLIB Packages, Standards Support, Other Packages
10387 @section Session Support
10388
10389 @menu
10390 * Repl:: Macros at top-level
10391 * Quick Print:: Loop-safe Output
10392 * Debug:: To err is human ...
10393 * Breakpoints:: Pause execution
10394 * Trace:: 'trace
10395 * System Interface:: 'system, 'getenv, and 'net-clients
10396 @end menu
10397
10398
10399 @node Repl, Quick Print, Session Support, Session Support
10400 @subsection Repl
10401
10402 @code{(require 'repl)}
10403 @ftindex repl
10404
10405 Here is a read-eval-print-loop which, given an eval, evaluates forms.
10406
10407 @deffn Procedure repl:top-level repl:eval
10408 @code{read}s, @code{repl:eval}s and @code{write}s expressions from
10409 @code{(current-input-port)} to @code{(current-output-port)} until an
10410 end-of-file is encountered. @code{load}, @code{slib:eval},
10411 @code{slib:error}, and @code{repl:quit} dynamically bound during
10412 @code{repl:top-level}.
10413 @end deffn
10414
10415 @deffn Procedure repl:quit
10416 Exits from the invocation of @code{repl:top-level}.
10417 @end deffn
10418
10419 The @code{repl:} procedures establish, as much as is possible to do
10420 portably, a top level environment supporting macros.
10421 @code{repl:top-level} uses @code{dynamic-wind} to catch error conditions
10422 and interrupts. If your implementation supports this you are all set.
10423
10424 Otherwise, if there is some way your implementation can catch error
10425 conditions and interrupts, then have them call @code{slib:error}. It
10426 will display its arguments and reenter @code{repl:top-level}.
10427 @code{slib:error} dynamically bound by @code{repl:top-level}.
10428
10429 To have your top level loop always use macros, add any interrupt
10430 catching lines and the following lines to your Scheme init file:
10431 @lisp
10432 (require 'macro)
10433 @ftindex macro
10434 (require 'repl)
10435 @ftindex repl
10436 (repl:top-level macro:eval)
10437 @end lisp
10438
10439 @node Quick Print, Debug, Repl, Session Support
10440 @subsection Quick Print
10441
10442 @code{(require 'qp)}
10443 @ftindex qp
10444
10445 @noindent
10446 When displaying error messages and warnings, it is paramount that the
10447 output generated for circular lists and large data structures be
10448 limited. This section supplies a procedure to do this. It could be
10449 much improved.
10450
10451 @quotation
10452 Notice that the neccessity for truncating output eliminates
10453 Common-Lisp's @ref{Format} from consideration; even when variables
10454 @code{*print-level*} and @code{*print-level*} are set, huge strings and
10455 bit-vectors are @emph{not} limited.
10456 @end quotation
10457
10458 @deffn Procedure qp arg1 @dots{}
10459 @deffnx Procedure qpn arg1 @dots{}
10460 @deffnx Procedure qpr arg1 @dots{}
10461 @code{qp} writes its arguments, separated by spaces, to
10462 @code{(current-output-port)}. @code{qp} compresses printing by
10463 substituting @samp{...} for substructure it does not have sufficient
10464 room to print. @code{qpn} is like @code{qp} but outputs a newline
10465 before returning. @code{qpr} is like @code{qpn} except that it returns
10466 its last argument.
10467 @end deffn
10468
10469 @defvar *qp-width*
10470 @code{*qp-width*} is the largest number of characters that @code{qp}
10471 should use.
10472 @end defvar
10473
10474 @node Debug, Breakpoints, Quick Print, Session Support
10475 @subsection Debug
10476
10477 @code{(require 'debug)}
10478 @ftindex debug
10479
10480 @noindent
10481 Requiring @code{debug} automatically requires @code{trace} and
10482 @code{break}.
10483
10484 @noindent
10485 An application with its own datatypes may want to substitute its own
10486 printer for @code{qp}. This example shows how to do this:
10487
10488 @example
10489 (define qpn (lambda args) @dots{})
10490 (provide 'qp)
10491 (require 'debug)
10492 @ftindex debug
10493 @end example
10494
10495 @deffn Procedure trace-all file @dots{}
10496 Traces (@pxref{Trace}) all procedures @code{define}d at top-level in
10497 @file{file} @dots{}.
10498 @deffnx Procedure track-all file @dots{}
10499 Tracks (@pxref{Trace}) all procedures @code{define}d at top-level in
10500 @file{file} @dots{}.
10501 @deffnx Procedure stack-all file @dots{}
10502 Stacks (@pxref{Trace}) all procedures @code{define}d at top-level in
10503 @file{file} @dots{}.
10504 @end deffn
10505
10506 @deffn Procedure break-all file @dots{}
10507 Breakpoints (@pxref{Breakpoints}) all procedures @code{define}d at
10508 top-level in @file{file} @dots{}.
10509 @end deffn
10510
10511 @node Breakpoints, Trace, Debug, Session Support
10512 @subsection Breakpoints
10513
10514 @code{(require 'break)}
10515 @ftindex break
10516
10517 @defun init-debug
10518 If your Scheme implementation does not support @code{break} or
10519 @code{abort}, a message will appear when you @code{(require 'break)} or
10520 @ftindex break
10521 @code{(require 'debug)} telling you to type @code{(init-debug)}. This
10522 @ftindex debug
10523 is in order to establish a top-level continuation. Typing
10524 @code{(init-debug)} at top level sets up a continuation for
10525 @code{break}.
10526 @end defun
10527
10528 @defun breakpoint arg1 @dots{}
10529 Returns from the top level continuation and pushes the continuation from
10530 which it was called on a continuation stack.
10531 @end defun
10532
10533 @defun continue
10534 Pops the topmost continuation off of the continuation stack and returns
10535 an unspecified value to it.
10536
10537 @defunx continue arg1 @dots{}
10538 Pops the topmost continuation off of the continuation stack and returns
10539 @var{arg1} @dots{} to it.
10540 @end defun
10541
10542 @defmac break proc1 @dots{}
10543 Redefines the top-level named procedures given as arguments so that
10544 @code{breakpoint} is called before calling @var{proc1} @dots{}.
10545 @defmacx break
10546 With no arguments, makes sure that all the currently broken identifiers
10547 are broken (even if those identifiers have been redefined) and returns a
10548 list of the broken identifiers.
10549 @end defmac
10550
10551 @defmac unbreak proc1 @dots{}
10552 Turns breakpoints off for its arguments.
10553 @defmacx unbreak
10554 With no arguments, unbreaks all currently broken identifiers and returns
10555 a list of these formerly broken identifiers.
10556 @end defmac
10557
10558 These are @emph{procedures} for breaking. If defmacros are not natively
10559 supported by your implementation, these might be more convenient to use.
10560
10561 @defun breakf proc
10562 @defunx breakf proc name
10563 To break, type
10564 @lisp
10565 (set! @var{symbol} (breakf @var{symbol}))
10566 @end lisp
10567 @noindent
10568 or
10569 @lisp
10570 (set! @var{symbol} (breakf @var{symbol} '@var{symbol}))
10571 @end lisp
10572 @noindent
10573 or
10574 @lisp
10575 (define @var{symbol} (breakf @var{function}))
10576 @end lisp
10577 @noindent
10578 or
10579 @lisp
10580 (define @var{symbol} (breakf @var{function} '@var{symbol}))
10581 @end lisp
10582 @end defun
10583
10584 @defun unbreakf proc
10585 To unbreak, type
10586 @lisp
10587 (set! @var{symbol} (unbreakf @var{symbol}))
10588 @end lisp
10589 @end defun
10590
10591 @node Trace, System Interface, Breakpoints, Session Support
10592 @subsection Tracing
10593
10594 @code{(require 'trace)}
10595 @ftindex trace
10596
10597 @noindent
10598 This feature provides three ways to monitor procedure invocations:
10599
10600 @table @asis
10601 @item stack
10602 Pushes the procedure-name when the procedure is called; pops when it
10603 returns.
10604 @item track
10605 Pushes the procedure-name and arguments when the procedure is called;
10606 pops when it returns.
10607 @item trace
10608 Pushes the procedure-name and prints @samp{CALL @var{procedure-name}
10609 @var{arg1} @dots{}} when the procdure is called; pops and prints
10610 @samp{RETN @var{procedure-name} @var{value}} when the procedure returns.
10611 @end table
10612
10613 @defvar debug:max-count
10614 If a traced procedure calls itself or untraced procedures which call it,
10615 stack, track, and trace will limit the number of stack pushes to
10616 @var{debug:max-count}.
10617 @end defvar
10618
10619 @defun print-call-stack
10620 @defunx print-call-stack port
10621 Prints the call-stack to @var{port} or the current-error-port.
10622 @end defun
10623
10624
10625 @defmac trace proc1 @dots{}
10626 Traces the top-level named procedures given as arguments.
10627 @defmacx trace
10628 With no arguments, makes sure that all the currently traced identifiers
10629 are traced (even if those identifiers have been redefined) and returns a
10630 list of the traced identifiers.
10631 @end defmac
10632
10633 @defmac track proc1 @dots{}
10634 Traces the top-level named procedures given as arguments.
10635 @defmacx track
10636 With no arguments, makes sure that all the currently tracked identifiers
10637 are tracked (even if those identifiers have been redefined) and returns
10638 a list of the tracked identifiers.
10639 @end defmac
10640
10641 @defmac stack proc1 @dots{}
10642 Traces the top-level named procedures given as arguments.
10643 @defmacx stack
10644 With no arguments, makes sure that all the currently stacked identifiers
10645 are stacked (even if those identifiers have been redefined) and returns
10646 a list of the stacked identifiers.
10647 @end defmac
10648
10649 @defmac untrace proc1 @dots{}
10650 Turns tracing, tracking, and off for its arguments.
10651 @defmacx untrace
10652 With no arguments, untraces all currently traced identifiers and returns
10653 a list of these formerly traced identifiers.
10654 @end defmac
10655
10656 @defmac untrack proc1 @dots{}
10657 Turns tracing, tracking, and off for its arguments.
10658 @defmacx untrack
10659 With no arguments, untracks all currently tracked identifiers and returns
10660 a list of these formerly tracked identifiers.
10661 @end defmac
10662
10663 @defmac unstack proc1 @dots{}
10664 Turns tracing, stacking, and off for its arguments.
10665 @defmacx unstack
10666 With no arguments, unstacks all currently stacked identifiers and returns
10667 a list of these formerly stacked identifiers.
10668 @end defmac
10669
10670 These are @emph{procedures} for tracing. If defmacros are not natively
10671 supported by your implementation, these might be more convenient to use.
10672
10673 @defun tracef proc
10674 @defunx tracef proc name
10675 To trace, type
10676 @lisp
10677 (set! @var{symbol} (tracef @var{symbol}))
10678 @end lisp
10679 @noindent
10680 or
10681 @lisp
10682 (set! @var{symbol} (tracef @var{symbol} '@var{symbol}))
10683 @end lisp
10684 @noindent
10685 or
10686 @lisp
10687 (define @var{symbol} (tracef @var{function}))
10688 @end lisp
10689 @noindent
10690 or
10691 @lisp
10692 (define @var{symbol} (tracef @var{function} '@var{symbol}))
10693 @end lisp
10694 @end defun
10695
10696 @defun untracef proc
10697 Removes tracing, tracking, or stacking for @var{proc}.
10698 To untrace, type
10699 @lisp
10700 (set! @var{symbol} (untracef @var{symbol}))
10701 @end lisp
10702 @end defun
10703
10704
10705 @node System Interface, , Trace, Session Support
10706 @subsection System Interface
10707
10708 @noindent
10709 If @code{(provided? 'getenv)}:
10710
10711 @defun getenv name
10712 Looks up @var{name}, a string, in the program environment. If @var{name} is
10713 found a string of its value is returned. Otherwise, @code{#f} is returned.
10714 @end defun
10715
10716 @noindent
10717 If @code{(provided? 'system)}:
10718
10719 @defun system command-string
10720 Executes the @var{command-string} on the computer and returns the
10721 integer status code.
10722 @end defun
10723
10724 @noindent
10725 If @code{system} is provided by the Scheme implementation, the
10726 @dfn{net-clients} package provides interfaces to common network client
10727 programs like FTP, mail, and Netscape.
10728
10729 @code{(require 'net-clients)}
10730 @ftindex net-clients
10731
10732 @include nclients.txi
10733
10734
10735 @node Extra-SLIB Packages, , Session Support, Other Packages
10736 @section Extra-SLIB Packages
10737
10738 Several Scheme packages have been written using SLIB. There are several
10739 reasons why a package might not be included in the SLIB distribution:
10740 @itemize @bullet
10741 @item
10742 Because it requires special hardware or software which is not universal.
10743 @item
10744 Because it is large and of limited interest to most Scheme users.
10745 @item
10746 Because it has copying terms different enough from the other SLIB
10747 packages that its inclusion would cause confusion.
10748 @item
10749 Because it is an application program, rather than a library module.
10750 @item
10751 Because I have been too busy to integrate it.
10752 @end itemize
10753
10754 Once an optional package is installed (and an entry added to
10755 @code{*catalog*}, the @code{require} mechanism allows it to be called up
10756 and used as easily as any other SLIB package. Some optional packages
10757 (for which @code{*catalog*} already has entries) available from SLIB
10758 sites are:
10759
10760 @table @asis
10761 @item SLIB-PSD
10762 is a portable debugger for Scheme (requires emacs editor).
10763
10764 @ifset html
10765 <A HREF="http://swissnet.ai.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz">
10766 @end ifset
10767 http://swissnet.ai.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz
10768 @ifset html
10769 </A>
10770 @end ifset
10771
10772 swissnet.ai.mit.edu:/pub/scm/slib-psd1-3.tar.gz
10773
10774 ftp.maths.tcd.ie:pub/bosullvn/jacal/slib-psd1-3.tar.gz
10775
10776 ftp.cs.indiana.edu:/pub/scheme-repository/utl/slib-psd1-3.tar.gz
10777 @sp 1
10778
10779 With PSD, you can run a Scheme program in an Emacs buffer, set
10780 breakpoints, single step evaluation and access and modify the program's
10781 variables. It works by instrumenting the original source code, so it
10782 should run with any R4RS compliant Scheme. It has been tested with SCM,
10783 Elk 1.5, and the sci interpreter in the Scheme->C system, but should
10784 work with other Schemes with a minimal amount of porting, if at
10785 all. Includes documentation and user's manual. Written by Pertti
10786 Kellom\"aki, pk@@cs.tut.fi. The Lisp Pointers article describing PSD
10787 (Lisp Pointers VI(1):15-23, January-March 1993) is available as
10788 @ifset html
10789 <A HREF="http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html">
10790 @end ifset
10791 http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html
10792 @ifset html
10793 </A>
10794 @end ifset
10795 @sp 1
10796
10797 @item SCHELOG
10798 is an embedding of Prolog in Scheme.
10799 @ifset html
10800 <A HREF="http://www.cs.rice.edu/CS/PLT/packages/schelog/">
10801 @end ifset
10802 http://www.cs.rice.edu/CS/PLT/packages/schelog/
10803 @ifset html
10804 </A>
10805 @end ifset
10806 @sp 1
10807
10808 @item JFILTER
10809 is a Scheme program which converts text among the JIS, EUC, and Shift-JIS Japanese character sets.
10810 @ifset html
10811 <A HREF="http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html">
10812 @end ifset
10813 http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html
10814 @ifset html
10815 </A>
10816 @end ifset
10817 @end table
10818
10819
10820 @node About SLIB, Index, Other Packages, Top
10821 @chapter About SLIB
10822
10823 @ifinfo
10824 @noindent
10825 More people than I can name have contributed to SLIB. Thanks to all of
10826 you!
10827
10828 @quotation
10829 SLIB @value{SLIBVERSION}, released @value{SLIBDATE}.@*
10830 Aubrey Jaffer <jaffer @@ ai.mit.edu>@*
10831 @i{Hyperactive Software} -- The Maniac Inside!@*
10832 @url{http://swissnet.ai.mit.edu/~jaffer/SLIB.html}
10833 @end quotation
10834 @end ifinfo
10835
10836 @menu
10837 * Installation:: How to install SLIB on your system.
10838 * Porting:: SLIB to new platforms.
10839 * Coding Guidelines:: How to write modules for SLIB.
10840 * Copyrights:: Intellectual propery issues.
10841 @end menu
10842
10843
10844 @node Installation, Porting, About SLIB, About SLIB
10845 @section Installation
10846
10847
10848 @ifset html
10849 <A NAME="Installation">
10850 @end ifset
10851 @ifset html
10852 </A>
10853 @end ifset
10854
10855 Check the manifest in @file{README} to find a configuration file for
10856 your Scheme implementation. Initialization files for most IEEE P1178
10857 compliant Scheme Implementations are included with this distribution.
10858
10859 If the Scheme implementation supports @code{getenv}, then the value of
10860 the shell environment variable @var{SCHEME_LIBRARY_PATH} will be used
10861 for @code{(library-vicinity)} if it is defined. Currently, Chez, Elk,
10862 MITScheme, scheme->c, VSCM, and SCM support @code{getenv}. Scheme48
10863 supports @code{getenv} but does not use it for determining
10864 @code{library-vicinity}. (That is done from the Makefile.)
10865
10866 You should check the definitions of @code{software-type},
10867 @code{scheme-implementation-version},
10868 @iftex
10869 @*
10870 @end iftex
10871 @code{implementation-vicinity},
10872 and @code{library-vicinity} in the initialization file. There are
10873 comments in the file for how to configure it.
10874
10875 Once this is done you can modify the startup file for your Scheme
10876 implementation to @code{load} this initialization file. SLIB is then
10877 installed.
10878
10879 Multiple implementations of Scheme can all use the same SLIB directory.
10880 Simply configure each implementation's initialization file as outlined
10881 above.
10882
10883 @deftp Implementation SCM
10884 The SCM implementation does not require any initialization file as SLIB
10885 support is already built into SCM. See the documentation with SCM for
10886 installation instructions.
10887 @end deftp
10888
10889 @deftp Implementation VSCM
10890 @format
10891 From: Matthias Blume <blume@@cs.Princeton.EDU>
10892 Date: Tue, 1 Mar 1994 11:42:31 -0500
10893 @end format
10894
10895 Disclaimer: The code below is only a quick hack. If I find some time to
10896 spare I might get around to make some more things work.
10897
10898 You have to provide @file{vscm.init} as an explicit command line
10899 argument. Since this is not very nice I would recommend the following
10900 installation procedure:
10901
10902 @enumerate
10903 @item
10904 run scheme
10905 @item
10906 @code{(load "vscm.init")}
10907 @item
10908 @code{(slib:dump "dumpfile")}
10909 @item
10910 mv dumpfile place-where-vscm-standard-bootfile-resides
10911 e.g. mv dumpfile /usr/local/vscm/lib/scheme-boot
10912 (In this case vscm should have been compiled with flag
10913 -DDEFAULT_BOOTFILE='"/usr/local/vscm/lib/scheme-boot"'. See Makefile
10914 (definition of DDP) for details.)
10915 @end enumerate
10916
10917 @end deftp
10918
10919 @deftp Implementation Scheme48
10920 To make a Scheme48 image for an installation under @code{<prefix>},
10921
10922 @enumerate
10923 @item
10924 @code{cd} to the SLIB directory
10925 @item
10926 type @code{make prefix=<prefix> slib48}.
10927 @item
10928 To install the image, type @code{make prefix=<prefix> install48}. This
10929 will also create a shell script with the name @code{slib48} which will
10930 invoke the saved image.
10931 @end enumerate
10932 @end deftp
10933
10934 @deftp Implementation {PLT Scheme}
10935 @deftpx Implementation {DrScheme}
10936 @deftpx Implementation {MzScheme}
10937 @format
10938 Date: Mon, 2 Oct 2000 21:29:48 -0400 (EDT)
10939 From: Shriram Krishnamurthi <sk@@cs.brown.edu>
10940 @end format
10941
10942 We distribute an SLIB init file for our system. If you have PLT Scheme
10943 (our preferred name for the entire suite, which includes DrScheme,
10944 MzScheme and other implementations) installed, you ought to be able to
10945 run @dfn{help-desk}, or run @samp{drscheme} and choose Help Desk from
10946 the Help menu; in Help Desk, type @samp{slib}. This will give
10947 instructions for how to load the SLIB init file.
10948 @end deftp
10949
10950
10951 @node Porting, Coding Guidelines, Installation, About SLIB
10952 @section Porting
10953
10954 If there is no initialization file for your Scheme implementation, you
10955 will have to create one. Your Scheme implementation must be largely
10956 compliant with @cite{IEEE Std 1178-1990}, @cite{Revised^4 Report on the
10957 Algorithmic Language Scheme}, or @cite{Revised^5 Report on the
10958 Algorithmic Language Scheme} in order to support SLIB. @footnote{If you
10959 are porting a @cite{Revised^3 Report on the Algorithmic Language Scheme}
10960 implementation, then you will need to finish writing @file{sc4sc3.scm}
10961 and @code{load} it from your initialization file.}
10962
10963 @file{Template.scm} is an example configuration file. The comments
10964 inside will direct you on how to customize it to reflect your system.
10965 Give your new initialization file the implementation's name with
10966 @file{.init} appended. For instance, if you were porting
10967 @code{foo-scheme} then the initialization file might be called
10968 @file{foo.init}.
10969
10970 Your customized version should then be loaded as part of your scheme
10971 implementation's initialization. It will load @file{require.scm} from
10972 the library; this will allow the use of @code{provide},
10973 @code{provided?}, and @code{require} along with the @dfn{vicinity}
10974 functions (these functions are documented in the section @ref{Require}).
10975 The rest of the library will then be accessible in a system independent
10976 fashion.
10977
10978 Please mail new working configuration files to @code{jaffer @@ ai.mit.edu}
10979 so that they can be included in the SLIB distribution.
10980
10981
10982 @node Coding Guidelines, Copyrights, Porting, About SLIB
10983 @section Coding Guidelines
10984
10985 All library packages are written in IEEE P1178 Scheme and assume that a
10986 configuration file and @file{require.scm} package have already been
10987 loaded. Other versions of Scheme can be supported in library packages
10988 as well by using, for example, @code{(provided? 'rev3-report)} or
10989 @code{(require 'rev3-report)} (@pxref{Require}).
10990 @ftindex rev3-report
10991
10992 The module name and @samp{:} should prefix each symbol defined in the
10993 package. Definitions for external use should then be exported by having
10994 @code{(define foo module-name:foo)}.
10995
10996 Code submitted for inclusion in SLIB should not duplicate routines
10997 already in SLIB files. Use @code{require} to force those library
10998 routines to be used by your package. Care should be taken that there
10999 are no circularities in the @code{require}s and @code{load}s between the
11000 library packages.
11001
11002 Documentation should be provided in Emacs Texinfo format if possible,
11003 But documentation must be provided.
11004
11005 Your package will be released sooner with SLIB if you send me a file
11006 which tests your code. Please run this test @emph{before} you send me
11007 the code!
11008
11009 @subheading Modifications
11010
11011 Please document your changes. A line or two for @file{ChangeLog} is
11012 sufficient for simple fixes or extensions. Look at the format of
11013 @file{ChangeLog} to see what information is desired. Please send me
11014 @code{diff} files from the latest SLIB distribution (remember to send
11015 @code{diff}s of @file{slib.texi} and @file{ChangeLog}). This makes for
11016 less email traffic and makes it easier for me to integrate when more
11017 than one person is changing a file (this happens a lot with
11018 @file{slib.texi} and @samp{*.init} files).
11019
11020 If someone else wrote a package you want to significantly modify, please
11021 try to contact the author, who may be working on a new version. This
11022 will insure against wasting effort on obsolete versions.
11023
11024 Please @emph{do not} reformat the source code with your favorite
11025 beautifier, make 10 fixes, and send me the resulting source code. I do
11026 not have the time to fish through 10000 diffs to find your 10 real fixes.
11027
11028 @node Copyrights, , Coding Guidelines, About SLIB
11029 @section Copyrights
11030
11031 @ifset html
11032 <A NAME="Copyrights">
11033 @end ifset
11034 @ifset html
11035 </A>
11036 @end ifset
11037
11038 This section has instructions for SLIB authors regarding copyrights.
11039
11040 Each package in SLIB must either be in the public domain, or come with a
11041 statement of terms permitting users to copy, redistribute and modify it.
11042 The comments at the beginning of @file{require.scm} and
11043 @file{macwork.scm} illustrate copyright and appropriate terms.
11044
11045 If your code or changes amount to less than about 10 lines, you do not
11046 need to add your copyright or send a disclaimer.
11047
11048 @subheading Putting code into the Public Domain
11049
11050 In order to put code in the public domain you should sign a copyright
11051 disclaimer and send it to the SLIB maintainer. Contact
11052 jaffer @@ ai.mit.edu for the address to mail the disclaimer to.
11053
11054 @quotation
11055 I, @var{name}, hereby affirm that I have placed the software package
11056 @var{name} in the public domain.
11057
11058 I affirm that I am the sole author and sole copyright holder for the
11059 software package, that I have the right to place this software package
11060 in the public domain, and that I will do nothing to undermine this
11061 status in the future.
11062
11063 @flushright
11064 @var{signature and date}
11065 @end flushright
11066 @end quotation
11067
11068 This wording assumes that you are the sole author. If you are not the
11069 sole author, the wording needs to be different. If you don't want to be
11070 bothered with sending a letter every time you release or modify a
11071 module, make your letter say that it also applies to your future
11072 revisions of that module.
11073
11074 Make sure no employer has any claim to the copyright on the work you are
11075 submitting. If there is any doubt, create a copyright disclaimer and
11076 have your employer sign it. Mail the signed disclaimer to the SLIB
11077 maintainer. Contact jaffer @@ ai.mit.edu for the address to mail the
11078 disclaimer to. An example disclaimer follows.
11079
11080 @subheading Explicit copying terms
11081
11082 @noindent
11083 If you submit more than about 10 lines of code which you are not placing
11084 into the Public Domain (by sending me a disclaimer) you need to:
11085
11086 @itemize @bullet
11087 @item
11088 Arrange that your name appears in a copyright line for the appropriate
11089 year. Multiple copyright lines are acceptable.
11090 @item
11091 With your copyright line, specify any terms you require to be different
11092 from those already in the file.
11093 @item
11094 Make sure no employer has any claim to the copyright on the work you are
11095 submitting. If there is any doubt, create a copyright disclaimer and
11096 have your employer sign it. Mail the signed disclaim to the SLIB
11097 maintainer. Contact jaffer @@ ai.mit.edu for the address to mail the
11098 disclaimer to.
11099 @end itemize
11100
11101 @subheading Example: Company Copyright Disclaimer
11102
11103 This disclaimer should be signed by a vice president or general manager
11104 of the company. If you can't get at them, anyone else authorized to
11105 license out software produced there will do. Here is a sample wording:
11106
11107 @quotation
11108 @var{employer} Corporation hereby disclaims all copyright
11109 interest in the program @var{program} written by @var{name}.
11110
11111 @var{employer} Corporation affirms that it has no other intellectual
11112 property interest that would undermine this release, and will do nothing
11113 to undermine it in the future.
11114
11115 @flushleft
11116 @var{signature and date},
11117 @var{name}, @var{title}, @var{employer} Corporation
11118 @end flushleft
11119 @end quotation
11120
11121 @node Index, , About SLIB, Top
11122 @c @node Procedure and Macro Index, Variable Index, About SLIB, Top
11123 @unnumbered Procedure and Macro Index
11124
11125 This is an alphabetical list of all the procedures and macros in SLIB.
11126
11127 @printindex fn
11128
11129 @c @node Variable Index, Concept Index, Procedure and Macro Index, Top
11130 @unnumbered Variable Index
11131
11132 This is an alphabetical list of all the global variables in SLIB.
11133
11134 @printindex vr
11135
11136 @c @node Concept Index, , Variable Index, Top
11137 @unnumbered Concept and Feature Index
11138
11139 @printindex cp
11140
11141 @contents
11142 @bye