1 \input texinfo @c -*-texinfo-*-
7 @c Choices for setchapternewpage are {on,off,odd}.
14 @dircategory The Algorithmic Language Scheme
16 * SLIB: (slib). Scheme Library
21 @c DL: lose the egregious vertical whitespace, esp. around examples
22 @c but paras in @defun-like things don't have parindent
27 This file documents SLIB, the portable Scheme library.
29 Copyright (C) 1993 Todd R. Eigenschink@*
30 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000 Aubrey Jaffer
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.
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).
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.
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
54 @node Top, The Library System, (dir), (dir)
58 @subtitle The Portable Scheme Library
59 @subtitle Version @value{SLIBVERSION}
60 @author by Aubrey Jaffer
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.
72 More people than I can name have contributed to SLIB. Thanks to all of
76 SLIB @value{SLIBVERSION}, released @value{SLIBDATE}.@*
77 Aubrey Jaffer <jaffer @@ ai.mit.edu>@*
79 <A HREF="http://swissnet.ai.mit.edu/~jaffer/SLIB.html">
81 @url{http://swissnet.ai.mit.edu/~jaffer/SLIB.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
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.
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.
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
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.
119 * The Library System:: How to use and customize.
120 * Scheme Syntax Extension Packages::
121 * Textual Conversion Packages::
122 * Mathematical Packages::
123 * Database Packages::
125 * About SLIB:: Install, etc.
129 @node The Library System, Scheme Syntax Extension Packages, Top, Top
130 @chapter The Library System
133 * Feature:: SLIB names.
134 * Requesting Features::
136 * Catalog Compilation::
138 * About this manual::
142 @node Feature, Requesting Features, The Library System, The Library System
147 SLIB denotes @dfn{features} by symbols. SLIB maintains a list of
148 features supported by the Scheme @dfn{session}. The set of features
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
169 Other features correspond to the presence of sets of Scheme procedures
172 @defun provided? feature
173 Returns @code{#t} if @var{feature} is supported by the current Scheme
177 @deffn Procedure provide feature
178 Informs SLIB that @var{feature} is supported. Henceforth
179 @code{(provided? @var{feature})} will return @code{#t}.
183 (provided? 'foo) @result{} #f
185 (provided? 'foo) @result{} #t
189 @node Requesting Features, Library Catalogs, Feature, The Library System
190 @section Requesting Features
194 SLIB creates and maintains a @dfn{catalog} mapping features to locations
195 of files introducing procedures and syntax denoted by those features.
198 At the beginning of each section of this manual, there is a line like
199 @code{(require '@var{feature})}.
201 The Scheme files comprising SLIB are cataloged so that these feature
202 names map to the corresponding files.
205 SLIB provides a form, @code{require}, which loads the files providing
206 the requested feature.
208 @deffn Procedure require feature
211 If @code{(provided? @var{feature})} is true,
212 then @code{require} just returns an unspecified value.
214 Otherwise, if @var{feature} is found in the catalog, then the
215 corresponding files will be loaded and an unspecified value returned.
217 Subsequently @code{(provided? @var{feature})} will return @code{#t}.
219 Otherwise (@var{feature} not found in the catalog), an error is
225 The catalog can also be queried using @code{require:feature->path}.
227 @defun require:feature->path feature
230 If @var{feature} is already provided, then returns @code{#t}.
232 Otherwise, if @var{feature} is in the catalog, the path or list of paths
233 associated with @var{feature} is returned.
235 Otherwise, returns @code{#f}.
240 @node Library Catalogs, Catalog Compilation, Requesting Features, The Library System
241 @section Library Catalogs
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:
250 standard SLIB packages.
252 additional packages of interest to this site.
254 packages specifically for the variety of Scheme which this
257 packages this user wants to always have available. This catalog is the
258 file @file{homecat} in the user's @dfn{HOME} directory.
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
268 Catalog files consist of one or more @dfn{association list}s.
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:
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{}.
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.
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>}.
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>}.
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)}.
313 ;;; "usercat": SLIB catalog additions for SIMSYNCH. -*-scheme-*-
316 (simsynch . "../synch/simsynch.scm")
317 (run . "../synch/run.scm")
318 (schlep . "schlep.scm")
323 @node Catalog Compilation, Built-in Support, Library Catalogs, The Library System
324 @section Catalog Compilation
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.
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.
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}:
348 @deffn Procedure require @r{'new-catalog}
350 This will load @file{mklibcat}, which compiles and writes a new
355 Another special form of @code{require} erases SLIB's catalog, forcing it
356 to be reloaded the next time the catalog is queried.
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
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
372 @item @code{implementation-vicinity} @file{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.
378 @item @code{library-vicinity} @file{mklibcat.scm}
380 creates @file{slibcat}.
382 @item @code{library-vicinity} @file{sitecat}
384 This file contains the associations specific to an SLIB installation.
386 @item @code{implementation-vicinity} @file{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}.
392 @item @code{implementation-vicinity} @file{mkimpcat.scm}
394 if present, creates @file{implcat}.
396 @item @code{implementation-vicinity} @file{sitecat}
398 This file contains the associations specific to a Scheme implementation
401 @item @code{home-vicinity} @file{homecat}
403 This file contains the associations specific to an SLIB user.
405 @item @code{user-vicinity} @file{usercat}
407 This file contains associations effecting only those sessions whose
408 @dfn{working directory} is @code{user-vicinity}.
412 @node Built-in Support, About this manual, Catalog Compilation, The Library System
413 @section Built-in Support
416 The procedures described in these sections are supported by all
417 implementations as part of the @samp{*.init} files or by
421 * Require:: Module Management
422 * Vicinity:: Pathname Management
423 * Configuration:: Characteristics of Scheme Implementation
424 * Input/Output:: Things not provided by the Scheme specs.
426 * System:: LOADing, EVALing, ERRORing, and EXITing
430 @node Require, Vicinity, Built-in Support, Built-in Support
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
439 Here are features which SLIB (@file{require.scm}) adds to
440 @var{*features*} when appropriate.
455 For each item, @code{(provided? '@var{feature})} will return @code{#t}
456 if that feature is available, and @code{#f} if not.
460 Is a list of pathnames denoting files which have been loaded.
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.
472 In the following functions if the argument @var{feature} is not a symbol
473 it is assumed to be a pathname.
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.
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.
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.
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.
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
512 @node Vicinity, Configuration, Require, Built-in Support
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.
526 These procedures are provided by all implementations.
528 @defun make-vicinity path
529 Returns the vicinity of @var{path} for use by @code{in-vicinity}.
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
542 @defun library-vicinity
543 Returns the vicinity of the shared Scheme library.
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.
552 Returns the vicinity of the current directory of the user. On most
553 systems this is @file{""} (the empty string).
557 Returns the vicinity of the user's @dfn{HOME} directory, the directory
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}
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}.
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}.
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
593 @node Configuration, Input/Output, Vicinity, Built-in Support
594 @subsection Configuration
597 These constants and procedures describe characteristics of the Scheme
598 and underlying operating system. They are provided by all
601 @defvr Constant char-code-limit
602 An integer 1 larger that the largest value which can be returned by
603 @code{char->integer}.
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,
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.
617 @defvr Constant slib:tab
621 @defvr Constant slib:form-feed
622 The form-feed character.
626 Returns a symbol denoting the generic operating system type. For
627 instance, @code{unix}, @code{vms}, @code{macos}, @code{amiga}, or
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.
636 (slib:report-version) @result{} slib "@value{SLIBVERSION}" on scm "5b1" on unix
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.
645 @defunx slib:report #t
646 provides a more verbose listing.
648 @defunx slib:report filename
649 Writes the report to file @file{filename}.
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"
660 common-list-functions macro values getopt
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
673 implementation *catalog* :
674 (i/o-extensions compiled "/home/jaffer/scm/ioext.so")
679 @node Input/Output, Legacy, Configuration, Built-in Support
680 @subsection Input/Output
683 These procedures are provided by all implementations.
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.
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
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
703 @deffn Procedure current-error-port
704 Returns the current port to which diagnostic and error output is
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)}.
716 @deffn Procedure output-port-width
717 @deffnx Procedure output-port-width port
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.
724 @deffn Procedure output-port-height
725 @deffnx Procedure output-port-height port
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.
732 @node Legacy, System, Input/Output, Built-in Support
735 These procedures are provided by all implementations.
738 @var{identity} returns its argument.
744 (identity '(foo bar))
746 (map identity @var{lst})
747 @equiv{} (copy-list @var{lst})
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.
757 Derfined as @code{#t}.
761 Defined as @code{#f}.
765 Returns the last pair in the list @var{l}. Example:
767 (last-pair (cons 1 2))
771 @equiv{} (cons 2 '())
775 @node System, , Legacy, Built-in Support
779 These procedures are provided by all implementations.
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}.
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.
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
801 If an implementation does not support compiled code then
802 @code{slib:load} will be identical to @code{slib:load-source}.
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
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}.
819 @deffn Procedure slib:warn arg1 arg2 @dots{}
820 Outputs a warning message containing the arguments.
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
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}.
841 @node About this manual, , Built-in Support, The Library System
842 @section About this manual
846 Entries that are labeled as Functions are called for their return
847 values. Entries that are labeled as Procedures are called primarily for
851 Examples in this text were produced using the @code{scm} Scheme
855 At the beginning of each section, there is a line that looks like
857 @code{(require 'feature)}. Include this line in your code prior to
862 @node Scheme Syntax Extension Packages, Textual Conversion Packages, The Library System, Top
863 @chapter Scheme Syntax Extension Packages
866 * Defmacro:: Supported by all implementations
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
874 Syntax extensions (macros) included with SLIB. Also @xref{Structures}.
876 * Fluid-Let:: 'fluid-let
877 * Yasos:: 'yasos, 'oop, 'collect
881 @node Defmacro, R4RS Macros, Scheme Syntax Extension Packages, Scheme Syntax Extension Packages
884 Defmacros are supported by all implementations.
885 @c See also @code{gentemp}, in @ref{Macros}.
888 Returns a new (interned) symbol each time it is called. The symbol
889 names are implementation-dependent
891 (gentemp) @result{} scm:G0
892 (gentemp) @result{} scm:G1
896 @defun defmacro:eval e
897 Returns the @code{slib:eval} of expanding all defmacros in scheme
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}.
912 Returns @code{#t} if @var{sym} has been defined by @code{defmacro},
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.
923 @code{macroexpand} is similar to @code{macroexpand-1}, but repeatedly
924 expands @var{form} until it is no longer a macro call.
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}.
934 @subsection Defmacroexpand
935 @code{(require 'defmacroexpand)}
936 @ftindex defmacroexpand
938 @defun defmacro:expand* e
939 Returns the result of expanding all defmacros in scheme expression
943 @node R4RS Macros, Macro by Example, Defmacro, Scheme Syntax Extension Packages
946 @code{(require 'macro)} is the appropriate call if you want R4RS
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.
952 The SLIB R4RS macro implementations support the following uniform
955 @defun macro:expand sexpression
956 Takes an R4RS expression, macro-expands it, and returns the result of
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.
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}.
974 @node Macro by Example, Macros That Work, R4RS Macros, Scheme Syntax Extension Packages
975 @section Macro by Example
977 @code{(require 'macro-by-example)}
978 @ftindex macro-by-example
980 A vanilla implementation of @cite{Macro by Example} (Eugene Kohlbecker,
981 R4RS) by Dorai Sitaram, (dorai@@cs.rice.edu) using @code{defmacro}.
986 generating hygienic global @code{define-syntax} Macro-by-Example macros
990 can define macros which use @code{...}.
993 needn't worry about a lexical variable in a macro definition
994 clashing with a variable from the macro use context
997 don't suffer the overhead of redefining the repl if @code{defmacro}
998 natively supported (most implementations)
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}.
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}.
1018 The top-level syntactic environment is extended by binding the
1019 @var{keyword} to the specified transformer.
1024 ((let* () body1 body2 ...)
1025 (let () body1 body2 ...))
1026 ((let* ((name1 val1) (name2 val2) ...)
1029 (let* (( name2 val2) ...)
1030 body1 body2 ...)))))
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
1038 @code{(@var{pattern} @var{template})}
1040 where the @var{pattern} and @var{template} are as in the grammar above.
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.
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
1055 @node Macros That Work, Syntactic Closures, Macro by Example, Scheme Syntax Extension Packages
1056 @section Macros That Work
1058 @code{(require 'macros-that-work)}
1059 @ftindex macros-that-work
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.
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.
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
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}.
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
1096 @center Macros That Work. Clinger and Rees. POPL '91.
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
1103 transformer spec @expansion{} (syntax-rules literals rules)
1105 rules @expansion{} ()
1108 rule @expansion{} (pattern template)
1110 pattern @expansion{} pattern_var ; a symbol not in literals
1111 | symbol ; a symbol in literals
1113 | (pattern . pattern)
1114 | (ellipsis_pattern)
1115 | #(pattern*) ; extends R4RS
1116 | #(pattern* ellipsis_pattern) ; extends R4RS
1119 template @expansion{} pattern_var
1122 | (template2 . template2)
1123 | #(template*) ; extends R4RS
1126 template2 @expansion{} template
1129 pattern_datum @expansion{} string ; no vector
1134 ellipsis_pattern @expansion{} pattern ...
1136 ellipsis_template @expansion{} template ...
1138 pattern_var @expansion{} symbol ; not in literals
1140 literals @expansion{} ()
1141 | (symbol . literals)
1144 @subsection Definitions
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.
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.
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.
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.
1164 @item Variables bound by a pattern
1165 The variables bound by a pattern are the pattern variables that appear
1168 @item Referenced variables of a subtemplate
1169 The referenced variables of a subtemplate are the pattern variables that
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.
1178 @subsection Restrictions
1180 No pattern variable appears more than once within a pattern.
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.
1186 Every ellipsis template must open at least one variable.
1188 For every ellipsis template, the variables opened by an ellipsis
1189 template must all be bound to sequences of the same length.
1191 The compiled form of a @var{rule} is
1194 rule @expansion{} (pattern template inserted)
1196 pattern @expansion{} pattern_var
1199 | (pattern . pattern)
1204 template @expansion{} pattern_var
1207 | (template2 . template2)
1211 template2 @expansion{} template
1214 pattern_datum @expansion{} string
1219 pattern_var @expansion{} #(V symbol rank)
1221 ellipsis_pattern @expansion{} #(E pattern pattern_vars)
1223 ellipsis_template @expansion{} #(E template pattern_vars)
1225 inserted @expansion{} ()
1226 | (symbol . inserted)
1228 pattern_vars @expansion{} ()
1229 | (pattern_var . pattern_vars)
1231 rank @expansion{} exact non-negative integer
1234 where V and E are unforgeable values.
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
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.
1249 @node Syntactic Closures, Syntax-Case Macros, Macros That Work, Scheme Syntax Extension Packages
1250 @section Syntactic Closures
1252 @code{(require 'syntactic-closures)}
1253 @ftindex syntactic-closures
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.
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
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}.
1279 @subsection Syntactic Closure Macro Facility
1281 @center A Syntactic Closures Macro Facility
1282 @center by Chris Hanson
1283 @center 9 November 1991
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
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
1295 @var{transformer spec} := (transformer @var{expression})
1298 Additionally, the following procedures are added:
1300 make-syntactic-closure
1301 capture-syntactic-environment
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}.
1312 @subsubsection Terminology
1314 This section defines the concepts and data types used by the syntactic
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
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.
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
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
1363 @subsubsection Transformer Definition
1365 This section describes the @code{transformer} special form and the
1366 procedures @code{make-syntactic-closure} and
1367 @code{capture-syntactic-environment}.
1369 @deffn Syntax transformer expression
1371 Syntax: It is an error if this syntax occurs except as a
1372 @var{transformer spec}.
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,
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.
1389 For example, here is a definition of a push macro using
1390 @code{syntax-rules}:@refill
1395 (set! list (cons item list)))))
1398 Here is an equivalent definition using @code{transformer}:
1404 (make-syntactic-closure env '() (cadr exp)))
1406 (make-syntactic-closure env '() (caddr exp))))
1407 `(set! ,list (cons ,item ,list))))))
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
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
1424 (let ((body (cdr exp)))
1425 `(call-with-current-continuation
1428 ,@@(map (lambda (exp)
1429 (make-syntactic-closure env '(exit)
1435 To assign meanings to the identifiers in a form, use
1436 @code{make-syntactic-closure} to close the form in a syntactic
1440 @defun make-syntactic-closure environment free-names form
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}.
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
1459 (let ((id (cadr exp))
1463 ,(make-syntactic-closure env (list id) exp))
1464 ,(make-syntactic-closure env '() init))))))
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
1474 To obtain a syntactic environment other than the usage environment, use
1475 @code{capture-syntactic-environment}.
1478 @defun capture-syntactic-environment procedure
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.
1485 An example will make this clear. Suppose we wanted to define a simple
1486 @code{loop-until} keyword equivalent to@refill
1488 (define-syntax loop-until
1490 ((loop-until id init test return step)
1493 (if test return (loop step)))))
1497 The following attempt at defining @code{loop-until} has a subtle bug:
1499 (define-syntax loop-until
1502 (let ((id (cadr exp))
1505 (return (cadddr (cdr exp)))
1506 (step (cadddr (cddr exp)))
1509 (make-syntactic-closure env free exp))))
1512 (if ,(close test (list id))
1513 ,(close return (list id))
1514 (loop ,(close step (list id)))))))
1515 (loop ,(close init '())))))))
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.
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
1535 (define-syntax loop-until
1538 (let ((id (cadr exp))
1541 (return (cadddr (cdr exp)))
1542 (step (cadddr (cddr exp)))
1545 (make-syntactic-closure env free exp))))
1547 ,(capture-syntactic-environment
1550 (,(make-syntactic-closure env '() `if)
1551 ,(close test (list id))
1552 ,(close return (list id))
1553 (,(make-syntactic-closure env '()
1555 ,(close step (list id)))))))))
1556 (loop ,(close init '())))))))
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
1564 A common use of @code{capture-syntactic-environment} is to get the
1565 transformer environment of a macro transformer:@refill
1569 (capture-syntactic-environment
1570 (lambda (transformer-env)
1575 @subsubsection Identifiers
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.
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
1587 (make-syntactic-closure env '() 'a)
1588 @result{} an @dfn{alias}
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.
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.
1608 @defun identifier? object
1609 Returns @code{#t} if @var{object} is an identifier, otherwise returns
1610 @code{#f}. Examples:@refill
1614 (identifier? (make-syntactic-closure env '() 'a))
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
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}.
1657 (capture-syntactic-environment
1658 (lambda (transformer-env)
1659 (identifier=? transformer-env 'x env 'x)))))))
1667 (let-syntax ((bar foo))
1672 (capture-syntactic-environment
1673 (lambda (transformer-env)
1674 (identifier=? transformer-env 'foo
1675 env (cadr form))))))))
1682 @subsubsection Acknowledgements
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
1694 @node Syntax-Case Macros, Fluid-Let, Syntactic Closures, Scheme Syntax Extension Packages
1695 @section Syntax-Case Macros
1697 @code{(require 'syntax-case)}
1698 @ftindex syntax-case
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.
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
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}.
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.
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:
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{}
1737 Removed a couple of Chez scheme dependencies.
1740 Renamed global variables used to minimize the possibility of name
1744 Adding an SLIB-specific initialization file.
1747 Removing a couple extra files, most notably the documentation (but see
1751 If you wish, you can see exactly what changes were done by reading the
1752 shell script in the file @file{syncase.sh}.
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}.
1761 In order to use syntax-case from an interactive top level, execute:
1763 (require 'syntax-case)
1764 @ftindex syntax-case
1767 (repl:top-level macro:eval)
1769 See the section Repl (@pxref{Repl}) for more information.
1771 To check operation of syntax-case get
1772 @file{cs.indiana.edu:/pub/scheme/syntax-case}, and type
1774 (require 'syntax-case)
1775 @ftindex syntax-case
1776 (syncase:sanity-check)
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
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}.
1789 @code{syntax-rules} and @code{with-syntax} (described in @cite{TR356})
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.
1796 Several other top-level bindings not documented in TR356 are created:
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)
1803 The syntax of define has been extended to allow @code{(define @var{id})},
1804 which assigns @var{id} to some unspecified value.
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.
1810 Send bug reports, comments, suggestions, and questions to Kent Dybvig
1811 (dyb@@iuvax.cs.indiana.edu).
1813 @subsection Note from maintainer
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.
1819 @node Fluid-Let, Yasos, Syntax-Case Macros, Scheme Syntax Extension Packages
1822 @code{(require 'fluid-let)}
1825 @deffn Syntax fluid-let @code{(@var{bindings} @dots{})} @var{forms}@dots{}
1828 (fluid-let ((@var{variable} @var{init}) @dots{})
1829 @var{expression} @var{expression} @dots{})
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.
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
1847 @node Yasos, , Fluid-Let, Scheme Syntax Extension Packages
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!
1854 @code{(require 'oop)} or @code{(require 'yasos)}
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].
1863 Another reference is:
1867 <A HREF="ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/swob.txt">
1869 Scheming with Objects
1873 @cite{AI Expert} Volume 7, Number 10 (October 1992), pp. 24-33.
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.
1882 @node Yasos terms, Yasos interface, Yasos, Yasos
1887 Any Scheme data object.
1889 @item @dfn{Instance}
1890 An instance of the OO system; an @dfn{object}.
1892 @item @dfn{Operation}
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.
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.
1917 @node Yasos interface, Setters, Yasos terms, Yasos
1918 @subsection Interface
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.
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.
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{}.
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.
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''.
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.
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.
1972 @node Setters, Yasos examples, Yasos interface, Yasos
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!}.
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}.
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!}:
1997 ((setter string-ref) foo 0 #\F) ; set element 0 of foo
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.
2010 (set (string-ref foo 2) #\O) ; generalized location with getter
2012 (set foo "foo") ; like set!
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.
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.
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.
2040 @node Yasos examples, , Setters, Yasos
2041 @subsection Examples
2044 ;;; These definitions for PRINT and SIZE are
2045 ;;; already supplied by
2048 (define-operation (print obj port)
2050 (if (instance? obj) "#<instance>" "~s")
2053 (define-operation (size obj)
2055 ((vector? obj) (vector-length obj))
2056 ((list? obj) (length obj))
2058 ((string? obj) (string-length obj))
2061 (error "Operation not supported: size" obj))))
2063 (define-predicate cell?)
2064 (define-operation (fetch obj))
2065 (define-operation (store! obj newValue))
2067 (define (make-cell value)
2070 ((fetch self) value)
2071 ((store! self newValue)
2072 (set! value newValue)
2076 (format port "#<Cell: ~s>" (fetch self)))))
2078 (define-operation (discard obj value)
2079 (format #t "Discarding ~s~%" value))
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)))))
2089 (define-predicate array?)
2090 (define-operation (array-ref array index))
2091 (define-operation (array-set! array index value))
2093 (define (make-array num-slots)
2094 (let ((anArray (make-vector num-slots)))
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))
2103 (format port "#<Array ~s>" (size self))))))
2105 (define-operation (position obj))
2106 (define-operation (discarded-value obj))
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)))
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)
2123 (format port "#<Cell-with-history ~s>"
2126 (define-access-operation fetch)
2127 (add-setter fetch store!)
2128 (define foo (make-cell 1))
2130 @result{} "#<Cell: 1>"
2134 @result{} "#<Cell: 2>"
2139 @node Textual Conversion Packages, Mathematical Packages, Scheme Syntax Extension Packages, Top
2140 @chapter Textual Conversion Packages
2143 * Precedence Parsing::
2144 * Format:: Common-Lisp Format
2145 * Standard Formatted I/O:: Posix printf and scanf
2146 * Programs and Arguments::
2148 * HTML Tables:: Databases meet HTML
2149 * HTTP and CGI:: Serve WWW sites
2150 * URI:: Uniform Resource Identifier
2151 * Printing Scheme:: Nicely
2154 * Schmooz:: Documentation markup for Scheme programs
2158 @node Precedence Parsing, Format, Textual Conversion Packages, Textual Conversion Packages
2159 @section Precedence Parsing
2161 @code{(require 'precedence-parse)} or @code{(require 'parse)}
2166 This package implements:
2170 a Pratt style precedence parser;
2172 a @dfn{tokenizer} which congeals tokens according to assigned classes of
2173 constituent characters;
2175 procedures giving direct control of parser rulesets;
2177 procedures for higher level specification of rulesets.
2181 * Precedence Parsing Overview::
2182 * Ruleset Definition and Use::
2183 * Token definition::
2184 * Nud and Led Definition::
2185 * Grammar Rule Definition::
2188 @node Precedence Parsing Overview, Ruleset Definition and Use, Precedence Parsing, Precedence Parsing
2189 @subsection Precedence Parsing Overview
2192 This package offers improvements over previous parsers.
2196 Common computer language constructs are concisely specified.
2198 Grammars can be changed dynamically. Operators can be assigned
2199 different meanings within a lexical context.
2201 Rulesets don't need compilation. Grammars can be changed incrementally.
2203 Operator precedence is specified by integers.
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
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
2220 calls the function @code{exit} with no arguments.
2222 @deftp Grammar prefix - negate
2226 Calls the function @code{negate} with the argument @code{42}.
2228 @deftp Grammar infix - difference
2232 Calls the function @code{difference} with arguments @code{x} and @code{y}.
2234 @deftp Grammar nary + sum
2238 Calls the function @code{sum} with arguments @code{x}, @code{y}, and
2241 @deftp Grammar postfix ! factorial
2245 Calls the function @code{factorial} with the argument @code{5}.
2247 @deftp Grammar prestfix set set!
2251 Calls the function @code{set!} with the arguments @code{foo} and
2254 @deftp Grammar commentfix /* */
2256 /* almost any text here */
2258 Ignores the comment delimited by @code{/*} and @code{*/}.
2260 @deftp Grammar matchfix @{ list @}
2264 Calls the function @code{list} with the arguments @code{0}, @code{1},
2267 @deftp Grammar inmatchfix ( funcall )
2271 Calls the function @code{funcall} with the arguments @code{f}, @code{x},
2274 @deftp Grammar delim ;
2278 delimits the extent of the restfix operator @code{set}.
2282 @node Ruleset Definition and Use, Token definition, Precedence Parsing Overview, Precedence Parsing
2283 @subsection Ruleset Definition and Use
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
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*}
2299 In order to start defining a grammar, either
2302 (set! *syn-defs* '())
2308 (set! *syn-defs* *syn-ignore-whitespace*)
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.
2318 Once your grammar is defined, save the value of @code{*syn-defs*} in a
2319 variable (for use when calling @code{prec:parse}).
2322 (define my-ruleset *syn-defs*)
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*}.
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
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.
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.
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
2350 @findex current-input-port
2353 @node Token definition, Nud and Led Definition, Ruleset Definition and Use, Precedence Parsing
2354 @subsection Token definition
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.
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.
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.
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).
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.
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.
2389 The following convenient constants are provided for use with
2390 @code{tok:char-group}.
2392 @defvr Constant tok:decimal-digits
2393 Is the string @code{"0123456789"}.
2395 @defvr Constant tok:upper-case
2396 Is the string consisting of all upper-case letters
2397 ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
2399 @defvr Constant tok:lower-case
2400 Is the string consisting of all lower-case letters
2401 ("abcdefghijklmnopqrstuvwxyz").
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.
2409 @node Nud and Led Definition, Grammar Rule Definition, Token definition, Precedence Parsing
2410 @subsection Nud and Led Definition
2412 This section describes advanced features. You can skip this section on
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.
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.
2432 Top Down Operator Precendence.
2433 @cite{SIGACT/SIGPLAN Symposium on Principles of Programming Languages},
2434 Boston, 1973, pages 41-51
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.
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.
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
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.
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
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.
2477 If no LED has been defined for a token, and @var{left} is set, the
2478 parser issues a warning.
2480 @node Grammar Rule Definition, , Nud and Led Definition, Precedence Parsing
2481 @subsection Grammar Rule Definition
2484 Here are procedures for defining rules for the syntax types introduced
2485 in @ref{Precedence Parsing Overview}.
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.
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
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
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.
2512 @defun prec:nofix tk sop
2513 Returns a rule specifying the following actions take place when @var{tk}
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.
2523 @defun prec:prefix tk sop bp rule1 @dots{}
2524 Returns a rule specifying the following actions take place when @var{tk}
2528 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2529 rules currently in effect.
2531 @code{prec:parse1} is called with binding-power @var{bp}.
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.
2538 The ruleset in effect before @var{tk} was parsed is restored;
2539 @var{rule1} @dots{} are forgotten.
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:
2549 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2550 rules currently in effect.
2552 One expression is parsed with binding-power @var{lbp}. If instead a
2553 delimiter is encountered, a warning is issued.
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.
2560 The ruleset in effect before @var{tk} was parsed is restored;
2561 @var{rule1} @dots{} are forgotten.
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:
2571 Expressions are parsed with binding-power @var{bp} as far as they are
2572 interleaved with the token @var{tk}.
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.
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:
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
2594 @defun prec:prestfix tk sop bp rule1 @dots{}
2595 Returns a rule specifying the following actions take place when @var{tk}
2599 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2600 rules currently in effect.
2602 Expressions are parsed with binding-power @var{bp} until a delimiter is
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.
2610 The ruleset in effect before @var{tk} was parsed is restored;
2611 @var{rule1} @dots{} are forgotten.
2615 @defun prec:commentfix tk stp match rule1 @dots{}
2616 Returns rules specifying the following actions take place when @var{tk}
2620 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2621 rules currently in effect.
2623 Characters are read until and end-of-file or a sequence of characters
2624 is read which matches the @emph{string} @var{match}.
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).
2629 The ruleset in effect before @var{tk} was parsed is restored;
2630 @var{rule1} @dots{} are forgotten.
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.
2639 @defun prec:matchfix tk sop sep match rule1 @dots{}
2640 Returns a rule specifying the following actions take place when @var{tk}
2644 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2645 rules currently in effect.
2647 A rule declaring the token @var{match} a delimiter takes effect.
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.
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.
2658 The ruleset in effect before @var{tk} was parsed is restored;
2659 @var{rule1} @dots{} are forgotten.
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:
2669 The rules @var{rule1} @dots{} augment and, in case of conflict, override
2670 rules currently in effect.
2672 A rule declaring the token @var{match} a delimiter takes effect.
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.
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.
2683 The ruleset in effect before @var{tk} was parsed is restored;
2684 @var{rule1} @dots{} are forgotten.
2689 @node Format, Standard Formatted I/O, Precedence Parsing, Textual Conversion Packages
2690 @section Format (version 3.0)
2692 @code{(require 'format)}
2697 @node Standard Formatted I/O, Programs and Arguments, Format, Textual Conversion Packages
2698 @section Standard Formatted I/O
2701 * Standard Formatted Output:: 'printf
2702 * Standard Formatted Input:: 'scanf
2707 @code{(require 'stdio)}
2710 @code{require}s @code{printf} and @code{scanf} and additionally defines
2714 Defined to be @code{(current-input-port)}.
2717 Defined to be @code{(current-output-port)}.
2720 Defined to be @code{(current-error-port)}.
2724 @node Standard Formatted Output, Standard Formatted Input, Standard Formatted I/O, Standard Formatted I/O
2725 @subsection Standard Formatted Output
2727 @code{(require 'printf)}
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{}
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.
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.
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}.
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.
2759 The conversion specifications in a format string have the form:
2762 % @r{[} @var{flags} @r{]} @r{[} @var{width} @r{]} @r{[} . @var{precision} @r{]} @r{[} @var{type} @r{]} @var{conversion}
2765 An output conversion specifications consist of an initial @samp{%}
2766 character followed in sequence by:
2770 Zero or more @dfn{flag characters} that modify the normal behavior of
2771 the conversion specification.
2775 Left-justify the result in the field. Normally the result is
2779 For the signed @samp{%d} and @samp{%i} conversions and all inexact
2780 conversions, prefix a plus sign if the value is positive.
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.
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
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
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
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})
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.
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})
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
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.
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.
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.
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.
2865 A character that specifies the conversion to be applied.
2868 @subsubsection Exact Conversions
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}).
2877 Print an integer as an unsigned octal number.
2880 Print an integer as an unsigned decimal number.
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}.
2888 @subsubsection Inexact Conversions
2892 Print a floating-point number in fixed-point notation.
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.
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.
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.
2913 @subsubsection Other Conversions
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.
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.
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
2932 @emph{Note:} @samp{%a} and @samp{%A} are SLIB extensions.
2935 @c Print the value of a pointer.
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.
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}.
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
2954 @node Standard Formatted Input, , Standard Formatted Output, Standard Formatted I/O
2955 @subsection Standard Formatted Input
2957 @code{(require 'scanf)}
2960 @deffn Function scanf-read-list format
2961 @deffnx Function scanf-read-list format port
2962 @deffnx Function scanf-read-list format string
2965 @defmac scanf format arg1 @dots{}
2966 @defmacx fscanf port format arg1 @dots{}
2967 @defmacx sscanf str format arg1 @dots{}
2969 Each function reads characters, interpreting them according to the
2970 control string @var{format} argument.
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:
2981 @item car expression
2983 @item cdr expression
2985 @item vector-ref expression
2987 @item substring expression
2988 @code{substring-move-left!}
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.
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:
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.
3007 @item An ordinary character (not @samp{%}) that must match the next
3008 character of the input stream.
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.
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.
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
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
3047 The conversion code indicates the interpretation of the input field; For
3048 a suppressed field, no value is returned. The following conversion
3054 A single % is expected in the input at this point; no value is returned.
3056 @item @samp{d}, @samp{D}
3057 A decimal integer is expected.
3059 @item @samp{u}, @samp{U}
3060 An unsigned decimal integer is expected.
3062 @item @samp{o}, @samp{O}
3063 An octal integer is expected.
3065 @item @samp{x}, @samp{X}
3066 A hexadecimal integer is expected.
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
3075 Returns the total number of bytes (including white space) read by
3076 @code{scanf}. No input is consumed by @code{%n}.
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.
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.
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.
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
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.
3123 @node Programs and Arguments, HTML, Standard Formatted I/O, Textual Conversion Packages
3124 @section Program and Arguments
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
3135 @node Getopt, Command Line, Programs and Arguments, Programs and Arguments
3138 @code{(require 'getopt)}
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.
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.
3152 Is set by getopt to the (string) option-argument of the current option.
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}.
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
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:
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
3185 Otherwise, @var{*optarg*} is set to the string following the option
3186 character in that element of @var{argv}, and @var{*optind*} is
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
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
3205 The special option @code{"--"} can be used to delimit the end of the
3206 options; @code{#f} is returned, and @code{"--"} is skipped.
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
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{#\:}.
3219 Otherwise, @code{getopt} returns @code{#f} when all command line options
3224 #! /usr/local/bin/scm
3225 ;;;This code is SCM specific.
3226 (define argv (program-arguments))
3230 (define opts ":a:b:cd")
3231 (let loop ((opt (getopt (length argv) argv opts)))
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))))
3250 @subsection Getopt--
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{--}.
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.
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
3271 (define opts ":-:b:")
3273 (define argv '("foo" "-b9" "--f1" "--2=" "--g3=35234.342" "--"))
3275 (define *optarg* #f)
3278 (do ((i 5 (+ -1 i)))
3280 (define opt (getopt-- argc argv opts))
3281 (print *optind* opt *optarg*)))
3291 @node Command Line, Parameter lists, Getopt, Programs and Arguments
3292 @subsection Command Line
3294 @code{(require 'read-command)}
3295 @ftindex read-command
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
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
3310 The @var{port} argument may be omitted, in which case it defaults to the
3311 value returned by @code{current-input-port}.
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{\}).
3319 The initial character and types of fields recognized are:
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.
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
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.
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.
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.
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{;}
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.
3371 @node Parameter lists, Getopt Parameter lists, Command Line, Programs and Arguments
3372 @subsection Parameter lists
3374 @code{(require 'parameters)}
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.
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.
3388 A @var{parameter} has the form @code{(@r{parameter-name} @r{value1}
3389 @dots{})}. This format allows for more than one value per
3393 A @var{parameter-list} is a list of @var{parameter}s, each with a
3394 different @var{parameter-name}.
3396 @deffn Function make-parameter-list parameter-names
3397 Returns an empty parameter-list with slots for @var{parameter-names}.
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}.
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}.
3411 If there are more than one @var{parameter-name} parameters, an error is
3415 @deffn Procedure adjoin-parameters! parameter-list parameter1 @dots{}
3416 Returns @var{parameter-list} with @var{parameter1} @dots{} merged in.
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}.
3427 This process is repeated until @var{parameter-list} stops growing. The
3428 value returned from @code{parameter-list-expand} is unspecified.
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.
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}.
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.
3451 In the following procedures @var{arities} is a list of symbols. The
3452 elements of @code{arities} can be:
3456 Requires a single parameter.
3458 A single parameter or no parameter is acceptable.
3460 A single boolean parameter or zero parameters is acceptable.
3462 Any number of parameters are acceptable.
3464 One or more of parameters are acceptable.
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).
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
3481 @node Getopt Parameter lists, Filenames, Parameter lists, Programs and Arguments
3482 @subsection Getopt Parameter lists
3484 @code{(require 'getopt-parameters)}
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}.
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--}).
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.
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.
3508 In all cases, if unclaimed arguments remain after processing, a warning
3509 is signaled and #f is returned.
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.
3521 These @code{getopt} functions can be used with SLIB relational
3522 databases. For an example, @xref{Database Utilities,
3523 make-command-server}.
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}.
3533 (getopt->parameter-list
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)
3554 Usage: cmd [OPTION ARGUMENT ...] ...
3557 -o, --optional=<number>
3558 -n, --nary=<symbols> ...
3559 -N, --nary1=<symbols> ...
3560 -s, --single=<string>
3566 ERROR: getopt->parameter-list "unrecognized option" "-?"
3570 @node Filenames, Batch, Getopt Parameter lists, Programs and Arguments
3571 @subsection Filenames
3573 @code{(require 'filename)} or @code{(require 'glob)}
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
3581 @dfn{glob} expansion described the bash manpage, except that names
3582 beginning with @samp{.} are matched and @samp{/} characters are not
3585 These functions interpret the following characters specially in
3586 @var{pattern} strings:
3589 Matches any string, including the null string.
3591 Matches any single character.
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.
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.
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.
3626 ((filename:substitute?? "scm_[0-9]*.html" "scm5c4_??.htm")
3628 @result{} "scm5c4_10.htm"
3629 ((filename:substitute?? "??" "beg?mid?end") "AZ")
3630 @result{} "begAmidZend"
3631 ((filename:substitute?? "*na*" "?NA?") "banana")
3633 ((filename:substitute?? "?*?" (lambda (s1 s2 s3) (string-append s3 s1))) "ABZ")
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.
3645 (replace-suffix "/usr/local/lib/slib/batch.scm" ".scm" ".c")
3646 @result{} "/usr/local/lib/slib/batch.c"
3651 @node Batch, , Filenames, Programs and Arguments
3654 @code{(require 'batch)}
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:
3666 The port on which to write lines of the batch file.
3668 The syntax of batch file to generate. Currently supported are:
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.
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
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.
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.
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
3722 (adjoin-parameters! @var{parms} (list 'batch-port @var{port}))
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}.
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
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{}.
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
3746 @var{arg1} @var{arg2} @dots{} @var{chunk}
3749 fits withing the platform's maximum command-line length.
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.
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}
3761 @emph{Note:} @code{batch:run-script} and @code{batch:try-command} are not the
3762 same for some operating systems (VMS).
3765 @defun batch:comment parms line1 @dots{}
3766 Writes comment lines @var{line1} @dots{} to the @code{batch-port} in
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{}.
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}.
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}.
3786 In addition, batch provides some small utilities very useful for writing
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.
3797 (truncate-up-to "/usr/local/lib/slib/batch.scm" "/")
3798 @result{} "batch.scm"
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
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
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
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!}.
3829 Here is an example of the use of most of batch's procedures:
3832 (require 'database-utilities)
3833 @ftindex database-utilities
3834 (require 'parameters)
3841 (define batch (create-database #f 'alist-table))
3842 (batch:initialize! batch)
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
3849 (batch:call-with-output-script
3852 (lambda (batch-port)
3853 (adjoin-parameters! my-parameters (list 'batch-port batch-port))
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)"
3862 " printf(\"hello world\\n\");"
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")
3877 Produces the file @file{my-batch}:
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~
3885 echo '#include <stdio.h>'>>hello.c
3886 echo 'int main(int argc, char **argv)'>>hello.c
3888 echo ' printf("hello world\n");'>>hello.c
3889 echo ' return 0;'>>hello.c
3901 When run, @file{my-batch} prints:
3905 mv: hello.c: No such file or directory
3910 @node HTML, HTML Tables, Programs and Arguments, Textual Conversion Packages
3913 @include htmlform.txi
3916 @node HTML Tables, HTTP and CGI, HTML, Textual Conversion Packages
3917 @section HTML Tables
3919 @include db2html.txi
3922 @node HTTP and CGI, URI, HTML Tables, Textual Conversion Packages
3923 @section HTTP and CGI
3925 @include http-cgi.txi
3928 @node URI, Printing Scheme, HTTP and CGI, Textual Conversion Packages
3935 @node Printing Scheme, Time and Date, URI, Textual Conversion Packages
3936 @section Printing Scheme
3939 * Generic-Write:: 'generic-write
3940 * Object-To-String:: 'object->string
3941 * Pretty-Print:: 'pretty-print, 'pprint-file
3945 @node Generic-Write, Object-To-String, Printing Scheme, Printing Scheme
3946 @subsection Generic-Write
3948 @code{(require 'generic-write)}
3949 @ftindex generic-write
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.
3957 @deffn Procedure generic-write obj display? width output
3960 Scheme data value to transform.
3962 Boolean, controls whether characters and strings are quoted.
3964 Extended boolean, selects format:
3969 pretty-print (value = max nb of chars per line)
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.
3977 The value returned by @code{generic-write} is undefined.
3981 (write obj) @equiv{} (generic-write obj #f #f @var{display-string})
3982 (display obj) @equiv{} (generic-write obj #t #f @var{display-string})
3987 @var{display-string} @equiv{}
3988 (lambda (s) (for-each write-char (string->list s)) #t)
3994 @node Object-To-String, Pretty-Print, Generic-Write, Printing Scheme
3995 @subsection Object-To-String
3997 @code{(require 'object->string)}
3998 @ftindex object->string
4000 @include obj2str.txi
4003 @node Pretty-Print, , Object-To-String, Printing Scheme
4004 @subsection Pretty-Print
4006 @code{(require 'pretty-print)}
4007 @ftindex pretty-print
4009 @deffn Procedure pretty-print obj
4010 @deffnx Procedure pretty-print obj port
4012 @code{pretty-print}s @var{obj} on @var{port}. If @var{port} is not
4013 specified, @code{current-output-port} is used.
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))
4029 @deffn Procedure pretty-print->string obj
4030 @deffnx Procedure pretty-print->string obj width
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
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)))
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))
4077 @code{(require 'pprint-file)}
4078 @ftindex pprint-file
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)}.
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.
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.
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}.
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
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")
4116 @node Time and Date, Vector Graphics, Printing Scheme, Textual Conversion Packages
4117 @section Time and Date
4121 * Posix Time:: 'posix-time
4122 * Common-Lisp Time:: 'common-lisp-time
4126 If @code{(provided? 'current-time)}:
4129 The procedures @code{current-time}, @code{difftime}, and
4130 @code{offset-time} deal with a @dfn{calendar time} datatype
4132 @cindex calendar time
4133 which may or may not be disjoint from other Scheme datatypes.
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}.
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.
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)}.
4151 @node Time Zone, Posix Time, Time and Date, Time and Date
4152 @subsection Time Zone
4154 (require 'time-zone)
4156 @deftp {Data Format} TZ-string
4158 POSIX standards specify several formats for encoding time-zone rules.
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.
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.
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.
4191 Each @i{<date>} has one of the formats:
4195 specifies the Julian day with @i{<day>} between 1 and 365. February 29
4196 is never counted and cannot be referenced.
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.
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.
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.
4221 @defun tz:params caltime tz
4222 @var{tz} is a time-zone object. @code{tz:params} returns a list of
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}.
4230 The number of seconds west of the Prime Meridian timezone @var{tz} is at
4233 The name for timezone @var{tz} at @var{caltime}.
4236 @code{tz:params} is unaffected by the default timezone; inquiries can be
4237 made of any timezone at any calendar time.
4242 The rest of these procedures and variables are provided for POSIX
4243 compatability. Because of shared state they are not thread-safe.
4246 Returns the default time-zone.
4249 Sets (and returns) the default time-zone to @var{tz}.
4251 @defunx tzset TZ-string
4252 Sets (and returns) the default time-zone to that specified by
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
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}.
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.
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.
4281 @node Posix Time, Common-Lisp Time, Time Zone, Time and Date
4282 @subsection Posix Time
4285 (require 'posix-time)
4289 @deftp {Data Type} {Calendar-Time}
4290 @cindex calendar time
4292 is a datatype encapsulating time.
4295 @deftp {Data Type} {Coordinated Universal Time}
4296 @cindex Coordinated Universal Time
4298 (abbreviated @dfn{UTC}) is a vector of integers representing time:
4306 hours since midnight (0 - 23)
4308 day of month (1 - 31)
4310 month (0 - 11). Note difference from @code{decode-universal-time}.
4312 the number of years since 1900. Note difference from
4313 @code{decode-universal-time}.
4317 day of year (0 - 365)
4319 1 for daylight savings, 0 for regular time
4323 @defun gmtime caltime
4324 Converts the calendar time @var{caltime} to UTC and returns it.
4326 @defunx localtime caltime tz
4327 Returns @var{caltime} converted to UTC relative to timezone @var{tz}.
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}).
4338 @defun gmktime univtime
4339 Converts a vector of integers in GMT Coordinated Universal Time (UTC)
4340 format to a calendar time.
4342 @defunx mktime univtime
4343 Converts a vector of integers in local Coordinated Universal Time (UTC)
4344 format to a calendar time.
4346 @defunx mktime univtime tz
4347 Converts a vector of integers in Coordinated Universal Time (UTC) format
4348 (relative to time-zone @var{tz})
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"}.
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.
4367 @node Common-Lisp Time, , Posix Time, Time and Date
4368 @subsection Common-Lisp Time
4370 @defun get-decoded-time
4371 Equivalent to @code{(decode-universal-time (get-universal-time))}.
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}.
4380 @defun decode-universal-time univtime
4381 Converts @var{univtime} to @dfn{Decoded Time} format.
4382 Nine values are returned:
4389 hours since midnight
4393 month (1 - 12). Note difference from @code{gmtime} and @code{localtime}.
4395 year (A.D.). Note difference from @code{gmtime} and @code{localtime}.
4399 #t for daylight savings, #f otherwise
4401 hours west of GMT (-24 - +24)
4404 Notice that the values returned by @code{decode-universal-time} do not
4405 match the arguments to @code{encode-universal-time}.
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.
4414 Notice that the values returned by @code{decode-universal-time} do not
4415 match the arguments to @code{encode-universal-time}.
4419 @node Vector Graphics, Schmooz, Time and Date, Textual Conversion Packages
4420 @section Vector Graphics
4423 * Tektronix Graphics Support::
4426 @node Tektronix Graphics Support, , Vector Graphics, Vector Graphics
4427 @subsection Tektronix Graphics Support
4429 @emph{Note:} The Tektronix graphics support files need more work, and
4432 @subsubsection Tektronix 4000 Series Graphics
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.
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.
4441 @deffn Procedure tek40:init
4444 @deffn Procedure tek40:graphics
4447 @deffn Procedure tek40:text
4450 @deffn Procedure tek40:linetype linetype
4453 @deffn Procedure tek40:move x y
4456 @deffn Procedure tek40:draw x y
4459 @deffn Procedure tek40:put-text x y str
4462 @deffn Procedure tek40:reset
4466 @subsubsection Tektronix 4100 Series Graphics
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.
4471 @deffn Procedure tek41:init
4474 @deffn Procedure tek41:reset
4477 @deffn Procedure tek41:graphics
4480 @deffn Procedure tek41:move x y
4483 @deffn Procedure tek41:draw x y
4486 @deffn Procedure tek41:point x y number
4489 @deffn Procedure tek41:encode-x-y x y
4492 @deffn Procedure tek41:encode-int number
4495 @node Schmooz, , Vector Graphics, Textual Conversion Packages
4498 @include schmooz.texi
4500 @node Mathematical Packages, Database Packages, Textual Conversion Packages, Top
4501 @chapter Mathematical Packages
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
4518 @node Bit-Twiddling, Modular Arithmetic, Mathematical Packages, Mathematical Packages
4519 @section Bit-Twiddling
4521 @code{(require 'logical)}
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
4528 functions. These functions behave as though operating on integers
4529 in two's-complement representation.
4531 @subheading Bitwise Operations
4534 Returns the integer which is the bit-wise AND of the two integer
4539 (number->string (logand #b1100 #b1010) 2)
4545 Returns the integer which is the bit-wise OR of the two integer
4550 (number->string (logior #b1100 #b1010) 2)
4556 Returns the integer which is the bit-wise XOR of the two integer
4561 (number->string (logxor #b1100 #b1010) 2)
4567 Returns the integer which is the 2s-complement of the integer argument.
4571 (number->string (lognot #b10000000) 2)
4572 @result{} "-10000001"
4573 (number->string (lognot #b0) 2)
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
4587 (logtest j k) @equiv{} (not (zero? (logand j k)))
4589 (logtest #b0100 #b1011) @result{} #f
4590 (logtest #b0100 #b0111) @result{} #t
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,
4602 (logcount #b10101010)
4612 @subheading Bit Within Word
4614 @defun logbit? index j
4616 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
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
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}.
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"
4638 @subheading Fields of Bits
4640 @defun bit-field n start end
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.
4646 This function was called @code{bit-extract} in previous versions of SLIB.
4651 (number->string (bit-field #b1101101010 0 4) 2)
4653 (number->string (bit-field #b1101101010 4 9) 2)
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.
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"
4673 @defun ash int count
4674 Returns an integer equivalent to
4675 @code{(inexact->exact (floor (* @var{int} (expt 2 @var{count}))))}.
4679 (number->string (ash #b1 3) 2)
4681 (number->string (ash #b1010 -1) 2)
4686 @defun integer-length n
4687 Returns the number of bits neccessary to represent @var{n}.
4691 (integer-length #b10101010)
4695 (integer-length #b1111)
4700 @defun integer-expt n k
4701 Returns @var{n} raised to the non-negative integer exponent @var{k}.
4712 @node Modular Arithmetic, Prime Numbers, Bit-Twiddling, Mathematical Packages
4713 @section Modular Arithmetic
4715 @code{(require 'modular)}
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.
4723 @defun symmetric:modulus n
4724 Returns @code{(quotient (+ -1 n) -2)} for positive odd integer @var{n}.
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.
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}.
4738 The rest of these functions assume normalized arguments; That is, the
4739 arguments are constrained by the following table:
4742 For all of these functions, if the first argument (@var{modulus}) is:
4745 Work as before. The result is between 0 and @var{modulus}.
4748 The arguments are treated as integers. An integer is returned.
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}
4758 If all the arguments are fixnums the computation will use only fixnums.
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.
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.
4770 @defun modular:negate modulus k2
4771 Returns (@minus{}@var{k2}) mod @var{modulus}.
4774 @defun modular:+ modulus k2 k3
4775 Returns (@var{k2} + @var{k3}) mod @var{modulus}.
4778 @defun modular:@minus{} modulus k2 k3
4779 Returns (@var{k2} @minus{} @var{k3}) mod @var{modulus}.
4782 @defun modular:* modulus k2 k3
4783 Returns (@var{k2} * @var{k3}) mod @var{modulus}.
4785 The Scheme code for @code{modular:*} with negative @var{modulus} is not
4786 completed for fixnum-only implementations.
4789 @defun modular:expt modulus k2 k3
4790 Returns (@var{k2} ^ @var{k3}) mod @var{modulus}.
4795 @node Prime Numbers, Random Numbers, Modular Arithmetic, Mathematical Packages
4796 @section Prime Numbers
4798 @code{(require 'factor)}
4805 @node Random Numbers, Fast Fourier Transform, Prime Numbers, Mathematical Packages
4806 @section Random Numbers
4808 @code{(require 'random)}
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.
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
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.
4832 @include randinex.txi
4835 @node Fast Fourier Transform, Cyclic Checksum, Random Numbers, Mathematical Packages
4836 @section Fast Fourier Transform
4838 @code{(require 'fft)}
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}.
4847 @code{fft-1} returns an array of complex numbers comprising the inverse
4848 Discrete Fourier Transform of @var{array}.
4851 @code{(fft-1 (fft @var{array}))} will return an array of values close to
4855 (fft '#(1 0+i -1 0-i 1 0+i -1 0-i)) @result{}
4857 #(0.0 0.0 0.0+628.0783185208527e-18i 0.0
4858 0.0 0.0 8.0-628.0783185208527e-18i 0.0)
4860 (fft-1 '#(0 0 0 0 0 0 8 0)) @result{}
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)
4867 @node Cyclic Checksum, Plotting, Fast Fourier Transform, Mathematical Packages
4868 @section Cyclic Checksum
4870 @code{(require 'make-crc)}
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.
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.
4883 @defunx make-port-crc generator
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.
4889 @defunx make-port-crc degree generator
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:
4899 (make-port-crc 32 #b00000100110000010001110110110111)
4902 Creates a procedure to calculate the P1003.2/D11.2 (POSIX.2) 32-bit
4903 checksum from the polynomial:
4906 32 26 23 22 16 12 11
4907 ( x + x + x + x + x + x + x +
4910 x + x + x + x + x + x + x + 1 ) mod 2
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"))
4924 @node Plotting, Root Finding, Cyclic Checksum, Mathematical Packages
4925 @section Plotting on Character Devices
4927 @code{(require 'charplot)}
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.
4935 @defvar charplot:height
4936 The number of rows to make the plot vertically.
4939 @defvar charplot:width
4940 The number of columns to make the plot horizontally.
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
4952 (set! charplot:height 19)
4953 (set! charplot:width 45)
4955 (define (make-points n)
4958 (cons (cons (/ n 6) (sin (/ n 6))) (make-points (1- n)))))
4960 (plot! (make-points 37) "x" "Sin(x)")
4963 Sin(x) ______________________________________________
4974 0|-------------------*--------------------------|
4983 |____________:_____._____:_____._____:_________|
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.
4997 @node Root Finding, Minimizing, Plotting, Mathematical Packages
4998 @section Root Finding
5000 @code{(require 'root)}
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.
5010 To find the closest integer to a given integers square root:
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))))
5019 (integer-sqrt 15) @result{} 4
5023 @defun integer-sqrt y
5024 Given a non-negative integer @var{y}, returns the rounded square-root of
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.
5035 If @var{prec} is instead a negative integer, @code{newton:find-root}
5036 returns the result of -@var{prec} iterations.
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.
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.
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.
5059 If @var{prec} is instead a negative integer, @code{laguerre:find-root}
5060 returns the result of -@var{prec} iterations.
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.
5071 If @var{prec} is instead a negative integer,
5072 @code{laguerre:find-polynomial-root} returns the result of -@var{prec}
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.
5083 If @var{x0} and @var{x1} are chosen such that they bracket a root, that is
5085 (or (< (f x0) 0 (f x1))
5086 (< (f x1) 0 (f x0)))
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.
5091 @code{secant:find-bracketed-root} will return @code{#f} unless @var{x0}
5092 and @var{x1} bracket a root.
5094 The secant method is used until a bracketing interval is found, at which point
5095 a modified @i{regula falsi} method is used.
5097 If @var{prec} is instead a negative integer, @code{secant:find-root}
5098 returns the result of -@var{prec} iterations.
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.
5107 @node Minimizing, Commutative Rings, Root Finding, Mathematical Packages
5110 @code{(require 'minimize)}
5114 @include minimize.txi
5116 @node Commutative Rings, Determinant, Minimizing, Mathematical Packages
5117 @section Commutative Rings
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.
5124 @code{(require 'commutative-ring)}
5125 @ftindex commutative-ring
5126 @cindex ring, commutative
5128 The @dfn{commutative-ring} package makes the procedures @code{+},
5129 @code{-}, @code{*}, @code{/}, and @code{^} @dfn{careful} in the sense
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
5142 Or just @code{(require 'self-set)}. Now try some sample expressions:
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)
5155 Associative rules have been applied and repeated addition and
5156 multiplication converted to multiplication and exponentiation.
5158 We can enable distributive rules, thus expanding to sum of products
5161 (set! *ruleset* (combined-rulesets distribute* distribute/))
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))
5175 Use of this package is not restricted to simple arithmetic expressions:
5178 (require 'determinant)
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))
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.
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
5195 @heading Rules and Rulesets
5197 The @dfn{commutative-ring} package allows control of ring properties
5198 through the use of @dfn{rulesets}.
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.
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.
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
5226 Two rulesets are defined by this package.
5228 @defvr Constant distribute*
5229 Contain the ruleset to distribute multiplication over addition and
5231 @defvrx Constant distribute/
5232 Contain the ruleset to distribute division over addition and
5235 Take care when using both @var{distribute*} and @var{distribute/}
5236 simultaneously. It is possible to put @code{/} into an infinite loop.
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.
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}.
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.
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.
5262 The operations @code{+} and @code{*} are assumed commutative; hence both
5263 orders of arguments to @var{reduction} will be tried if necessary.
5265 The following rule is the definition for distributing @code{*} over
5272 (apply + (map (lambda (trm) (* trm exp2)) (cdr exp1))))))
5276 @heading How to Create a Commutative Ring
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.
5287 (cond ((and (= 2 (length list1))
5288 (eq? (car list1) (cadr list1)))
5290 ((not (term< (first list1) (last1 list1)))
5291 (apply n (reverse list1)))
5292 (else (cons 'n list1))))
5294 (define (s x y) (n x y))
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))))
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.
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)))
5330 Test the procedures to see if they work.
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)))
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))))
5361 (N*N (S a b) (S a b)) @result{} (m a b)
5364 Then register the rule for multiplying type N objects by type N objects.
5367 (cring:define-rule '* 'N 'N N*N))
5370 Now we are ready to compute!
5377 (- (* (S a f) (S d g)) (* (S a g) (S d f))))
5379 (- (* (S a g) (S d d)) (* (S a d) (S d g))))
5381 (- (* (S a d) (S d f)) (* (S a f) (S d d))))))
5384 (- (* (S a g) (S d f)) (* (S a f) (S d g))))
5386 (- (* (S a b) (S d g)) (* (S a g) (S d b))))
5388 (- (* (S a f) (S d b)) (* (S a b) (S d f))))))
5391 (- (* (S a d) (S d g)) (* (S a g) (S d d))))
5393 (- (* (S a g) (S d b)) (* (S a b) (S d g))))
5395 (- (* (S a b) (S d d)) (* (S a d) (S d b))))))
5398 (- (* (S a f) (S d d)) (* (S a d) (S d f))))
5400 (- (* (S a b) (S d f)) (* (S a f) (S d b))))
5402 (- (* (S a d) (S d b)) (* (S a b) (S d d))))))))
5403 (* (S b e) (S c a) (S e c)
5408 (- (+ (m a c e b d f g)
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)))
5420 @node Determinant, , Commutative Rings, Mathematical Packages
5421 @section Determinant
5423 @defun determinant square-matrix
5424 Returns the determinant of @var{square-matrix}.
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
5435 @node Database Packages, Other Packages, Mathematical Packages, Top
5436 @chapter Database Packages
5440 * Relational Database:: 'relational-database
5441 * Weight-Balanced Trees:: 'wt-tree
5444 @node Base Table, Relational Database, Database Packages, Database Packages
5447 A base table implementation using Scheme association lists is available
5448 as the value of the identifier @code{alist-table} after doing:
5450 @code{(require 'alist-table)}
5451 @ftindex alist-table
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.
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.
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:
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))
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.
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.
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.
5502 Calling the @code{close-base} (and possibly other) method on a
5503 @var{mutable?} database will cause @var{filename} to be written to.
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.
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.
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.
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
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
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}.
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
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.
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.
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
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.
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
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.
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}.
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.
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
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.
5627 Any other value matches only those keys @code{equal?} to it.
5632 The @var{key-dimension} and @var{column-types} arguments are needed to
5633 decode the combined-keys for matching with @var{match-keys}.
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.
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.
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
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.
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.
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.
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.
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.
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}.
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}.
5698 Scheme exact integer.
5702 @code{#t} or @code{#f}.
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
5709 @node Relational Database, Weight-Balanced Trees, Base Table, Database Packages
5710 @section Relational Database
5712 @code{(require 'relational-database)}
5713 @ftindex relational-database
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.
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
5732 @node Motivations, Creating and Opening Relational Databases, Relational Database, Relational Database
5733 @subsection Motivations
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.
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
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
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
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.
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.
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.
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.
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.
5801 Such standardization to a relational-like model brings many benefits:
5805 Tables, fields, domains, and types can be dealt with by name in
5808 The underlying database implementation can be changed (for
5809 performance or other reasons) by changing a single line of code.
5811 The formats of tables can be easily extended or changed without
5814 Consistency checks are specified as part of the table descriptions.
5815 Changes in checks need only occur in one place.
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.
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.
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.
5829 Scheme's latent types mesh well with the strict typing and logical
5830 requirements of the relational model.
5832 Portable formats allow easy interchange of data. The included table
5833 descriptions help prevent misinterpretation of format.
5836 @node Creating and Opening Relational Databases, Relational Database Operations, Motivations, Relational Database
5837 @subsection Creating and Opening Relational Databases
5839 @defun make-relational-system base-table-implementation
5841 Returns a procedure implementing a relational database using the
5842 @var{base-table-implementation}.
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:
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))
5860 (create-alist-database "mydata.db"))
5865 What follows are the descriptions of the methods available from
5866 relational system returned by a call to @code{make-relational-system}.
5868 @defun create-database filename
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}
5881 @defun open-database filename mutable?
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.
5892 @node Relational Database Operations, Table Operations, Creating and Opening Relational Databases, Relational Database
5893 @subsection Relational Database Operations
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:
5902 (create-alist-database "mydata.db"))
5903 (define telephone-table-desc
5904 ((my-database 'create-table) 'telephone-table-desc))
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.
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
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.
5932 @defun table-exists? table-name
5933 Returns @code{#t} if @var{table-name} exists in the system catalog,
5934 otherwise returns @code{#f}.
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}.
5944 These methods will be present only in databases which are
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.
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}.
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
5965 @defun create-view ??
5966 @defunx project-table ??
5967 @defunx restrict-table ??
5968 @defunx cart-prod-tables ??
5969 Not yet implemented.
5972 @node Table Operations, Catalog Representation, Relational Database Operations, Relational Database
5973 @subsection Table Operations
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:
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
5989 (and (string? d) (> (string-length d) 2)
5992 (memv c '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
5993 #\+ #\( #\ #\) #\-)))
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.
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
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.
6018 ((plat 'get 'processor) 'djgpp) @result{} i386
6019 ((plat 'get 'processor) 'be-os) @result{} #f
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
6030 ((plat 'get* 'processor)) @result{}
6031 (i386 8086 i386 8086 i386 i386 8086 m68000
6032 m68000 m68000 m68000 m68000 powerpc)
6034 ((plat 'get* 'processor) #f) @result{}
6035 (i386 8086 i386 8086 i386 i386 8086 m68000
6036 m68000 m68000 m68000 m68000 powerpc)
6038 (define (a-key? key)
6039 (char=? #\a (string-ref (symbol->string key) 0)))
6041 ((plat 'get* 'processor) a-key?) @result{}
6042 (m68000 m68000 m68000 m68000 m68000 powerpc)
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)
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.
6056 ((plat 'row:retrieve) 'linux) @result{} (linux i386 linux gcc)
6057 ((plat 'row:retrieve) 'multics) @result{} #f
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.
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 -))
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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}.
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:
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.
6162 Any other value matches only those keys @code{equal?} to it.
6167 Subsequent operations to this table will signal an error.
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.
6179 @defvrx Constant primary-limit
6180 Returns the number of primary keys fields in the relations in this
6184 @node Catalog Representation, Unresolved Issues, Table Operations, Relational Database
6185 @subsection Catalog Representation
6188 Each database (in an implementation) has a @dfn{system catalog} which
6189 describes all the user accessible tables in that database (including
6193 The system catalog base table has the following fields. @code{PRI}
6194 indicates a primary key for that table.
6199 column-limit the highest column number
6200 coltab-name descriptor table name
6201 bastab-id data base table identifier
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.
6211 Descriptors for base tables (not views) are tables (pointed to by
6212 system catalog). Descriptor (base) tables have the fields:
6216 PRI column-number sequential integers from 1
6217 primary-key? boolean TRUE for primary key components
6219 column-integrity-rule
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.
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!
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:
6246 domain-integrity-rule
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.
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.
6264 The types for which support is planned are:
6275 foreign-key <table-name>
6277 virtual <expression>
6281 @node Unresolved Issues, Database Utilities, Catalog Representation, Relational Database
6282 @subsection Unresolved Issues
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.
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.
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.
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.
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.
6315 There are 2 scope issues that must be resolved for multiprocess
6316 transaction boundaries:
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
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.
6339 @node Database Utilities, Database Reports, Unresolved Issues, Relational Database
6340 @subsection Database Utilities
6342 @code{(require 'database-utilities)}
6343 @ftindex database-utilities
6346 This enhancement wraps a utility layer on @code{relational-database}
6350 Automatic loading of the appropriate base-table package when opening a
6353 Automatic execution of initialization commands stored in database.
6355 Transparent execution of database commands stored in @code{*commands*}
6360 Also included are utilities which provide:
6363 Data definition from Scheme lists and
6368 for any SLIB relational database.
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}.
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.
6385 @defunx open-database! filename
6386 @defunx open-database! filename base-table-type
6387 Returns @emph{mutable} open enchanced relational database @dots{}
6391 The table @code{*commands*} in an @dfn{enhanced} relational-database has
6392 the fields (with domains):
6396 parameters parameter-list
6397 procedure expression
6398 documentation string
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:
6414 arity parameter-arity
6416 defaulter expression
6418 documentation string
6422 The @code{arity} field can take the values:
6426 Requires a single parameter of the specified domain.
6428 A single parameter of the specified domain or zero parameters is
6431 A single boolean parameter or zero parameters (in which case @code{#f}
6432 is substituted) is acceptable.
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
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
6443 The @code{domain} field specifies the domain which a parameter or
6444 parameters in the @code{index}th field must satisfy.
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.
6453 @subsubheading Invoking Commands
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.
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.
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.
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:
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.
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.
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.
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.
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
6508 A list of lists of @code{(@r{alias} @r{parameter-name})}. There can be
6509 more than one alias per @var{parameter-name}.
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}).
6518 (require 'database-utilities)
6519 @ftindex database-utilities
6520 (require 'fluid-let)
6522 (require 'parameters)
6527 (define my-rdb (create-database #f 'alist-table))
6529 (define-tables my-rdb
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")))
6545 ((parameter-index uint))
6553 ("optional-number" 4)
6558 ((parameters parameter-list)
6559 (parameter-names parameter-name-translation)
6560 (procedure expression)
6561 (documentation string))
6565 (lambda (rdb) (lambda args (print args)))
6566 "test command arguments"))))
6568 (define (dbutil:serve-command-line rdb command-table
6570 (set! argv (if (vector? argv) (vector->list argv) argv))
6571 ((make-command-server rdb command-table)
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)))))
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))
6586 (dbutil:serve-command-line
6587 my-rdb 'my-commands 'foo (length opts) opts)))
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)
6614 Usage: cmd [OPTION ARGUMENT ...] ...
6617 -o, --optional[=]<number>
6618 -n, --nary[=]<symbols> ...
6619 -N, --nary1[=]<symbols> ...
6620 -s, --single[=]<string>
6622 ERROR: getopt->parameter-list "unrecognized option" "-?"
6625 Some commands are defined in all extended relational-databases. The are
6626 called just like @ref{Relational Database Operations}.
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}.
6633 For the fields and layout of the domain table, @xref{Catalog
6634 Representation}. Currently, these fields are
6641 domain-integrity-rule
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.
6653 (for-each (build 'add-domain)
6655 (lambda (x) (or (not x) (string? x)))
6658 (filename #f #f string #f)
6659 (build-whats #f #f symbol #f)))
6663 @defun delete-domain domain-name
6664 Removes and returns the @var{domain-name} row from the @dfn{domains}
6668 @defun domain-checker domain
6669 Returns a procedure to check an argument for conformance to domain
6673 @subsubheading Defining Tables
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:
6680 (@r{<name>} @r{<descriptor-name>} @r{<descriptor-name>} @r{<rows>})
6684 (@r{<name>} @r{<primary-key-fields>} @r{<other-fields>} @r{<rows>})
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
6693 @r{<primary-key-fields>} and @r{<other-fields>} are lists of field
6694 descriptors of the form:
6697 (@r{<column-name>} @r{<domain>})
6701 (@r{<column-name>} @r{<domain>} @r{<column-integrity-rule>})
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
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.
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.
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.
6727 (require 'database-utilities)
6728 @ftindex database-utilities
6729 (define my-rdb (create-database "foo.db" 'alist-table))
6731 (define-tables my-rdb
6734 ((parameters parameter-list)
6735 (procedure expression)
6736 (documentation string))
6740 (lambda (rdb) (lambda specs (apply define-tables rdb specs)))
6741 "Create or Augment tables from list of specs")
6745 (lambda (rdb) (display "Welcome") (newline) rdb)
6748 ((my-rdb 'define-tables)
6751 ((also-ran processor-family))
6760 ((processor processor-family)
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))))
6777 ((my-rdb 'close-database))
6779 (set! my-rdb (open-database "foo.db" 'alist-table))
6784 @subsubheading Listing Tables
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.
6792 The list returned by @code{list-table-definition}, when passed as an
6793 argument to @code{define-tables}, will recreate the table.
6797 @node Database Reports, Database Browser, Database Utilities, Relational Database
6798 @subsection Database Reports
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}.
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
6816 The table is created as ascii text and written to that port.
6818 The table is created as ascii text and written to the file named by
6821 @var{destination} is the primary key for a row in the table named *printers*.
6824 The report is prepared as follows:
6828 @code{Format} (@pxref{Format}) is called with the @code{header} field
6829 and the (list of) @code{column-names} of the table.
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}.
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
6843 A new page is output.
6845 This entire process repeats until all the rows are output.
6849 Each row in the table *reports* has the fields:
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.
6861 A @code{format} string. For each row in the table, @code{format} is
6862 called with this string and the row.
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
6869 Each row in the table *printers* has the fields:
6874 @item print-procedure
6875 The procedure to call to actually print.
6880 @node Database Browser, , Database Reports, Relational Database
6881 @subsection Database Browser
6883 (require 'database-browse)
6885 @deffn Procedure browse database
6887 Prints the names of all the tables in @var{database} and sets browse's
6888 default to @var{database}.
6890 @deffnx Procedure browse
6892 Prints the names of all the tables in the default database.
6894 @deffnx Procedure browse table-name
6896 For each record of the table named by the symbol @var{table-name},
6897 prints a line composed of all the field values.
6899 @deffnx Procedure browse pathname
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.
6904 @deffnx Procedure browse database table-name
6906 Sets browse's default to @var{database} and prints the records of the
6907 table named by the symbol @var{table-name}.
6909 @deffnx Procedure browse pathname table-name
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}.
6917 @node Weight-Balanced Trees, , Relational Database, Database Packages
6918 @section Weight-Balanced Trees
6920 @code{(require 'wt-tree)}
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
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.
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.
6948 Operations to find and remove minimum element make weight balanced trees
6949 simple to use for priority queues.
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.
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
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
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.
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?}.
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
7006 (load-option 'wt-tree)
7011 once before calling any of the procedures defined here.
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::
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
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.
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}:
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))
7051 Two key values are assumed to be equal if neither is less than the other
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}.
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
7066 (define number-wt-type (make-wt-tree-type <))
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
7075 (define string-wt-type (make-wt-tree-type string<?))
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.
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.
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:
7100 (lambda (type alist)
7101 (let ((tree (make-wt-tree type)))
7102 (for-each (lambda (association)
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
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.
7121 @deffn {procedure+} wt-tree? object
7122 Returns @code{#t} if @var{object} is a weight-balanced tree, otherwise
7126 @deffn {procedure+} wt-tree/empty? wt-tree
7127 Returns @code{#t} if @var{wt-tree} contains no associations, otherwise
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.
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
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}.
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}.
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}.
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}.
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}.
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
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
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}.
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}.
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.
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.
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.
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
7252 A proper subset predicate can be constructed:
7255 (define (proper-subset? s1 s2)
7256 (and (wt-tree/subset? s1 s2)
7257 (< (wt-tree/size s1) (wt-tree/size s2))))
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
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
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.
7276 This procedure is equivalent to
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)))
7284 In the worst-case the time required by this operation is proportional to
7285 the size of the smaller tree.
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}.
7297 A sorted association list can be derived simply:
7300 (wt-tree/fold (lambda (key datum list)
7301 (cons (cons key datum) list))
7306 The data in the associations can be summed like this:
7309 (wt-tree/fold (lambda (key datum sum) (+ sum datum))
7315 @deffn {procedure+} wt-tree/for-each action wt-tree
7316 This procedure traverses the tree in-order, applying @var{action} to
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
7324 The example prints the tree:
7327 (wt-tree/for-each (lambda (key value)
7328 (display (list key value)))
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
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.
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.
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.
7359 Indexing can be used to find the median and maximum keys in the tree as
7363 median: (wt-tree/index @var{wt-tree}
7364 (quotient (wt-tree/size @var{wt-tree}) 2))
7366 maximum: (wt-tree/index @var{wt-tree}
7367 (-1+ (wt-tree/size @var{wt-tree})))
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.
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.
7391 These operations signal an error if the tree is empty.
7392 They could be written
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))
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
7409 (wt-tree/delete @var{wt-tree} (wt-tree/min @var{wt-tree}))
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
7422 (wt-tree/delete! @var{wt-tree} (wt-tree/min @var{wt-tree}))
7427 @node Other Packages, About SLIB, Database Packages, Top
7428 @chapter Other Packages
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::
7439 @node Data Structures, Procedures, Other Packages, Other Packages
7440 @section Data Structures
7446 * Array Mapping:: 'array-for-each
7447 * Association Lists:: 'alist
7449 * Portable Image Files:: 'pnm
7450 * Collections:: 'collect
7451 * Dynamic Data Type:: 'dynamic
7452 * Hash Tables:: 'hash-table
7453 * Hashing:: 'hash, 'sierpinski, 'soundex
7455 * Priority Queues:: 'priority-queue
7458 * Structures:: 'struct, 'structure
7464 @node Arrays, Array Mapping, Data Structures, Data Structures
7467 @code{(require 'array)}
7471 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
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}.
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
7483 (make-array 'foo 3 3) @equiv{} (make-array 'foo '(0 2) '(0 2))
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
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)
7499 (define freds-center
7500 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
7502 (array-ref freds-center 0 0)
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.
7512 @defun array-shape array
7513 @code{array-shape} returns a list of inclusive bounds. So:
7515 (array-shape (make-array 'foo 3 5))
7516 @result{} ((0 2) (0 4))
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:
7524 (array-dimensions (make-array 'foo 3 5))
7529 @deffn Procedure array-in-bounds? array index1 index2 @dots{}
7530 Returns @code{#t} if its arguments would be acceptable to
7534 @defun array-ref array index1 index2 @dots{}
7535 Returns the element at the @code{(@var{index1}, @var{index2})} element
7539 @deffn Procedure array-set! array new-value index1 index2 @dots{}
7542 @defun array-1d-ref array index
7543 @defunx array-2d-ref array index1 index2
7544 @defunx array-3d-ref array index1 index2 index3
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
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
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.
7559 An exercise left to the reader: implement the rest of APL.
7563 @node Array Mapping, Association Lists, Arrays, Data Structures
7564 @subsection Array Mapping
7566 @code{(require 'array-for-each)}
7567 @ftindex array-for-each
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.
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.
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})).
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.
7594 One can implement @var{array-indexes} as
7596 (define (array-indexes array)
7597 (let ((ra (apply make-array #f (array-shape array))))
7598 (array-index-map! ra (lambda x x))
7603 (define (apl:index-generator n)
7604 (let ((v (make-uniform-vector n 1)))
7605 (array-index-map! v (lambda (i) i))
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.
7618 @node Association Lists, Byte, Array Mapping, Data Structures
7619 @subsection Association Lists
7621 @code{(require 'alist)}
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.
7629 Alist functions can be used with a secondary index method such as hash
7630 tables for improved performance.
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
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}.
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
7653 (define put (alist-associator string-ci=?))
7655 (set! alist (put alist "Foo" 9))
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
7665 (define rem (alist-remover string-ci=?))
7666 (set! alist (rem alist "foo"))
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.
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
7682 @node Byte, Portable Image Files, Association Lists, Data Structures
7685 @code{(require 'byte)}
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}.
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.
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}
7704 and returns an unspecified value. @c <!>
7708 @deffn Function make-bytes k
7709 @deffnx Function make-bytes k byte
7711 @code{Make-bytes} returns a newly allocated byte-array of
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.
7719 @deffn Function bytes-length bytes
7721 @code{bytes-length} returns length of byte-array @var{bytes}.
7722 @findex bytes-length
7726 @deffn Function write-byte byte
7727 @deffnx Function write-byte byte port
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
7737 @deffn Function read-byte
7738 @deffnx Function read-byte port
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
7749 @deffn Function bytes byte @dots{}
7751 Returns a newly allocated byte-array composed of the arguments.
7755 @deffn Function bytes->list bytes
7756 @deffnx Function list->bytes bytes
7758 @code{Bytes->list} returns a newly allocated list of the
7760 bytes that make up the given byte-array. @code{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
7766 inverses so far as @code{equal?} is concerned.
7771 @node Portable Image Files, Collections, Byte, Data Structures
7772 @subsection Portable Image Files
7774 @code{(require 'pnm)}
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:
7781 A symbol describing the type of the file named by @var{path}.
7783 The image width in pixels.
7785 The image height in pixels.
7787 The maximum value of pixels assume in the file.
7790 The current set of file-type symbols is:
7794 Black-and-White image; pixel values are 0 or 1.
7797 Gray (monochrome) image; pixel values are from 0 to @var{maxval}
7798 specified in file header.
7801 RGB (full color) image; red, green, and blue interleaved pixel values
7802 are from 0 to @var{maxval}
7807 @deffn Function pnm:image-file->array path array
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.
7813 @deffnx Function pnm:image-file->array path
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.
7820 @deffn Procedure pnm:array-write type array maxval path
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}.
7830 @node Collections, Dynamic Data Type, Portable Image Files, Data Structures
7831 @subsection Collections
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!
7837 @code{(require 'collect)}
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).
7846 New types of collections may be defined as YASOS objects (@pxref{Yasos}).
7847 They must support the following operations:
7850 @code{(collection? @var{self})} (always returns @code{#t});
7853 @code{(size @var{self})} returns the number of elements in the collection;
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
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
7866 @code{(gen-keys @var{self})} is like @code{gen-elts}, but yields the
7867 collection's keys in order.
7870 They might support specialized @code{for-each-key} and
7871 @code{for-each-elt} operations.
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?}.
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
7892 (map-elts + (list 1 2 3) (vector 1 2 3))
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
7905 (map-keys + (list 1 2 3) (vector 1 2 3))
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.
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
7921 @code{(require 'common-list-functions)} (@pxref{Common List
7923 @ftindex common-list-functions
7927 (reduce + 0 (vector 1 2 3))
7929 (reduce union '() '((a b c) (b c d) (d a)))
7930 @result{} (c b d a).
7934 @defun any? pred . collections
7935 A generalization of the list-based @code{some} (@pxref{Lists as
7936 sequences}) to collections.
7940 (any? odd? (list 2 3 4 5))
7945 @defun every? pred . collections
7946 A generalization of the list-based @code{every} (@pxref{Lists as
7947 sequences}) to collections.
7951 (every? collection? '((1 2) #(1 2)))
7956 @defun empty? collection
7957 Returns @code{#t} iff there are no elements in @var{collection}.
7959 @code{(empty? @var{collection}) @equiv{} (zero? (size @var{collection}))}
7962 @defun size collection
7963 Returns the number of elements in @var{collection}.
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
7972 Here is a sample collection: @code{simple-table} which is also a
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
7980 (define (MAKE-SIMPLE-TABLE)
7981 (let ( (table (list)) )
7985 ((SIZE self) (size table))
7986 ((PRINT self port) (format port "#<SIMPLE-TABLE>"))
7987 ((LOOKUP self key failure-object)
7989 ((assq key table) => cdr)
7990 (else failure-object)
7992 ((ASSOCIATE! self key value)
7995 => (lambda (bucket) (set-cdr! bucket value) key))
7997 (set! table (cons (cons key value) table))
8000 ((REMOVE! self key);; returns old value
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))
8009 (let loop ( (last table) (this (cdr table)) )
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))
8019 (loop (cdr last) (cdr this)))
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)
8029 ((FOR-EACH-ELT self proc)
8030 (for-each (lambda (bucket) (proc (cdr bucket))) table)
8039 @node Dynamic Data Type, Hash Tables, Collections, Data Structures
8040 @subsection Dynamic Data Type
8042 @code{(require 'dynamic)}
8045 @defun make-dynamic obj
8046 Create and returns a new @dfn{dynamic} whose global value is @var{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
8055 @defun dynamic-ref dyn
8056 Return the value of the given dynamic in the current dynamic
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.
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.
8074 The @code{dynamic-bind} macro is not implemented.
8079 @node Hash Tables, Hashing, Dynamic Data Type, Data Structures
8080 @subsection Hash Tables
8082 @code{(require 'hash-table)}
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
8093 A hash table is a vector of association lists.
8095 @defun make-hash-table k
8096 Returns a vector of @var{k} empty (association) lists.
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
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
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}.
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}
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
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.
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
8148 @node Hashing, Object, Hash Tables, Data Structures
8151 @code{(require 'hash)}
8154 These hashing functions are for use in quickly classifying objects.
8155 Hash tables use these functions.
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
8165 For @code{hashq}, @code{(eq? obj1 obj2)} implies @code{(= (hashq obj1 k)
8168 For @code{hashv}, @code{(eqv? obj1 obj2)} implies @code{(= (hashv obj1 k)
8171 For @code{hash}, @code{(equal? obj1 obj2)} implies @code{(= (hash obj1 k)
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
8181 @code{(require 'sierpinski)}
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.
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.)
8195 Example use: Make an indexer (hash-function) for integer points lying in
8196 square of integer grid points [0,99]x[0,99]:
8198 (define space-key (make-sierpinski-indexer 100))
8200 Now let's compute the index of some points:
8202 (space-key 24 78) @result{} 9206
8203 (space-key 23 80) @result{} 9172
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.
8212 Example applications:
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.
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.)
8238 @code{(require 'soundex)}
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.
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.
8251 See Knuth, Vol. 3 @cite{Sorting and searching}, pp 391--2
8253 To manage unusual inputs, @code{soundex} omits all non-alphabetic
8254 characters. Consequently, in this implementation:
8257 (soundex <string of blanks>) @result{} ""
8258 (soundex "") @result{} ""
8261 Examples from Knuth:
8264 (map soundex '("Euler" "Gauss" "Hilbert" "Knuth"
8265 "Lloyd" "Lukasiewicz"))
8266 @result{} ("E460" "G200" "H416" "K530" "L300" "L222")
8268 (map soundex '("Ellery" "Ghosh" "Heilbronn" "Kant"
8269 "Ladd" "Lissajous"))
8270 @result{} ("E460" "G200" "H416" "K530" "L300" "L222")
8273 Some cases in which the algorithm fails (Knuth):
8276 (map soundex '("Rogers" "Rodgers")) @result{} ("R262" "R326")
8278 (map soundex '("Sinclair" "St. Clair")) @result{} ("S524" "S324")
8280 (map soundex '("Tchebysheff" "Chebyshev")) @result{} ("T212" "C121")
8285 @node Object, Priority Queues, Hashing, Data Structures
8286 @subsection Macroless Object System
8290 @node Priority Queues, Queues, Object, Data Structures
8291 @subsection Priority Queues
8293 @code{(require 'priority-queue)}
8294 @ftindex priority-queue
8296 @defun make-heap pred<?
8297 Returns a binary heap suitable which can be used for priority queue
8301 @defun heap-length heap
8302 Returns the number of elements in @var{heap}.
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.
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.
8316 The algorithm for priority queues was taken from @cite{Introduction to
8317 Algorithms} by T. Cormen, C. Leiserson, R. Rivest. 1989 MIT Press.
8321 @node Queues, Records, Priority Queues, Data Structures
8324 @code{(require 'queue)}
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.
8332 Returns a new, empty queue.
8336 Returns @code{#t} if @var{obj} is a queue.
8339 @defun queue-empty? q
8340 Returns @code{#t} if the queue @var{q} is empty.
8343 @deffn Procedure queue-push! q datum
8344 Adds @var{datum} to the front of queue @var{q}.
8347 @deffn Procedure enquque! q datum
8348 Adds @var{datum} to the rear of queue @var{q}.
8351 All of the following functions raise an error if the queue @var{q} is
8354 @defun queue-front q
8355 Returns the datum at the front of the queue @var{q}.
8359 Returns the datum at the rear of the queue @var{q}.
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
8373 @node Records, Structures, Queues, Data Structures
8376 @code{(require 'record)}
8379 The Record package provides a facility for user to define their own
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.
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
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}.
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.
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.
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
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}.
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
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.
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
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.
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.
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.
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
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}.
8504 @node Structures, , Records, Data Structures
8505 @subsection Structures
8507 @code{(require 'struct)} (uses defmacros)
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
8515 Matthew McDonald <mafm@@cs.uwa.edu.au> added field setters.
8517 @defmac define-record tag (var1 var2 @dots{})
8518 Defines several functions pertaining to record-name @var{tag}:
8520 @defun make-@var{tag} var1 var2 @dots{}
8522 @defun @var{tag}? obj
8524 @defun @var{tag}->var1 obj
8526 @defun @var{tag}->var2 obj
8529 @defun set-@var{tag}-var1! obj val
8531 @defun set-@var{tag}-var2! obj val
8535 Here is an example of its use.
8538 (define-record term (operator left right))
8539 @result{} #<unspecified>
8540 (define foo (make-term 'plus 1 2))
8544 (set-term-left! foo 2345)
8545 @result{} #<unspecified>
8551 @defmac variant-case exp (tag (var1 var2 @dots{}) body) @dots{}
8552 executes the following for the matching clause:
8555 ((lambda (@var{var1} @var{var} @dots{}) @var{body})
8556 (@var{tag->var1} @var{exp})
8557 (@var{tag->var2} @var{exp}) @dots{})
8562 @node Procedures, Standards Support, Data Structures, Other Packages
8565 Anything that doesn't fall neatly into any of the other categories winds
8569 * Common List Functions:: 'common-list-functions
8570 * Tree Operations:: 'tree
8571 * Type Coercion:: 'coerce
8572 * Chapter Ordering:: 'chapter-order
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.
8584 @node Common List Functions, Tree Operations, Procedures, Procedures
8585 @subsection Common List Functions
8587 @code{(require 'common-list-functions)}
8588 @ftindex common-list-functions
8590 The procedures below follow the Common LISP equivalents apart from
8591 optional arguments in some cases.
8594 * List construction::
8596 * Lists as sequences::
8597 * Destructive list operations::
8598 * Non-List functions::
8602 @node List construction, Lists as sets, Common List Functions, Common List Functions
8603 @subsubsection List construction
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
8613 @result{} (#<unspecified> #<unspecified> #<unspecified>)
8615 @result{} (foo foo foo foo foo)
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
8631 (list* @var{args} '())
8632 @equiv{} (list @var{args})
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.
8645 (copy-list '(foo foo foo))
8646 @result{} (foo foo foo)
8647 (define q '(foo bar baz bang))
8651 (define r (copy-list q))
8657 (eq? bar (car (copy-list (list bar 'foo))))
8667 @node Lists as sets, Lists as sequences, List construction, Common List Functions
8668 @subsubsection Lists as sets
8670 @code{eqv?} is used to test for membership by procedures which treat
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})}.
8680 (adjoin 'baz '(bar baz bang))
8681 @result{} (bar baz bang)
8682 (adjoin 'foo '(bar baz bang))
8683 @result{} (foo bar baz bang)
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.
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)
8701 @defun intersection l1 l2
8702 @code{intersection} returns all elements that are in both @var{l1} and
8707 (intersection '(1 2 3 4) '(3 4 5 6))
8709 (intersection '(1 2 3 4) '(5 6 7 8))
8714 @defun set-difference l1 l2
8715 @code{set-difference} returns all elements that are in @var{l1} but not
8720 (set-difference '(1 2 3 4) '(3 4 5 6))
8722 (set-difference '(1 2 3 4) '(1 2 3 4 5 6))
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}.
8734 (member-if vector? '(1 2 3 4))
8736 (member-if number? '(1 2 3 4))
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.
8752 (some odd? '(1 2 3 4))
8755 (some odd? '(2 4 6 8))
8758 (some > '(2 3) '(1 4))
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}
8770 (every even? '(1 2 3 4))
8773 (every even? '(2 4 6 8))
8776 (every > '(2 3) '(1 4))
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
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}
8794 (notevery even? '(1 2 3 4))
8797 (notevery even? '(2 4 6 8))
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}.
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}.
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
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.
8832 (find-if number? '(foo 1 bar 2))
8835 (find-if number? '(foo bar baz bang))
8838 (find-if symbol? '(1 2 foo bar))
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.
8851 (remove 1 '(1 2 1 3 1 4 1 5))
8854 (remove 'foo '(bar baz bang))
8855 @result{} (bang baz bar)
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
8866 (remove-if number? '(1 2 3 4))
8869 (remove-if even? '(1 2 3 4 5 6 7 8))
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
8881 (remove-if-not number? '(foo bar baz))
8883 (remove-if-not odd? '(1 2 3 4 5 6 7 8))
8888 @defun has-duplicates? lst
8889 returns @code{#t} if 2 members of @var{lst} are @code{equal?}, @code{#f}
8894 (has-duplicates? '(1 2 3 4))
8897 (has-duplicates? '(2 4 3 4))
8902 The procedure @code{remove-duplicates} uses @code{member} (rather than
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?}.
8911 (remove-duplicates '(1 2 3 4))
8914 (remove-duplicates '(2 4 3 4))
8920 @node Lists as sequences, Destructive list operations, Lists as sets, Common List Functions
8921 @subsubsection Lists as sequences
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}.
8929 (position 'foo '(foo bar baz bang))
8931 (position 'baz '(foo bar baz bang))
8933 (position 'oops '(foo bar baz bang))
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.
8949 (reduce + '(1 2 3 4))
8951 (define (bad-sum . l) (reduce + l))
8953 @equiv{} (reduce + (1 2 3 4))
8954 @equiv{} (+ (+ (+ 1 2) 3) 4)
8957 @equiv{} (reduce + ())
8959 (reduce string-append '("hello" "cruel" "world"))
8960 @equiv{} (string-append (string-append "hello" "cruel") "world")
8961 @result{} "hellocruelworld"
8962 (reduce anything '())
8964 (reduce anything '(x))
8968 What follows is a rather non-standard implementation of @code{reverse}
8969 in terms of @code{reduce} and a combinator elsewhere called
8973 ;;; Contributed by Jussi Piitulainen (jpiitula@@ling.helsinki.fi)
8982 (reduce-init (commute cons) '() args)))
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}.
8996 (define (sum . l) (reduce-init + 0 l))
8998 @equiv{} (reduce-init + 0 (1 2 3 4))
8999 @equiv{} (+ (+ (+ (+ 0 1) 2) 3) 4)
9002 @equiv{} (reduce-init + 0 '())
9005 (reduce-init string-append "@@" '("hello" "cruel" "world"))
9007 (string-append (string-append (string-append "@@" "hello")
9010 @result{} "@@hellocruelworld"
9013 Given a differentiation of 2 arguments, @code{diff}, the following will
9014 differentiate by any number of variables.
9016 (define (diff* exp . vars)
9017 (reduce-init diff exp vars))
9022 ;;; Real-world example: Insertion sort using reduce-init.
9024 (define (insert l item)
9027 (if (< (car l) item)
9028 (cons (car l) (insert (cdr l) item))
9030 (define (insertion-sort l) (reduce-init insert '() l))
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)
9044 @code{last} returns the last @var{n} elements of @var{lst}. @var{n}
9045 must be a non-negative integer.
9049 (last '(foo bar baz bang) 2)
9050 @result{} (baz bang)
9056 @defun butlast lst n
9057 @code{butlast} returns all but the last @var{n} elements of
9062 (butlast '(a b c d) 3)
9064 (butlast '(a b c d) 4)
9070 @code{last} and @code{butlast} split a list into two parts when given
9071 identical arugments.
9073 (last '(a b c d e) 2)
9075 (butlast '(a b c d e) 2)
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
9086 (nthcdr 2 '(a b c d))
9088 (nthcdr 0 '(a b c d))
9093 @defun butnthcdr n lst
9094 @code{butnthcdr} returns all but the nthcdr @var{n} elements of
9099 (butnthcdr 3 '(a b c d))
9101 (butnthcdr 4 '(a b c d))
9107 @code{nthcdr} and @code{butnthcdr} split a list into two parts when
9108 given identical arugments.
9110 (nthcdr 2 '(a b c d e))
9112 (butnthcdr 2 '(a b c d e))
9118 @node Destructive list operations, Non-List functions, Lists as sequences, Common List Functions
9119 @subsubsection Destructive list operations
9121 These procedures may mutate the list they operate on, but any such
9122 mutation is undefined.
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}).
9129 Example: You want to find the subsets of a set. Here's the obvious way:
9132 (define (subsets set)
9135 (append (mapcar (lambda (sub) (cons (car set) sub))
9136 (subsets (cdr set)))
9137 (subsets (cdr set)))))
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.
9148 @result{} (a b c d e f)
9150 @result{} (a b c d e f)
9153 @code{nconc} is the same as @code{append!} in @file{sc2.scm}.
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!}.
9162 (define foo '(a b c))
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
9173 (set! lst (nreverse lst))
9176 is the proper usage, not
9180 The example should suffice to show why this is the case.
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}.
9191 (define lst '(foo bar baz bang))
9193 @result{} (bar baz bang)
9195 @result{} (foo bar baz bang)
9197 (define lst '(1 2 3 4 5 6 7 8 9))
9198 (delete-if odd? lst)
9201 @result{} (1 2 4 6 8)
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
9208 (set! lst (delete el lst))
9211 is the proper usage, not
9215 The examples should suffice to show why this is the case.
9220 @node Non-List functions, , Destructive list operations, Common List Functions
9221 @subsubsection Non-List functions
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
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
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.)
9260 (atom? #(1 2)) ; dubious!
9266 @node Tree Operations, Type Coercion, Common List Functions, Procedures
9267 @subsection Tree operations
9269 @code{(require 'tree)}
9272 These are operations that treat lists a representations of trees.
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.
9282 @code{substq} and @code{substv} are similar, but test against @var{old}
9283 using @code{eq?} and @code{eqv?} respectively.
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))
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.
9305 (copy-tree (list bar 'foo))
9306 @result{} ((bar) foo)
9307 (eq? bar (car (copy-tree (list bar 'foo))))
9313 @node Type Coercion, Chapter Ordering, Tree Operations, Procedures
9314 @subsection Type Coercion
9315 @code{(require 'coerce)}
9321 @node Chapter Ordering, Sorting, Type Coercion, Procedures
9322 @subsection Chapter Ordering
9324 @code{(require 'chapter-order)}
9325 @ftindex chapter-order
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
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
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
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.
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.
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@}"
9367 @node Sorting, Topological Sort, Chapter Ordering, Procedures
9370 @code{(require 'sort)}
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).
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
9382 (merge predicate list1 list2)
9383 (merge! predicate list1 list2)
9384 (sort predicate list)
9385 (sort! predicate list)
9388 while MIT Scheme 7.1, following Common LISP, offers unstable
9390 (sort list predicate)
9395 (sort! list/vector predicate?)
9400 (sort list/vector predicate?)
9401 (sort! list/vector predicate?)
9404 Here is a comprehensive catalogue of the variations I have found.
9408 Both @code{sort} and @code{sort!} may be provided.
9410 @code{sort} may be provided without @code{sort!}.
9412 @code{sort!} may be provided without @code{sort}.
9414 Neither may be provided.
9416 The sequence argument may be either a list or a vector.
9418 The sequence argument may only be a list.
9420 The sequence argument may only be a vector.
9422 The comparison function may be expected to behave like @code{<}.
9424 The comparison function may be expected to behave like @code{<=}.
9426 The interface may be @code{(sort predicate? sequence)}.
9428 The interface may be @code{(sort sequence predicate?)}.
9430 The interface may be @code{(sort sequence &optional (predicate? <))}.
9432 The sort may be stable.
9434 The sort may be unstable.
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).
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
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.
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
9459 (and (f x y) (f y z)) @equiv{} (f x z)
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}.
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)}).
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.
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.
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.
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
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.
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
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
9517 (set! slist (sort! slist <))
9520 is the proper usage, not
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
9530 (define (keyed less? key)
9531 (lambda (x y) (less? (key x) (key y))))
9534 and then, when you would have written
9536 (sort a-sequence #'my-less :key #'my-key)
9539 in Common LISP, just write
9541 (sort! a-sequence (keyed my-less? my-key))
9546 @node Topological Sort, String-Case, Sorting, Procedures
9547 @subsection Topological Sort
9549 @code{(require 'topological-sort)} or @code{(require 'tsort)}
9550 @ftindex topological-sort
9554 The algorithm is inspired by Cormen, Leiserson and Rivest (1990)
9555 @cite{Introduction to Algorithms}, chapter 23.
9557 @defun tsort dag pred
9558 @defunx topological-sort dag pred
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.
9566 is one of @code{eq?}, @code{eqv?}, @code{equal?}, @code{=},
9567 @code{char=?}, @code{char-ci=?}, @code{string=?}, or @code{string-ci=?}.
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.
9574 Time complexity: O (|V| + |E|)
9576 Example (from Cormen):
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:
9588 (tsort '((shirt tie belt)
9593 (undershorts pants shoes)
9597 (socks undershorts pants shoes watch shirt belt tie jacket)
9603 @node String-Case, String Ports, Topological Sort, Procedures
9604 @subsection String-Case
9606 @code{(require 'string-case)}
9607 @ftindex string-case
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.
9615 @defun string-upcase! str
9616 @defunx string-downcase! str
9617 @defunx string-captialize! str
9618 The destructive versions of the functions above.
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}.
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).
9635 @node String Ports, String Search, String-Case, Procedures
9636 @subsection String Ports
9638 @code{(require 'string-port)}
9639 @ftindex string-port
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
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
9657 @node String Search, Line I/O, String Ports, Procedures
9658 @subsection String Search
9660 @code{(require 'string-search)}
9661 @ftindex string-search
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}.
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}.
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
9686 (substring? "rat" "pirate") @result{} 2
9687 (substring? "rat" "outrage") @result{} #f
9688 (substring? "" any-string) @result{} 0
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}.
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
9700 @deffnx Procedure find-string-from-port? str in-port char
9701 Searches up to the first occurrence of character @var{char} in
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})
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.
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.
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{}.
9726 @node Line I/O, Multi-Processing, String Search, Procedures
9727 @subsection Line I/O
9729 @code{(require 'line-i/o)}
9735 @node Multi-Processing, Metric Units, Line I/O, Procedures
9736 @subsection Multi-Processing
9738 @code{(require 'process)}
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}.
9745 @findex alarm-interrupt
9746 Until this is ported to another implementation, consider it an example
9747 of writing schedulers in Scheme.
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.
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
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}).
9769 @node Metric Units, , Multi-Processing, Procedures
9770 @subsection Metric Units
9772 @code{(require 'metric-units)}
9773 @ftindex metric-units
9775 @url{http://swissnet.ai.mit.edu/~jaffer/MIXF.html}
9777 @dfn{Metric Interchange Format} is a character string encoding for
9778 numerical values and units which:
9782 is unambiguous in all locales;
9785 uses only [TOG] "Portable Character Set" characters matching "Basic
9786 Latin" characters in Plane 0 of the Universal Character Set [UCS];
9789 is transparent to [UTF-7] and [UTF-8] UCS transformation formats;
9792 is human readable and writable;
9795 is machine readable and writable;
9798 incorporates SI prefixes and units;
9801 incorporates [ISO 6093] numbers; and
9804 incorporates [IEC 60027-2] binary prefixes.
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.
9811 Within a compound unit, each of the base and derived symbols can
9812 optionally have an attached SI prefix.
9814 Unit symbols formed from other unit symbols by multiplication are
9815 indicated by means of a dot (PERIOD, @samp{.}) placed between them.
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.
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
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.
9833 Compound prefix symbols, that is, prefix symbols formed by the
9834 juxtaposition of two or more prefix symbols, are not permitted.
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).
9843 A unit exponent follows the unit, separated by a CIRCUMFLEX (@samp{^}).
9844 Exponents may be positive or negative. Fractional exponents must be
9847 @subsubheading SI Prefixes
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
9863 @subsubheading Binary Prefixes
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).
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
9880 @subsubheading Unit Symbols
9883 Type of Quantity Name Symbol Equivalent
9884 ================ ==== ====== ==========
9886 time minute min = 60.s
9887 time hour h = 60.min
9889 frequency hertz Hz s^-1
9890 signaling rate baud Bd s^-1
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
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
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.
9948 Otherwise, @code{si:conversion-factor} returns:
9952 if neither @var{from-unit} nor @var{to-unit} is a syntactically valid
9955 if @var{from-unit} is not a syntactically valid unit.
9957 if @var{to-unit} is not a syntactically valid unit.
9959 if linear conversion (by a factor) is not possible.
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
9978 @node Standards Support, Session Support, Procedures, Other Packages
9979 @section Standards Support
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
9997 @node With-File, Transcripts, Standards Support, Standards Support
9998 @subsection With-File
10000 @code{(require 'with-file)}
10003 @defun with-input-from-file file thunk
10004 @defunx with-output-to-file file thunk
10005 Description found in R4RS.
10008 @node Transcripts, Rev2 Procedures, With-File, Standards Support
10009 @subsection Transcripts
10011 @code{(require 'transcript)}
10012 @ftindex transcript
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}.
10024 @node Rev2 Procedures, Rev4 Optional Procedures, Transcripts, Standards Support
10025 @subsection Rev2 Procedures
10027 @code{(require 'rev2-procedures)}
10028 @ftindex rev2-procedures
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
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
10041 0 <= @var{start1} <= @var{end1} <= (string-length @var{string1})
10042 0 <= @var{start2} <= @var{end1} - @var{start1} + @var{start2} <= (string-length @var{string2})
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).
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.
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}.
10060 @defun string-null? str
10061 @equiv{} @code{(= 0 (string-length @var{str}))}
10064 @deffn Procedure append! . pairs
10065 Destructively appends its arguments. Equivalent to @code{nconc}.
10073 Subtracts 1 from @var{n}.
10081 These are equivalent to the procedures of the same name but without the
10087 @node Rev4 Optional Procedures, Multi-argument / and -, Rev2 Procedures, Standards Support
10088 @subsection Rev4 Optional Procedures
10090 @code{(require 'rev4-optional-procedures)}
10091 @ftindex rev4-optional-procedures
10093 For the specification of these optional procedures,
10094 @xref{Standard procedures, , ,r4rs, Revised(4) Scheme}.
10096 @defun list-tail l p
10099 @defun string->list s
10102 @defun list->string l
10108 @deffn Procedure string-fill! s obj
10111 @defun list->vector l
10114 @defun vector->list s
10117 @deffn Procedure vector-fill! s obj
10124 @node Multi-argument / and -, Multi-argument Apply, Rev4 Optional Procedures, Standards Support
10125 @subsection Multi-argument / and -
10127 @code{(require 'mutliarg/and-)}
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
10135 @defun two-arg:/ n1 n2
10136 The original two-argument version of @code{/}.
10139 @defun / divident . divisors
10142 @defun two-arg:- n1 n2
10143 The original two-argument version of @code{-}.
10146 @defun - minuend . subtrahends
10153 @node Multi-argument Apply, Rationalize, Multi-argument / and -, Standards Support
10154 @subsection Multi-argument Apply
10156 @code{(require 'multiarg-apply)}
10157 @ftindex multiarg-apply
10160 For the specification of this optional form,
10161 @xref{Control features, , ,r4rs, Revised(4) Scheme}.
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.
10168 @defun apply proc . args
10175 @node Rationalize, Promises, Multi-argument Apply, Standards Support
10176 @subsection Rationalize
10178 @code{(require 'rationalize)}
10179 @ftindex rationalize
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.
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.
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.
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
10202 @t{(find-ratio 3/97 .0001) @result{} (3 97)
10203 (find-ratio 3/97 .001) @result{} (1 32)
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}.
10213 @t{(find-ratio-between 2/7 3/5) @result{} (1 2)
10214 (find-ratio-between -3/5 -2/7) @result{} (-1 2)
10220 @node Promises, Dynamic-Wind, Rationalize, Standards Support
10221 @subsection Promises
10223 @code{(require 'promise)}
10226 @defun make-promise proc
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}).
10238 @node Dynamic-Wind, Eval, Promises, Standards Support
10239 @subsection Dynamic-Wind
10241 @code{(require 'dynamic-wind)}
10242 @ftindex dynamic-wind
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.
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).
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).
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.
10268 @node Eval, Values, Dynamic-Wind, Standards Support
10271 @code{(require 'eval)}
10273 @defun eval expression environment-specifier
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}.
10286 (eval '(* 7 3) (scheme-report-environment 5))
10289 (let ((f (eval '(lambda (f x) (f x x))
10290 (null-environment))))
10296 @defun scheme-report-environment version
10297 @defunx null-environment version
10298 @defunx null-environment
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.
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.
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.
10321 @defun interaction-environment
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.
10331 Here are some more @code{eval} examples:
10335 @result{} #<unspecified>
10336 (define car 'volvo)
10337 @result{} #<unspecified>
10340 (eval 'car (interaction-environment))
10342 (eval 'car (scheme-report-environment 5))
10343 @result{} #<primitive-procedure car>
10344 (eval '(eval 'car (interaction-environment))
10345 (scheme-report-environment 5))
10347 (eval '(eval '(set! car 'buick) (interaction-environment))
10348 (scheme-report-environment 5))
10349 @result{} #<unspecified>
10352 (eval 'car (scheme-report-environment 5))
10353 @result{} #<primitive-procedure car>
10354 (eval '(eval 'car (interaction-environment))
10355 (scheme-report-environment 5))
10360 @node Values, , Eval, Standards Support
10363 @code{(require 'values)}
10366 @defun values obj @dots{}
10367 @code{values} takes any number of arguments, and passes (returns) them
10368 to its continuation.
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.
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
10386 @node Session Support, Extra-SLIB Packages, Standards Support, Other Packages
10387 @section Session Support
10390 * Repl:: Macros at top-level
10391 * Quick Print:: Loop-safe Output
10392 * Debug:: To err is human ...
10393 * Breakpoints:: Pause execution
10395 * System Interface:: 'system, 'getenv, and 'net-clients
10399 @node Repl, Quick Print, Session Support, Session Support
10402 @code{(require 'repl)}
10405 Here is a read-eval-print-loop which, given an eval, evaluates forms.
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}.
10415 @deffn Procedure repl:quit
10416 Exits from the invocation of @code{repl:top-level}.
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.
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}.
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:
10436 (repl:top-level macro:eval)
10439 @node Quick Print, Debug, Repl, Session Support
10440 @subsection Quick Print
10442 @code{(require 'qp)}
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
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.
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
10470 @code{*qp-width*} is the largest number of characters that @code{qp}
10474 @node Debug, Breakpoints, Quick Print, Session Support
10477 @code{(require 'debug)}
10481 Requiring @code{debug} automatically requires @code{trace} and
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:
10489 (define qpn (lambda args) @dots{})
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{}.
10506 @deffn Procedure break-all file @dots{}
10507 Breakpoints (@pxref{Breakpoints}) all procedures @code{define}d at
10508 top-level in @file{file} @dots{}.
10511 @node Breakpoints, Trace, Debug, Session Support
10512 @subsection Breakpoints
10514 @code{(require 'break)}
10518 If your Scheme implementation does not support @code{break} or
10519 @code{abort}, a message will appear when you @code{(require 'break)} or
10521 @code{(require 'debug)} telling you to type @code{(init-debug)}. This
10523 is in order to establish a top-level continuation. Typing
10524 @code{(init-debug)} at top level sets up a continuation for
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.
10534 Pops the topmost continuation off of the continuation stack and returns
10535 an unspecified value to it.
10537 @defunx continue arg1 @dots{}
10538 Pops the topmost continuation off of the continuation stack and returns
10539 @var{arg1} @dots{} to it.
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{}.
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.
10551 @defmac unbreak proc1 @dots{}
10552 Turns breakpoints off for its arguments.
10554 With no arguments, unbreaks all currently broken identifiers and returns
10555 a list of these formerly broken identifiers.
10558 These are @emph{procedures} for breaking. If defmacros are not natively
10559 supported by your implementation, these might be more convenient to use.
10562 @defunx breakf proc name
10565 (set! @var{symbol} (breakf @var{symbol}))
10570 (set! @var{symbol} (breakf @var{symbol} '@var{symbol}))
10575 (define @var{symbol} (breakf @var{function}))
10580 (define @var{symbol} (breakf @var{function} '@var{symbol}))
10584 @defun unbreakf proc
10587 (set! @var{symbol} (unbreakf @var{symbol}))
10591 @node Trace, System Interface, Breakpoints, Session Support
10592 @subsection Tracing
10594 @code{(require 'trace)}
10598 This feature provides three ways to monitor procedure invocations:
10602 Pushes the procedure-name when the procedure is called; pops when it
10605 Pushes the procedure-name and arguments when the procedure is called;
10606 pops when it returns.
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.
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}.
10619 @defun print-call-stack
10620 @defunx print-call-stack port
10621 Prints the call-stack to @var{port} or the current-error-port.
10625 @defmac trace proc1 @dots{}
10626 Traces the top-level named procedures given as arguments.
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.
10633 @defmac track proc1 @dots{}
10634 Traces the top-level named procedures given as arguments.
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.
10641 @defmac stack proc1 @dots{}
10642 Traces the top-level named procedures given as arguments.
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.
10649 @defmac untrace proc1 @dots{}
10650 Turns tracing, tracking, and off for its arguments.
10652 With no arguments, untraces all currently traced identifiers and returns
10653 a list of these formerly traced identifiers.
10656 @defmac untrack proc1 @dots{}
10657 Turns tracing, tracking, and off for its arguments.
10659 With no arguments, untracks all currently tracked identifiers and returns
10660 a list of these formerly tracked identifiers.
10663 @defmac unstack proc1 @dots{}
10664 Turns tracing, stacking, and off for its arguments.
10666 With no arguments, unstacks all currently stacked identifiers and returns
10667 a list of these formerly stacked identifiers.
10670 These are @emph{procedures} for tracing. If defmacros are not natively
10671 supported by your implementation, these might be more convenient to use.
10674 @defunx tracef proc name
10677 (set! @var{symbol} (tracef @var{symbol}))
10682 (set! @var{symbol} (tracef @var{symbol} '@var{symbol}))
10687 (define @var{symbol} (tracef @var{function}))
10692 (define @var{symbol} (tracef @var{function} '@var{symbol}))
10696 @defun untracef proc
10697 Removes tracing, tracking, or stacking for @var{proc}.
10700 (set! @var{symbol} (untracef @var{symbol}))
10705 @node System Interface, , Trace, Session Support
10706 @subsection System Interface
10709 If @code{(provided? 'getenv)}:
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.
10717 If @code{(provided? 'system)}:
10719 @defun system command-string
10720 Executes the @var{command-string} on the computer and returns the
10721 integer status code.
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.
10729 @code{(require 'net-clients)}
10730 @ftindex net-clients
10732 @include nclients.txi
10735 @node Extra-SLIB Packages, , Session Support, Other Packages
10736 @section Extra-SLIB Packages
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:
10742 Because it requires special hardware or software which is not universal.
10744 Because it is large and of limited interest to most Scheme users.
10746 Because it has copying terms different enough from the other SLIB
10747 packages that its inclusion would cause confusion.
10749 Because it is an application program, rather than a library module.
10751 Because I have been too busy to integrate it.
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
10762 is a portable debugger for Scheme (requires emacs editor).
10765 <A HREF="http://swissnet.ai.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz">
10767 http://swissnet.ai.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz
10772 swissnet.ai.mit.edu:/pub/scm/slib-psd1-3.tar.gz
10774 ftp.maths.tcd.ie:pub/bosullvn/jacal/slib-psd1-3.tar.gz
10776 ftp.cs.indiana.edu:/pub/scheme-repository/utl/slib-psd1-3.tar.gz
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
10789 <A HREF="http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html">
10791 http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html
10798 is an embedding of Prolog in Scheme.
10800 <A HREF="http://www.cs.rice.edu/CS/PLT/packages/schelog/">
10802 http://www.cs.rice.edu/CS/PLT/packages/schelog/
10809 is a Scheme program which converts text among the JIS, EUC, and Shift-JIS Japanese character sets.
10811 <A HREF="http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html">
10813 http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html
10820 @node About SLIB, Index, Other Packages, Top
10821 @chapter About SLIB
10825 More people than I can name have contributed to SLIB. Thanks to all of
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}
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.
10844 @node Installation, Porting, About SLIB, About SLIB
10845 @section Installation
10849 <A NAME="Installation">
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.
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.)
10866 You should check the definitions of @code{software-type},
10867 @code{scheme-implementation-version},
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.
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
10879 Multiple implementations of Scheme can all use the same SLIB directory.
10880 Simply configure each implementation's initialization file as outlined
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.
10889 @deftp Implementation VSCM
10891 From: Matthias Blume <blume@@cs.Princeton.EDU>
10892 Date: Tue, 1 Mar 1994 11:42:31 -0500
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.
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:
10906 @code{(load "vscm.init")}
10908 @code{(slib:dump "dumpfile")}
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.)
10919 @deftp Implementation Scheme48
10920 To make a Scheme48 image for an installation under @code{<prefix>},
10924 @code{cd} to the SLIB directory
10926 type @code{make prefix=<prefix> slib48}.
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.
10934 @deftp Implementation {PLT Scheme}
10935 @deftpx Implementation {DrScheme}
10936 @deftpx Implementation {MzScheme}
10938 Date: Mon, 2 Oct 2000 21:29:48 -0400 (EDT)
10939 From: Shriram Krishnamurthi <sk@@cs.brown.edu>
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.
10951 @node Porting, Coding Guidelines, Installation, About SLIB
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.}
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
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
10978 Please mail new working configuration files to @code{jaffer @@ ai.mit.edu}
10979 so that they can be included in the SLIB distribution.
10982 @node Coding Guidelines, Copyrights, Porting, About SLIB
10983 @section Coding Guidelines
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
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)}.
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
11002 Documentation should be provided in Emacs Texinfo format if possible,
11003 But documentation must be provided.
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
11009 @subheading Modifications
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).
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.
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.
11028 @node Copyrights, , Coding Guidelines, About SLIB
11029 @section Copyrights
11032 <A NAME="Copyrights">
11038 This section has instructions for SLIB authors regarding copyrights.
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.
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.
11048 @subheading Putting code into the Public Domain
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.
11055 I, @var{name}, hereby affirm that I have placed the software package
11056 @var{name} in the public domain.
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.
11064 @var{signature and date}
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.
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.
11080 @subheading Explicit copying terms
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:
11088 Arrange that your name appears in a copyright line for the appropriate
11089 year. Multiple copyright lines are acceptable.
11091 With your copyright line, specify any terms you require to be different
11092 from those already in the file.
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
11101 @subheading Example: Company Copyright Disclaimer
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:
11108 @var{employer} Corporation hereby disclaims all copyright
11109 interest in the program @var{program} written by @var{name}.
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.
11116 @var{signature and date},
11117 @var{name}, @var{title}, @var{employer} Corporation
11121 @node Index, , About SLIB, Top
11122 @c @node Procedure and Macro Index, Variable Index, About SLIB, Top
11123 @unnumbered Procedure and Macro Index
11125 This is an alphabetical list of all the procedures and macros in SLIB.
11129 @c @node Variable Index, Concept Index, Procedure and Macro Index, Top
11130 @unnumbered Variable Index
11132 This is an alphabetical list of all the global variables in SLIB.
11136 @c @node Concept Index, , Variable Index, Top
11137 @unnumbered Concept and Feature Index