[Top] [Contents] [Index] [ ? ]

Gambit-C

This manual documents Gambit-C. It covers release v4.6.0.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1. The Gambit-C system

The Gambit programming system is a full implementation of the Scheme language which conforms to the R4RS, R5RS and IEEE Scheme standards. It consists of two main programs: gsi, the Gambit Scheme interpreter, and gsc, the Gambit Scheme compiler.

Gambit-C is a version of the Gambit programming system in which the compiler generates portable C code, making the whole Gambit-C system and the programs compiled with it easily portable to many computer architectures for which a C compiler is available. With appropriate declarations in the source code the executable programs generated by the compiler run roughly as fast as equivalent C programs.

For the most up to date information on Gambit and add-on packages please check the Gambit web page at http://gambit.iro.umontreal.ca. The web page has links to the Gambit mailing list, the bug reporting system, and the source code repository.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.1 Accessing the system files

Files related to Gambit, such as executables, libraries and header files, are stored in multiple Gambit installation directories. Gambit may be installed on a system according to two different installation models.

In the first model there is a single directory where all the Gambit installation directories are stored. This central installation directory is typically /usr/local/Gambit-C under UNIX, /Library/Gambit-C under Mac OS X and C:/Program Files/Gambit-C under Microsoft Windows. This may have been overridden when the system was built with the command ‘configure --prefix=/my/Gambit-C’. If the system was built with the command ‘configure --enable-multiple-versions’ then the central installation directory is prefix/version, where version is the system version string (e.g. v4.6.0 for Gambit v4.6.0). Moreover, prefix/current will be a symbolic link which points to the central installation directory. In this model, the Gambit installation directory named X is simply the subdirectory X of the central installation directory.

In the second model some or all of the Gambit installation directories are stored in installation specific directories. The location of these directories is assigned when the system is built using the command ‘configure --bindir=/my/bin --includedir=/my/include --libdir=/my/lib’.

The advantage of the first model is that it is easy to have multiple versions of Gambit coexist and to remove all the files of a given version. However, the second model may be necessary to conform to the package installation conventions of some operating systems.

Executable programs such as the interpreter gsi and compiler gsc can be found in the bin installation directory. Adding this directory to the PATH environment variable allows these programs to be started by simply entering their name. This is done automatically by the Mac OS X and Microsoft Windows installers.

The runtime library is located in the lib installation directory. When the system’s runtime library is built as a shared-library (with the command ‘configure --enable-shared’) all programs built with Gambit-C, including the interpreter and compiler, need to find this library when they are executed and consequently this directory must be in the path searched by the system for shared-libraries. This path is normally specified through an environment variable which is LD_LIBRARY_PATH on most versions of UNIX, LIBPATH on AIX, SHLIB_PATH on HPUX, DYLD_LIBRARY_PATH on Mac OS X, and PATH on Microsoft Windows. If the shell is sh, the setting of the path can be made for a single execution by prefixing the program name with the environment variable assignment, as in:

 
$ LD_LIBRARY_PATH=/usr/local/Gambit-C/lib gsi

A similar problem exists with the Gambit header file gambit.h, located in the include installation directory. This header file is needed for compiling Scheme programs with the Gambit-C compiler. When the C compiler is being called explicitly it may be necessary to use a -I<dir> command line option to indicate where to find header files and a -L<dir> command line option to indicate where to find libraries.

Access to both of these files can be simplified by creating a link to them in the appropriate system directories (special privileges may however be required):

 
$ ln -s /usr/local/Gambit-C/lib/libgambc.a /usr/lib # name may vary
$ ln -s /usr/local/Gambit-C/include/gambit.h /usr/include

Alternatively these files can be copied or linked in the directory where the C compiler is invoked (this requires no special privileges).

Another approach is to set some environment variables which are used to tell the C compiler where to find header files and libraries. For example, the following settings can be used for the gcc C compiler:

 
$ export LIBRARY_PATH=/usr/local/Gambit-C/lib
$ export CPATH=/usr/local/Gambit-C/include

Note that this may have been done by the installation process. In particular, the Mac OS X and Microsoft Windows prebuilt installers set up the environment so that the gcc compiler finds these files automatically.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2. The Gambit Scheme interpreter

Synopsis:

 
gsi [-:runtimeoption,…] [-i] [-f] [-v] [[-] [-e expressions] [file]]

The interpreter is executed in interactive mode when no file or ‘-’ or ‘-e’ option is given on the command line. Otherwise the interpreter is executed in batch mode. The ‘-i’ option is ignored by the interpreter. The initialization file will be examined unless the ‘-f’ option is present (see section Customization). The ‘-v’ option prints the system version string, system time stamp, operating system type, and configure script options on standard output and exits. Runtime options are explained in Runtime options.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.1 Interactive mode

In interactive mode a read-eval-print loop (REPL) is started for the user to interact with the interpreter. At each iteration of this loop the interpreter displays a prompt, reads a command and executes it. The commands can be expressions to evaluate (the typical case) or special commands related to debugging, for example ‘,q’ to terminate the process (for a complete list of commands see Debugging). Most commands produce some output, such as the value or error message resulting from an evaluation.

The input and output of the interaction is done on the interaction channel. The interaction channel can be specified through the runtime options but if none is specified the system uses a reasonable default that depends on the system’s configuration. When the system’s runtime library was built with support for GUIDE, the Gambit Universal IDE (with the command ‘configure --enable-guide’) the interaction channel corresponds to the console window of the primordial thread (for details see GUIDE), otherwise the interaction channel is the user’s console, also known as the controlling terminal in the UNIX world. When the REPL starts, the ports associated with ‘(current-input-port)’, ‘(current-output-port)’ and ‘(current-error-port)’ all refer to the interaction channel.

Expressions are evaluated in the global interaction environment. The interpreter adds to this environment any definition entered using the define and define-macro special forms. Once the evaluation of an expression is completed, the value or values resulting from the evaluation are output to the interaction channel by the pretty printer. The special “void” object is not output. This object is returned by most procedures and special forms which the Scheme standard defines as returning an unspecified value (e.g. write, set!, define).

Here is a sample interaction with gsi:

 
$ gsi
Gambit v4.6.0

> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
> (map fact '(1 2 3 4 5 6))
(1 2 6 24 120 720)
> (values (fact 10) (fact 40))
3628800
815915283247897734345611269596115894272000000000
> ,q

What happens when errors occur is explained in Debugging.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.2 Batch mode

In batch mode the command line arguments denote files to be loaded, REPL interactions to start (‘-’ option), and expressions to be evaluated (‘-e’ option). Note that the ‘-’ and ‘-e’ options can be interspersed with the files on the command line and can occur multiple times. The interpreter processes the command line arguments from left to right, loading files with the load procedure and evaluating expressions with the eval procedure in the global interaction environment. After this processing the interpreter exits.

When the file name has no extension the load procedure first attempts to load the file with no extension as a Scheme source file. If that file doesn’t exist it will search for both a source file and an object file. The object file’s name is obtained by adding to the file name a ‘.on’ extension with the highest consecutive version number starting with 1. The source file’s name is obtained by adding to the file name the file extensions ‘.scm’ and ‘.six’ (the first found is the source file). If both a source file and an object file exist, then the one with the latest modification time is loaded. Otherwise the file that is found is loaded. When the file name has an extension, the load procedure will only attempt to load the file with that specific name.

When the extension of the file loaded is ‘.scm’ the content of the file will be parsed using the normal Scheme prefix syntax. When the extension of the file loaded is ‘.six’ the content of the file will be parsed using the Scheme infix syntax extension (see Scheme infix syntax extension). Otherwise, gsi will parse the file using the normal Scheme prefix syntax.

The ports associated with ‘(current-input-port)’, ‘(current-output-port)’ and ‘(current-error-port)’ initially refer respectively to the standard input (‘stdin’), standard output (‘stdout’) and the standard error (‘stderr’) of the interpreter. This is true even in REPLs started with the ‘-’ option. The usual interaction channel (console or IDE’s console window) is still used to read expressions and commands and to display results. This makes it possible to use REPLs to debug programs which read the standard input and write to the standard output, even when these have been redirected.

Here is a sample use of the interpreter in batch mode, under UNIX:

 
$ cat h.scm
(display "hello") (newline)
$ cat w.six
display("world"); newline();
$ gsi h.scm - w.six -e "(pretty-print 1)(pretty-print 2)"
hello
> (define (display x) (write (reverse (string->list x))))
> ,(c 0)
(#\d #\l #\r #\o #\w)
1
2

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.3 Customization

There are two ways to customize the interpreter. When the interpreter starts off it tries to execute a ‘(load "~~lib/gambcext")’ (for an explanation of how file names are interpreted see Host environment). An error is not signaled when the file does not exist. Interpreter extensions and patches that are meant to apply to all users and all modes should go in that file.

Extensions which are meant to apply to a single user or to a specific working directory are best placed in the initialization file, which is a file containing Scheme code. In all modes, the interpreter first tries to locate the initialization file by searching the following locations: ‘.gambcini’ and ‘~/.gambcini’ (with no extension, a ‘.scm’ extension, and a ‘.six’ extension in that order). The first file that is found is examined as though the expression (include initialization-file) had been entered at the read-eval-print loop where initialization-file is the file that was found. Note that by using an include the macros defined in the initialization file will be visible from the read-eval-print loop (this would not have been the case if load had been used). The initialization file is not searched for or examined when the ‘-f’ option is specified.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4 Process exit status

The status is zero when the interpreter exits normally and is nonzero when the interpreter exits due to an error. Here is the meaning of the exit statuses:

0

The execution of the primordial thread (i.e. the main thread) did not encounter any error. It is however possible that other threads terminated abnormally (by default threads other than the primordial thread terminate silently when they raise an exception that is not handled).

64

The runtime options or the environment variable ‘GAMBCOPT’ contained a syntax error or were invalid.

70

This normally indicates that an exception was raised in the primordial thread and the exception was not handled.

71

There was a problem initializing the runtime system, for example insufficient memory to allocate critical tables.

For example, if the shell is sh:

 
$ gsi -:d0 -e "(pretty-print (expt 2 100))"
1267650600228229401496703205376
$ echo $?
0
$ gsi -:d0,unknown # try to use an unknown runtime option
$ echo $?
64
$ gsi -:d0 nonexistent.scm # try to load a file that does not exist
$ echo $?
70
$ gsi nonexistent.scm
*** ERROR IN ##main -- No such file or directory
(load "nonexistent.scm")
$ echo $?
70
 
$ gsi -:m4000000 # ask for a 4 gigabyte heap
*** malloc: vm_allocate(size=528384) failed (error code=3)
*** malloc[15068]: error: Can't allocate region
$ echo $?
71

Note the use of the runtime option ‘-:d0’ that prevents error messages from being output, and the runtime option ‘-:m4000000’ which sets the minimum heap size to 4 gigabytes.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5 Scheme scripts

The load procedure treats specially files that begin with the two characters ‘#!’ and ‘@;’. Such files are called script files and the first line is called the script line. In addition to indicating that the file is a script, the script line provides information about the source code language to be used by the load procedure. After the two characters ‘#!’ and ‘@;’ the system will search for the first substring matching one of the following language specifying tokens:

scheme-r4rs

R4RS language with prefix syntax, case-insensitivity, keyword syntax not supported

scheme-r5rs

R5RS language with prefix syntax, case-insensitivity, keyword syntax not supported

scheme-ieee-1178-1990

IEEE 1178-1990 language with prefix syntax, case-insensitivity, keyword syntax not supported

scheme-srfi-0

R5RS language with prefix syntax and SRFI 0 support (i.e. cond-expand special form), case-insensitivity, keyword syntax not supported

gsi-script

Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword syntax supported

gsc-script

Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword syntax supported

six-script

Full Gambit Scheme language with infix syntax, case-sensitivity, keyword syntax supported

If a language specifying token is not found, load will use the same language as a nonscript file (i.e. it uses the file extension and runtime system options to determine the language).

After processing the script line, load will parse the rest of the file (using the syntax of the language indicated) and then execute it. When the file is being loaded because it is an argument on the interpreter’s command line, the interpreter will:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.1 Scripts under UNIX and Mac OS X

Under UNIX and Mac OS X, the Gambit-C installation process creates the executable ‘gsi’ and also the executables ‘six’, ‘gsi-script’, ‘six-script’, ‘scheme-r5rs’, ‘scheme-srfi-0’, etc as links to ‘gsi’. A Scheme script need only start with the name of the desired Scheme language variant prefixed with ‘#!’ and the directory where the Gambit-C executables are stored. This script should be made executable by setting the execute permission bits (with a ‘chmod +x script’). Here is an example of a script which lists on standard output the files in the current directory:

 
#!/usr/local/Gambit-C/bin/gsi-script
(for-each pretty-print (directory-files))

Here is another UNIX script, using the Scheme infix syntax extension, which takes a single integer argument and prints on standard output the numbers from 1 to that integer:

 
#!/usr/local/Gambit-C/bin/six-script

void main (obj n_str)
{
  int n = \string->number(n_str);
  for (int i=1; i<=n; i++)
    \pretty-print(i);
}

For maximal portability it is a good idea to start scripts indirectly through the ‘/usr/bin/env’ program, so that the executable of the interpreter will be searched in the user’s ‘PATH’. This is what SRFI 22 recommends. For example here is a script that mimics the UNIX ‘cat’ utility for text files:

 
#!/usr/bin/env gsi-script

(define (display-file filename)
  (display (call-with-input-file filename
             (lambda (port)
               (read-line port #f)))))

(for-each display-file (cdr (command-line)))

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.2 Scripts under Microsoft Windows

Under Microsoft Windows, the Gambit-C installation process creates the executable ‘gsi.exe’ and ‘six.exe’ and also the batch files ‘gsi-script.bat’, ‘six-script.bat’, ‘scheme-r5rs.bat’, ‘scheme-srfi-0.bat’, etc which simply invoke ‘gsi.exe’ with the same command line arguments. A Scheme script need only start with the name of the desired Scheme language variant prefixed with ‘@;’. A UNIX script can be converted to a Microsoft Windows script simply by changing the script line and storing the script in a file whose name has a ‘.bat’ or ‘.cmd’ extension:

 
@;gsi-script %~f0 %*
(display "files:\n")
(pretty-print (directory-files))

Note that Microsoft Windows always searches executables in the user’s ‘PATH’, so there is no need for an indirection such as the UNIX ‘/usr/bin/env’. However the script line must end with ‘%~f0 %*’ to pass the expanded filename of the script and command line arguments to the interpreter.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.5.3 Compiling scripts

A script file can be compiled using the Gambit Scheme compiler (see section The Gambit Scheme compiler) into a standalone executable. The script line will provide information to the compiler on which language to use. The script line also provides information on which runtime options to use when executing the compiled script. This is useful to set the default runtime options of an executable program.

The compiled script will be executed similarly to an interpreted script (i.e. the list of command line arguments returned by the command-line procedure and the invocation of the main procedure).

For example:

 
$ cat square.scm
#!/usr/local/Gambit-C/bin/gsi-script -:d0
(define (main arg)
  (pretty-print (expt (string->number arg) 2)))
$ gsi square 30        # gsi will load square.scm
900
$ gsc -exe square      # compile the script to a standalone program
$ ./square 30
900
$ ./square 1 2 3       # too many arguments to main
$ echo $?
70
$ ./square -:d1 1 2 3  # ask for error message
*** ERROR -- Wrong number of arguments passed to procedure
(main "1" "2" "3")

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3. The Gambit Scheme compiler

Synopsis:

 
gsc [-:runtimeoption,…] [-i] [-f] [-v]
    [-prelude expressions] [-postlude expressions]
    [-dynamic] [-exe] [-obj] [-cc-options options]
    [-ld-options-prelude options] [-ld-options options]
    [-warnings] [-verbose] [-report] [-expansion] [-gvm]
    [-debug] [-debug-location] [-debug-source]
    [-debug-environments] [-track-scheme]
    [-o output] [-c] [-keep-c] [-link] [-flat] [-l base]
    [[-] [-e expressions] [file]]

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.1 Interactive mode

When no command line argument is present other than options the compiler behaves like the interpreter in interactive mode. The only difference with the interpreter is that the compilation related procedures listed in this chapter are also available (i.e. compile-file, compile-file-to-c, etc).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 Customization

Like the interpreter, the compiler will examine the initialization file unless the ‘-f’ option is specified.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3 Batch mode

In batch mode gsc takes a set of file names (with either no extension, or a ‘.c’ extension, or some other extension) on the command line and compiles each Scheme file into a C file. The extension can be omitted from file when the Scheme file has a ‘.scm’ or ‘.six’ extension. When the extension of the Scheme file is ‘.six’ the content of the file will be parsed using the Scheme infix syntax extension (see Scheme infix syntax extension). Otherwise, gsc will parse the Scheme file using the normal Scheme prefix syntax. Files with a ‘.c’ extension must have been previously produced by gsc, with the ‘-c’ option, and are used by Gambit’s linker.

For each Scheme file a C file ‘file.c’ will be produced. The C file’s name is the same as the Scheme file, but the extension is changed to ‘.c’. By default the C file is created in the same directory as the Scheme file. This default can be overridden with the compiler’s ‘-o’ option.

The C files produced by the compiler serve two purposes. They will be processed by a C compiler to generate object files, and they also contain information to be read by Gambit’s linker to generate a link file. The link file is a C file that collects various linking information for a group of modules, such as the set of all symbols and global variables used by the modules. The linker is only invoked when the ‘-link’ or ‘-exe’ options appear on the command line.

Compiler options must be specified before the first file name and after the ‘-:’ runtime option (see section Runtime options). If present, the ‘-i’, ‘-f’, and ‘-v’ compiler options must come first. The available options are:

-i

Force interpreter mode.

-f

Do not examine the initialization file.

-v

Print the system version string, system time stamp, operating system type, and configure script options on standard output and exit.

-prelude expressions

Add expressions to the top of the source code being compiled.

-postlude expressions

Add expressions to the bottom of the source code being compiled.

-cc-options options

Add options to the command that invokes the C compiler.

-ld-options-prelude options

Add options to the command that invokes the C linker.

-ld-options options

Add options to the command that invokes the C linker.

-warnings

Display warnings.

-verbose

Display a trace of the compiler’s activity.

-report

Display a global variable usage report.

-expansion

Display the source code after expansion.

-gvm

Generate a listing of the GVM code.

-debug

Include all debugging information in the code generated.

-debug-location

Include source code location debugging information in the code generated.

-debug-source

Include the source code debugging information in the code generated.

-debug-environments

Include environment debugging information in the code generated.

-track-scheme

Generate ‘#line’ directives referring back to the Scheme code.

-o output

Set name of output file or directory where output file(s) are written.

-dynamic

Compile Scheme source files to dynamically loadable object files (this is the default).

-exe

Compile Scheme source files into an executable program.

-obj

Compile Scheme source files to object files.

-keep-c

Keep any intermediate ‘.c’ files that are generated.

-c

Compile Scheme source files to C without generating link file.

-link

Compile Scheme source files to C and generate a link file.

-flat

Generate a flat link file instead of the default incremental link file.

-l base

Specify the link file of the base library to use for the link.

-

Start REPL interaction.

-e expressions

Evaluate expressions in the interaction environment.

The ‘-i’ option forces the compiler to process the remaining command line arguments like the interpreter.

The ‘-prelude’ option adds the specified expressions to the top of the source code being compiled. The main use of this option is to supply declarations on the command line. For example the following invocation of the compiler will compile the file ‘bench.scm’ in unsafe mode:

 
$ gsc -prelude "(declare (not safe))" bench.scm

The ‘-postlude’ option adds the specified expressions to the bottom of the source code being compiled. The main use of this option is to supply the expression that will start the execution of the program. For example:

 
$ gsc -postlude "(start-bench)" bench.scm

The ‘-cc-options’ option is only meaningful when a dynamically loadable object file is being generated (neither the ‘-c’ or ‘-link’ options are used). The ‘-cc-options’ option adds the specified options to the command that invokes the C compiler. The main use of this option is to specify the include path, some symbols to define or undefine, the optimization level, or any C compiler option that is different from the default. For example:

 
$ gsc -cc-options "-U___SINGLE_HOST -O2 -I../include" bench.scm

The ‘-ld-options-prelude’ and ‘-ld-options’ options are only meaningful when a dynamically loadable object file is being generated (neither the ‘-c’ or ‘-link’ options are used). The ‘-ld-options-prelude’ and ‘-ld-options’ options add the specified options to the command that invokes the C linker (the options in ld-options-prelude are passed to the C linker before the input file and the options in ld-options are passed after). The main use of this option is to specify additional object files or libraries that need to be linked, or any C linker option that is different from the default (such as the library search path and flags to select between static and dynamic linking). For example:

 
$ gsc -ld-options "-L/usr/X11R6/lib -lX11 -dynamic" bench.scm

The ‘-warnings’ option displays on standard output all warnings that the compiler may have.

The ‘-verbose’ option displays on standard output a trace of the compiler’s activity.

The ‘-report’ option displays on standard output a global variable usage report. Each global variable used in the program is listed with 4 flags that indicate whether the global variable is defined, referenced, mutated and called.

The ‘-expansion’ option displays on standard output the source code after expansion and inlining by the front end.

The ‘-gvm’ option generates a listing of the intermediate code for the “Gambit Virtual Machine” (GVM) of each Scheme file on ‘file.gvm’.

The ‘-debug’ option causes debugging information to be saved in the code generated. It is equivalent to the combination of the ‘-debug-location’ option, the ‘-debug-source’ option and the ‘-debug-environments’ option. Note that the debugging information will substantially increase the C compilation time and the size of the generated code. When compiling a 3000 line Scheme file it was observed that the total compilation time is 500% longer and the executable code is 150% bigger.

The ‘-debug-location’ option causes source code location debugging information to be saved in the code generated. With this option run time error messages indicate the location of the error in the source code file. When compiling a 3000 line Scheme file it was observed that the total compilation time is 200% longer and the executable code is 60% bigger.

The ‘-debug-source’ option causes source code debugging information to be saved in the code generated. With this option run time error messages indicate the source code, the backtraces are more precise, and the pp procedure will display the source code of compiled procedures. When compiling a 3000 line Scheme file it was observed that the total compilation time is 90% longer and the executable code is 90% bigger.

The ‘-debug-environments’ option causes environment debugging information to be saved in the code generated. With this option the debugger will have access to the environments of the continuations. In other words the local variables defined in compiled procedures (and not optimized away by the compiler) will be shown by the ‘,e’ REPL command. When compiling a 3000 line Scheme file it was observed that the total compilation time is 70% longer and the executable code is 40% bigger.

The ‘-track-scheme’ options causes the generation of ‘#line’ directives that refer back to the Scheme source code. This allows the use of a C debugger or profiler to debug Scheme code.

The ‘-o’ option sets the filename of the output file, or the directory in which the output file(s) generated by the compiler are written.

If the ‘-link’ or ‘-exe’ options appear on the command line, the Gambit linker is invoked to generate the link file from the set of C files specified on the command line or produced by the Gambit compiler. By default the link file is ‘last_.c’, where ‘last.c’ is the last file in the set of C files. When the ‘-c’ option is specified, the Scheme source files are compiled to C files. When the ‘-exe’ option is specified, the generated C files and link file are compiled and linked using the C compiler to produce an executable program whose name defaults to ‘last.exe’. When the ‘-obj’ option is specified, the generated C files are compiled using the C compiler to produce object files (‘.o’ or ‘.obj’ extensions). If neither the ‘-link’, ‘-c’, ‘-exe’, ‘-obj’ options appear on the command line, the Scheme source files are compiled to dynamically loadable object files (‘.on’ extension). The ‘-keep-c’ option will prevent the deletion of any intermediate ‘.c’ file that is generated. Note that in this case the intermediate ‘.c’ file will be generated in the same directory as the Scheme source file even if the ‘-o’ option is used.

The ‘-flat’ option is only meaningful when a link file is being generated (i.e. the ‘-link’ or ‘-exe’ options also appear on the command line). The ‘-flat’ option directs the Gambit linker to generate a flat link file. By default, the linker generates an incremental link file (see the next section for a description of the two types of link files).

The ‘-l’ option is only meaningful when an incremental link file is being generated (i.e. the ‘-link’ or ‘-exe’ options appear on the command line and the ‘-flat’ option is absent). The ‘-l’ option specifies the link file (without the ‘.c’ extension) of the base library to use for the incremental link. By default the link file of the Gambit runtime library is used (i.e. ‘~~lib/_gambc.c’).

The ‘-’ option starts a REPL interaction.

The ‘-e’ option evaluates the specified expressions in the interaction environment.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4 Link files

Gambit can be used to create programs and libraries of Scheme modules. This section explains the steps required to do so and the role played by the link files.

In general, a program is composed of a set of Scheme modules and C modules. Some of the modules are part of the Gambit runtime library and the other modules are supplied by the user. When the program is started it must setup various global tables (including the symbol table and the global variable table) and then sequentially execute the Scheme modules (more or less as though they were being loaded one after another). The information required for this is contained in one or more link files generated by the Gambit linker from the C files produced by the Gambit compiler.

The order of execution of the Scheme modules corresponds to the order of the modules on the command line which produced the link file. The order is usually important because most modules define variables and procedures which are used by other modules (for this reason the program’s main computation is normally started by the last module).

When a single link file is used to contain the linking information of all the Scheme modules it is called a flat link file. Thus a program built with a flat link file contains in its link file both information on the user modules and on the runtime library. This is fine if the program is to be statically linked but is wasteful in a shared-library context because the linking information of the runtime library can’t be shared and will be duplicated in all programs (this linking information typically takes hundreds of kilobytes).

Flat link files are mainly useful to bundle multiple Scheme modules to make a runtime library (such as the Gambit runtime library) or to make a single file that can be loaded with the load procedure.

An incremental link file contains only the linking information that is not already contained in a second link file (the “base” link file). Assuming that a flat link file was produced when the runtime library was linked, a program can be built by linking the user modules with the runtime library’s link file, producing an incremental link file. This allows the creation of a shared-library which contains the modules of the runtime library and its flat link file. The program is dynamically linked with this shared-library and only contains the user modules and the incremental link file. For small programs this approach greatly reduces the size of the program because the incremental link file is small. A “hello world” program built this way can be as small as 5 Kbytes. Note that it is perfectly fine to use an incremental link file for statically linked programs (there is very little loss compared to a single flat link file).

Incremental link files may be built from other incremental link files. This allows the creation of shared-libraries which extend the functionality of the Gambit runtime library.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4.1 Building an executable program

The simplest way to create an executable program is to invoke gsc with the ‘-exe’ option. The compiler will transparently perform all the steps necessary, including compiling Scheme source files to C files, generating the link file, compiling the C files generated to object files, and creating the final executable file using the C linker. The following example shows how to build the executable program ‘hello.exe’ which contains the two Scheme modules ‘h.scm’ and ‘w.six’.

 
$ cat h.scm
(display "hello") (newline)
$ cat w.six
display("world"); newline();
$ gsc -o hello.exe -exe h.scm w.six
h.scm:
/Users/feeley/gambit/doc/h.c:
w.six:
/Users/feeley/gambit/doc/w.c:
/Users/feeley/gambit/doc/w_.c:
$ ./hello.exe
hello
world

The detailed steps which are performed can be viewed by setting the ‘GAMBC_CC_VERBOSE’ environment variable to a nonnull value. For example:

 
$ export GAMBC_CC_VERBOSE=yes
$ gsc -o hello.exe -exe h.scm w.six
h.scm:
/Users/feeley/gambit/doc/h.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "h.o" h.c
w.six:
/Users/feeley/gambit/doc/w.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w.o" w.c
/Users/feeley/gambit/doc/w_.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w_.o" w_.c
gcc  -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include"
 -o "hello.exe" h.o w.o w_.o "/usr/local/Gambit-C/lib/libgambc.a"

Using a single invocation of gsc with the ‘-exe’ option is sometimes inappropriate when the build process is more complex, for example when the program is composed of several seperately compiled modules. In such a case it is useful to decompose the build process into smaller compilation steps. The ‘hello.exe’ executable program could have been built by seperating the generation of C files from the C compilation and linking:

 
$ gsc -c h.scm
$ gsc -c w.six
$ gsc -o hello.exe -exe h.c w.c

When even finer control is desired the build process can be decomposed into smaller steps that invoke the C compiler and linker explicitly. This is described in the rest of this section.

The gsc compiler can be invoked to compile each Scheme module into a C file and to create an incremental link file. The C files and the link file must then be compiled with a C compiler and linked (at the object file level) with the Gambit runtime library and possibly other libraries (such as the math library and the dynamic loading library).

Here is for example how a program with three modules (one in C and two in Scheme) can be built. The content of the three source files (‘m1.c’, ‘m2.scm’ and ‘m3.scm’) is:

 
/* File: "m1.c" */
int power_of_2 (int x) { return 1<<x; }

; File: "m2.scm"
(c-declare "extern int power_of_2 ();")
(define pow2 (c-lambda (int) int "power_of_2"))
(define (twice x) (cons x x))

; File: "m3.scm"
(write (map twice (map pow2 '(1 2 3 4)))) (newline)

The compilation of the two Scheme source files can be done with three invocations of gsc:

 
$ gsc -c m2.scm        # create m2.c (note: .scm is optional)
$ gsc -c m3.scm        # create m3.c (note: .scm is optional)
$ gsc -link m2.c m3.c  # create the incremental link file m3_.c

Alternatively, the three invocations of gsc can be replaced by a single invocation:

 
$ gsc -link m2 m3
m2:
m3:

At this point there will be 4 C files: ‘m1.c’, ‘m2.c’, ‘m3.c’, and ‘m3_.c’. To produce an executable program these files must be compiled with a C compiler and linked with the Gambit-C runtime library. The C compiler options needed will depend on the C compiler and the operating system (in particular it may be necessary to add the options ‘-I/usr/local/Gambit-C/include -L/usr/local/Gambit-C/lib’ to access the ‘gambit.h’ header file and the Gambit-C runtime library).

Here is an example under Mac OS X:

 
$ uname -srmp
Darwin 8.1.0 Power Macintosh powerpc
$ gsc -obj m1.c m2.c m3.c m3_.c
m1.c:
m2.c:
m3.c:
m3_.c:
$ gcc m1.o m2.o m3.o m3_.o -lgambc
$ ./a.out
((2 . 2) (4 . 4) (8 . 8) (16 . 16))

Here is an example under Linux:

 
$ uname -srmp
Linux 2.6.8-1.521 i686 athlon
$ gsc -obj m1.c m2.c m3.c m3_.c
m1.c:
m2.c:
m3.c:
m3_.c:
$ gcc m1.o m2.o m3.o m3_.o -lgambc -lm -ldl -lutil
$ ./a.out
((2 . 2) (4 . 4) (8 . 8) (16 . 16))

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4.2 Building a loadable library

To bundle multiple modules into a single object file that can be dynamically loaded with the load procedure, a flat link file is needed. The compiler’s ‘-o’ option must be used to name the C file generated as follows. If the dynamically loadable object file is to be named ‘myfile.on’ then the ‘-o’ option must set the name of the link file generated to ‘myfile.on.c’ (note that the ‘.c’ extension could also be ‘.cc’, ‘.cpp’ or whatever extension is appropriate for C/C++ source files). The three modules of the previous example can be bundled by generating a link file in this way:

 
$ gsc -link -flat -o foo.o1.c m2 m3
m2:
m3:
*** WARNING -- "cons" is not defined,
***            referenced in: ("m2.c")
*** WARNING -- "map" is not defined,
***            referenced in: ("m3.c")
*** WARNING -- "newline" is not defined,
***            referenced in: ("m3.c")
*** WARNING -- "write" is not defined,
***            referenced in: ("m3.c")

The warnings indicate that there are no definitions (defines or set!s) of the variables cons, map, newline and write in the set of modules being linked. Before ‘foo.o1’ is loaded, these variables will have to be bound; either implicitly (by the runtime library) or explicitly.

When compiling the C files and link file generated, the flag ‘-D___DYNAMIC’ must be passed to the C compiler and the C compiler and linker must be told to generate a dynamically loadable shared library.

Here is an example under Mac OS X:

 
$ uname -srmp
Darwin 8.1.0 Power Macintosh powerpc
$ gsc -link -flat -o foo.o1.c m2 m3 > /dev/null
m2:
m3:
$ gsc -obj m1.c m2.c m3.c foo.o1.c
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ gcc -bundle m1.o m2.o m3.o foo.o1.o -o foo.o1
$ gsi foo.o1
((2 . 2) (4 . 4) (8 . 8) (16 . 16))

Here is an example under Linux:

 
$ uname -srmp
Linux 2.6.8-1.521 i686 athlon
$ gsc -link -flat -o foo.o1.c m2 m3 > /dev/null
m2:
m3:
$ gsc -obj m1.c m2.c m3.c foo.o1.c
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ gcc -shared m1.o m2.o m3.o foo.o1.o -o foo.o1
$ gsi foo.o1
((2 . 2) (4 . 4) (8 . 8) (16 . 16))

Here is a more complex example, under Solaris, which shows how to build a loadable library ‘mymod.o1’ composed of the files ‘m4.scm’, ‘m5.scm’ and ‘x.c’ that links to system shared libraries (for X-windows):

 
$ uname -srmp
SunOS ungava 5.6 Generic_105181-05 sun4m sparc SUNW,SPARCstation-20
$ gsc -link -flat -o mymod.o1.c m4 m5
m4:
m5:
*** WARNING -- "*" is not defined,
***            referenced in: ("m4.c")
*** WARNING -- "+" is not defined,
***            referenced in: ("m5.c")
*** WARNING -- "display" is not defined,
***            referenced in: ("m5.c" "m4.c")
*** WARNING -- "newline" is not defined,
***            referenced in: ("m5.c" "m4.c")
*** WARNING -- "write" is not defined,
***            referenced in: ("m5.c")
$ gsc -obj m4.c m5.c x.c mymod.o1.c
m4.c:
m5.c:
x.c:
mymod.o1.c:
$ /usr/ccs/bin/ld -G -o mymod.o1 mymod.o1.o m4.o m5.o x.o -lX11 -lsocket
$ gsi mymod.o1
hello from m4
hello from m5
(f1 10) = 22
$ cat m4.scm
(define (f1 x) (* 2 (f2 x)))
(display "hello from m4")
(newline)

(c-declare #<<c-declare-end
#include "x.h"
c-declare-end
)
(define x-initialize (c-lambda (char-string) bool "x_initialize"))
(define x-display-name (c-lambda () char-string "x_display_name"))
(define x-bell (c-lambda (int) void "x_bell"))
$ cat m5.scm
(define (f2 x) (+ x 1))
(display "hello from m5")
(newline)

(display "(f1 10) = ")
(write (f1 10))
(newline)

(x-initialize (x-display-name))
(x-bell 50) ; sound the bell at 50%
$ cat x.c
#include <X11/Xlib.h>

static Display *display;

int x_initialize (char *display_name)
{
  display = XOpenDisplay (display_name);
  return display != NULL;
}

char *x_display_name (void)
{
  return XDisplayName (NULL);
}

void x_bell (int volume)
{
  XBell (display, volume);
  XFlush (display);
}
$ cat x.h
int x_initialize (char *display_name);
char *x_display_name (void);
void x_bell (int);

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4.3 Building a shared-library

A shared-library can be built using an incremental link file or a flat link file. An incremental link file is normally used when the Gambit runtime library (or some other library) is to be extended with new procedures. A flat link file is mainly useful when building a “primal” runtime library, which is a library (such as the Gambit runtime library) that does not extend another library. When compiling the C files and link file generated, the flags ‘-D___LIBRARY’ and ‘-D___SHARED’ must be passed to the C compiler. The flag ‘-D___PRIMAL’ must also be passed to the C compiler when a primal library is being built.

A shared-library ‘mylib.so’ containing the two first modules of the previous example can be built this way:

 
$ uname -srmp
Linux bailey 1.2.13 #2 Wed Aug 28 16:29:41 GMT 1996 i586
$ gsc -link -o mylib.c m2
$ gsc -obj -cc-options "-D___SHARED" m1.c m2.c mylib.c
m1.c:
m2.c:
mylib.c:
$ gcc -shared  m1.o m2.o mylib.o -o mylib.so

Note that this shared-library is built using an incremental link file (it extends the Gambit runtime library with the procedures pow2 and twice). This shared-library can in turn be used to build an executable program from the third module of the previous example:

 
$ gsc -link -l mylib m3
$ gsc -obj m3.c m3_.c
m3.c:
m3_.c:
$ gcc m3.o m3_.o mylib.so -lgambc
$ LD_LIBRARY_PATH=.:/usr/local/lib ./a.out
((2 . 2) (4 . 4) (8 . 8) (16 . 16))

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4.4 Other compilation options

The performance of the code can be increased by passing the ‘-D___SINGLE_HOST’ flag to the C compiler. This will merge all the procedures of a module into a single C procedure, which reduces the cost of intra-module procedure calls. In addition the ‘-O’ option can be passed to the C compiler. For large modules, it will not be practical to specify both ‘-O’ and ‘-D___SINGLE_HOST’ for typical C compilers because the compile time will be high and the C compiler might even fail to compile the program for lack of memory. It has been observed that lower levels of optimization (e.g. ‘-O1’) often give faster compilation and also generate faster code. It is a good idea to experiment.

Normally C compilers will not automatically search ‘/usr/local/Gambit-C/include’ for header files so the flag ‘-I/usr/local/Gambit-C/include’ should be passed to the C compiler. Similarly, C compilers/linkers will not automatically search ‘/usr/local/Gambit-C/lib’ for libraries so the flag ‘-L/usr/local/Gambit-C/lib’ should be passed to the C compiler/linker. Alternatives are given in Accessing the system files.

A variety of flags are needed by some C compilers when compiling a shared-library or a dynamically loadable library. Some of these flags are: ‘-shared’, ‘-call_shared’, ‘-rdynamic’, ‘-fpic’, ‘-fPIC’, ‘-Kpic’, ‘-KPIC’, ‘-pic’, ‘+z’, ‘-G’. Check your compiler’s documentation to see which flag you need.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5 Procedures specific to compiler

The Gambit Scheme compiler features the following procedures that are not available in the Gambit Scheme interpreter.

(compile-file-to-c file [options: options] [output: output] [module-name: module-name])procedure

The file parameter must be a string naming an existing file containing Scheme source code. The extension can be omitted from file when the Scheme file has a ‘.scm’ or ‘.six’ extension. This procedure compiles the source file into a file containing C code. By default, this file is named after file with the extension replaced with ‘.c’. The name of the generated file can be specified with the output parameter. If output is a string naming a directory then the C file is created in that directory. Otherwise the name of the C file is output. The name of the generated module can be specified with the module-name parameter. If module-name is #f or is not specified, then the name of the module is derived from the name of the C file generated, without the extension.

Compilation options are specified through the options parameter which must be a list of symbols. Any combination of the following options can be used: ‘verbose’, ‘report’, ‘expansion’, ‘gvm’, and ‘debug’.

When the compilation is successful, compile-file-to-c returns the name of the C file generated. When there is a compilation error, #f is returned.

 
$ cat h.scm
(display "hello") (newline)
$ gsc
Gambit v4.6.0

> (compile-file-to-c "h")
"/Users/feeley/gambit/doc/h.c"
(compile-file file [options: options] [output: output] [cc-options: cc-options] [ld-options-prelude: ld-options-prelude] [ld-options: ld-options])procedure

The file, options, and output parameters have the same meaning as for the compile-file-to-c procedure. The cc-options parameter is a string containing the options to pass to the C compiler and the ld-options-prelude and ld-options parameters are strings containing the options to pass to the C linker (the options in ld-options-prelude are passed to the C linker before the input file and the options in ld-options are passed after).

The compile-file procedure compiles the source file file into an object file, which is either a file dynamically loadable using the load procedure, or a C linkable object file destined to be linked with the C linker (for example to create a standalone executable program). The file may be a Scheme source file or a C file possibly generated by the Gambit Scheme compiler (for example with the compile-file-to-c procedure). The presence of the obj option in options will cause the creation of a C linkable object file and therefore the options ld-options-prelude and ld-options are ignored, otherwise a dynamically loadable file is created. In both cases, if file is a Scheme source file, the compiler first compiles file to a C file which is created in the same directory as file regardless of the output parameter. Then the C file is compiled with the C compiler.

When the compilation is successful, compile-file returns the name of the object file generated. When there is a compilation error, #f is returned.

The name of the object file can be specified with the output parameter. If output is a string naming a directory then the object file is created in that directory. Otherwise the name of the object file is output.

In the case of a dynamically loadable object file, by default the object file is named after file with the extension replaced with ‘.on’, where n is a positive integer that acts as a version number. The next available version number is generated automatically by compile-file.

When dynamically loaded object files are loaded using the load procedure, the ‘.on’ extension can be specified (to select a particular version) or omitted (to load the file with a ‘.on’ extension with the highest n consecutively from 1). When the ‘.on’ extension is not specified and older versions are no longer needed, all versions must be deleted and the compilation must be repeated (this is necessary because the file name, including the extension, is used to name some of the exported symbols of the object file).

Note that dynamically loadable object files can only be generated on host operating systems that support dynamic loading.

 
$ cat h.scm
(display "hello") (newline)
$ gsc
Gambit v4.6.0

> (compile-file "h")
"/Users/feeley/gambit/doc/h.o1"
> (load "h")
hello
"/Users/feeley/gambit/doc/h.o1"
> (compile-file-to-c "h" output: "h.o99.c")
"/Users/feeley/gambit/doc/h.o99.c"
> (compile-file "h.o99.c")
"/Users/feeley/gambit/doc/h.o99"
> (load "h.o99")
hello
"/Users/feeley/gambit/doc/h.o99"
> (compile-file-to-c "h")
"/Users/feeley/gambit/doc/h.c"
> (compile-file "h.c" options: '(obj))
"/Users/feeley/gambit/doc/h.o"
(link-incremental module-list [output: output] [base: base] [warnings?: warnings?])procedure

The first parameter must be a non empty list of strings naming Scheme modules to link (extensions must be omitted). An incremental link file is generated for the modules specified in module-list. By default the link file generated is named ‘last_.c’, where last is the name of the last module. The name of the generated link file can be specified with the output parameter. If output is a string naming a directory then the link file is created in that directory. Otherwise the name of the link file is output.

The base link file is specified by the base parameter, which must be a string. By default the base link file is the Gambit runtime library link file ‘~~lib/_gambc.c’. However, when base is supplied the base link file is named ‘base.c’.

The warnings? parameter controls whether warnings are generated for undefined references.

The following example shows how to build the executable program ‘hello’ which contains the two Scheme modules ‘h.scm’ and ‘w.six’.

 
$ uname -srmp
Darwin 8.1.0 Power Macintosh powerpc
$ cat h.scm
(display "hello") (newline)
$ cat w.six
display("world"); newline();
$ gsc
Gambit v4.6.0

> (compile-file-to-c "h")
"/Users/feeley/gambit/doc/h.c"
> (compile-file-to-c "w")
"/Users/feeley/gambit/doc/w.c"
> (link-incremental '("h" "w") output: "hello.c")
"/Users/feeley/gambit/doc/hello_.c"
> ,q
$ gsc -obj h.c w.c hello.c
h.c:
w.c:
hello.c:
$ gcc h.o w.o hello.o -lgambc -o hello
$ ./hello
hello
world
(link-flat module-list [output: output] [warnings?: warnings?])procedure

The first parameter must be a non empty list of strings naming Scheme modules to link. The first string must be the name of a Scheme module or the name of a link file and the remaining strings must name Scheme modules (in all cases extensions must be omitted). A flat link file is generated for the modules specified in module-list. By default the link file generated is named ‘last_.c’, where last is the name of the last module. The name of the generated link file can be specified with the output parameter. If output is a string naming a directory then the link file is created in that directory. Otherwise the name of the link file is output. If a dynamically loadable object file is produced from the link file ‘output’, then the name of the dynamically loadable object file must be ‘output’ stripped of its file extension.

The warnings? parameter controls whether warnings are generated for undefined references.

The following example shows how to build the dynamically loadable object file ‘lib.o1’ which contains the two Scheme modules ‘m6.scm’ and ‘m7.scm’.

 
$ uname -srmp
Darwin 8.1.0 Power Macintosh powerpc
$ cat m6.scm
(define (f x) (g (* x x)))
$ cat m7.scm
(define (g y) (+ n y))
$ gsc
Gambit v4.6.0

> (compile-file-to-c "m6")
"/Users/feeley/gambit/doc/m6.c"
> (compile-file-to-c "m7")
"/Users/feeley/gambit/doc/m7.c"
> (link-flat '("m6" "m7") output: "lib.o1.c")
*** WARNING -- "*" is not defined,
***            referenced in: ("m6.c")
*** WARNING -- "+" is not defined,
***            referenced in: ("m7.c")
*** WARNING -- "n" is not defined,
***            referenced in: ("m7.c")
"/Users/feeley/gambit/doc/lib.o1.c"
> ,q
$ gcc -bundle -D___DYNAMIC m6.c m7.c lib.o1.c -o lib.o1
$ gsc
Gambit v4.6.0

> (load "lib")
*** WARNING -- Variable "n" used in module "m7" is undefined
"/Users/feeley/gambit/doc/lib.o1"
> (define n 10)
> (f 5)
35
> ,q

The warnings indicate that there are no definitions (defines or set!s) of the variables *, + and n in the modules contained in the library. Before the library is used, these variables will have to be bound; either implicitly (by the runtime library) or explicitly.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4. Runtime options

Both gsi and gsc as well as executable programs compiled and linked using gsc take a ‘-:’ option which supplies parameters to the runtime system. This option must appear first on the command line. The colon is followed by a comma separated list of options with no intervening spaces. The available options are:

mHEAPSIZE

Set minimum heap size in kilobytes.

hHEAPSIZE

Set maximum heap size in kilobytes.

lLIVEPERCENT

Set heap occupation after garbage collection.

s

Select standard Scheme mode.

S

Select Gambit Scheme mode.

d[OPT...]

Set debugging options.

@[INTF][:PORT]

Override the configuration of the main RPC server.

=DIRECTORY

Override the central installation directory.

~~DIR=DIRECTORY

Override the DIR installation directory.

+ARGUMENT

Add ARGUMENT to the command line before other arguments.

f[OPT...]

Set file options.

t[OPT...]

Set terminal options.

-[OPT...]

Set standard input and output options.

The ‘m’ option specifies the minimum size of the heap. The ‘m’ is immediately followed by an integer indicating the number of kilobytes of memory. The heap will not shrink lower than this size. By default, the minimum size is 0.

The ‘h’ option specifies the maximum size of the heap. The ‘h’ is immediately followed by an integer indicating the number of kilobytes of memory. The heap will not grow larger than this size. By default, there is no limit (i.e. the heap will grow until the virtual memory is exhausted).

The ‘l’ option specifies the percentage of the heap that will be occupied with live objects after the heap is resized at the end of a garbage collection. The ‘l’ is immediately followed by an integer between 1 and 100 inclusively indicating the desired percentage. The garbage collector resizes the heap to reach this percentage occupation. By default, the percentage is 50.

The ‘s’ option selects standard Scheme mode. In this mode the reader is case-insensitive and keywords are not recognized. The ‘S’ option selects Gambit Scheme mode (the reader is case-sensitive and recognizes keywords which end with a colon). By default Gambit Scheme mode is used.

The ‘d’ option sets various debugging options. The letter ‘d’ is followed by a sequence of letters indicating suboptions.

p

Uncaught exceptions will be treated as “errors” in the primordial thread only.

a

Uncaught exceptions will be treated as “errors” in all threads.

r

When an “error” occurs a new REPL will be started.

s

When an “error” occurs a new REPL will be started. Moreover the program starts in single-stepping mode.

q

When an “error” occurs the program will terminate with a nonzero exit status.

R

When a user interrupt occurs a new REPL will be started. User interrupts are typically obtained by typing <^C>. Note that with some system configurations <^C> abruptly terminates the process. For example, under Microsoft Windows, <^C> works fine with the standard console but with the MSYS terminal window it terminates the process.

D

When a user interrupt occurs it will be deferred until the parameter current-user-interrupt-handler is bound.

Q

When a user interrupt occurs the program will terminate with a nonzero exit status.

LEVEL

The verbosity level is set to LEVEL (a digit from 0 to 9). At level 0 the runtime system will not display error messages and warnings.

i

The REPL interaction channel will be the IDE REPL window (if the IDE is available).

c

The REPL interaction channel will be the console.

-

The REPL interaction channel will be standard input and standard output.

@[HOST][:PORT]

The REPL interaction channel will be connected to the remote debugger at address HOST:PORT (if there is a remote debugger at that address). The default HOST is 127.0.0.1 and the default PORT is 44555. THIS OPTION IS NOT YET IMPLEMENTED!

The default debugging options are equivalent to -:dpqQ1i (i.e. an uncaught exception in the primordial thread terminates the program after displaying an error message). When the letter ‘d’ is not followed by suboptions, it is equivalent to -:dprR1i (i.e. a new REPL is started only when an uncaught exception occurs in the primordial thread). When gsi and gsc are running the main REPL, the debugging options are changed to cause errors in the primordial thread and user interrupts to start a nested REPL.

The ‘@[INTF][:PORT]’ option overrides the configuration of the main RPC server. The default INTF is 127.0.0.1 and the default PORT is 44556. THIS OPTION IS NOT YET IMPLEMENTED!

The ‘=DIRECTORY’ option overrides the setting of the central installation directory.

The ‘~~DIR=DIRECTORY’ option overrides the setting of the DIR installation directory.

The ‘+’ option adds the text that follows to the command line before other arguments.

The ‘f’, ‘t’ and ‘-’ options specify the default settings of the ports created for files, terminals and standard input and output respectively. The default character encoding, end-of-line encoding and buffering can be set. Moreover, for terminals the line-editing feature can be enabled or disabled. The ‘f’, ‘t’ and ‘-’ must be followed by a sequence of these options:

A

ASCII character encoding.

1

ISO-8859-1 character encoding.

2

UCS-2 character encoding.

4

UCS-4 character encoding.

6

UTF-16 character encoding.

8

UTF-8 character encoding.

U

UTF character encoding with fallback to UTF-8 on input if no BOM is present.

UA

UTF character encoding with fallback to ASCII on input if no BOM is present.

U1

UTF character encoding with fallback to ISO-8859-1 on input if no BOM is present.

U6

UTF character encoding with fallback to UTF-16 on input if no BOM is present.

U8

UTF character encoding with fallback to UTF-8 on input if no BOM is present.

c

End-of-line is encoded as CR (carriage-return).

l

End-of-line is encoded as LF (linefeed)

cl

End-of-line is encoded as CR-LF.

u

Unbuffered I/O.

n

Line buffered I/O (‘n’ for “at newline”).

f

Fully buffered I/O.

r

Illegal character encoding is treated as an error (exception raised).

R

Silently replace illegal character encodings with Unicode character #xfffd (replacement character).

e

Enable line-editing (applies to terminals only).

E

Disable line-editing (applies to terminals only).

When a program’s execution starts, the runtime system obtains the runtime options by processing in turn four sources of runtime options: the defaults, the environment variable ‘GAMBCOPT’, the script line of the source code, and the first command line argument of the program. Any runtime option can be overriden by a subsequent source of runtime options. It is sometimes useful to prevent overriding the runtime options of the script line. This can be achieved by starting the script line runtime options with ‘-::’. In this case the environment variable ‘GAMBCOPT’ is ignored, and the first command line argument of the program is not used for runtime options (it is treated like a normal command line argument).

For example:

 
$ GAMBCOPT=d0,=~/my-gambit2
$ export GAMBCOPT
$ gsi -e '(pretty-print (path-expand "~~")) (/ 1 0)'
"/Users/feeley/my-gambit2/"
$ echo $?
70
$ gsi -:d1 -e '(pretty-print (path-expand "~~")) (/ 1 0)'
"/Users/feeley/my-gambit2/"
*** ERROR IN (string)@1.3 -- Divide by zero
(/ 1 0)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5. Debugging


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1 Debugging model

The evaluation of an expression may stop before it is completed for the following reasons:

  1. An evaluation error has occured, such as attempting to divide by zero.
  2. The user has interrupted the evaluation (usually by typing <^C>).
  3. A breakpoint has been reached or (step) was evaluated.
  4. Single-stepping mode is enabled.

When an evaluation stops, a message is displayed indicating the reason and location where the evaluation was stopped. The location information includes, if known, the name of the procedure where the evaluation was stopped and the source code location in the format ‘stream@line.column’, where stream is either a string naming a file or a symbol within parentheses, such as ‘(console)’.

A nested REPL is then initiated in the context of the point of execution where the evaluation was stopped. The nested REPL’s continuation and evaluation environment are the same as the point where the evaluation was stopped. For example when evaluating the expression ‘(let ((y (- 1 1))) (* (/ x y) 2))’, a “divide by zero” error is reported and the nested REPL’s continuation is the one that takes the result and multiplies it by two. The REPL’s lexical environment includes the lexical variable ‘y’. This allows the inspection of the evaluation context (i.e. the lexical and dynamic environments and continuation), which is particularly useful to determine the exact location and cause of an error.

The prompt of nested REPLs includes the nesting level; ‘1>’ is the prompt at the first nesting level, ‘2>’ at the second nesting level, and so on. An end of file (usually <^D>) will cause the current REPL to be terminated and the enclosing REPL (one nesting level less) to be resumed.

At any time the user can examine the frames in the REPL’s continuation, which is useful to determine which chain of procedure calls lead to an error. A backtrace that lists the chain of active continuation frames in the REPL’s continuation can be obtained with the ‘,b’ command. The frames are numbered from 0, that is frame 0 is the most recent frame of the continuation where execution stopped, frame 1 is the parent frame of frame 0, and so on. It is also possible to move the REPL to a specific parent continuation (i.e. a specific frame of the continuation where execution stopped) with the ‘,N’, ‘,N+’, ‘,N-’, ‘,+’, ‘,-’, ‘,++’, and ‘,--’ commands. When the frame number of the frame being examined is not zero, it is shown in the prompt after the nesting level, for example ‘1\5>’ is the prompt when the REPL nesting level is 1 and the frame number is 5.

Expressions entered at a nested REPL are evaluated in the environment (both lexical and dynamic) of the continuation frame currently being examined if that frame was created by interpreted Scheme code. If the frame was created by compiled Scheme code then expressions get evaluated in the global interaction environment. This feature may be used in interpreted code to fetch the value of a variable in the current frame or to change its value with set!. Note that some special forms (define in particular) can only be evaluated in the global interaction environment.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.2 Debugging commands

In addition to expressions, the REPL accepts the following special “comma” commands:

,?

Give a summary of the REPL commands.

,(h subject)

This command will show the section of the Gambit manual with the definition of the procedure or special form subject, which must be a symbol. For example ‘,(h time)’ will show the section documenting the time special form. Please see the help procedure for additional information.

,h

This command will show the section of the Gambit manual with the definition of the procedure which raised the exception for which this REPL was started.

,q

Terminate the process with exit status 0. This is equivalent to calling (exit 0).

,qt

Terminate the current thread (note that terminating the primordial thread terminates the process).

,t

Return to the outermost REPL, also known as the “top-level REPL”.

,d

Leave the current REPL and resume the enclosing REPL. This command does nothing in the top-level REPL.

,(c expr)

Leave the current REPL and continue the computation that initiated the REPL with a specific value. This command can only be used to continue a computation that signaled an error. The expression expr is evaluated in the current context and the resulting value is returned as the value of the expression which signaled the error. For example, if the evaluation of the expression ‘(* (/ x y) 2)’ signaled an error because ‘y’ is zero, then in the nested REPL a ‘,(c (+ 4 y))’ will resume the computation of ‘(* (/ x y) 2)’ as though the value of ‘(/ x y)’ was 4. This command must be used carefully because the context where the error occured may rely on the result being of a particular type. For instance a ‘,(c #f)’ in the previous example will cause ‘*’ to signal a type error (this problem is the most troublesome when debugging Scheme code that was compiled with type checking turned off so be careful).

,c

Leave the current REPL and continue the computation that initiated the REPL. This command can only be used to continue a computation that was stopped due to a user interrupt, breakpoint or a single-step.

,s

Leave the current REPL and continue the computation that initiated the REPL in single-stepping mode. The computation will perform an evaluation step (as defined by step-level-set!) and then stop, causing a nested REPL to be entered. Just before the evaluation step is performed, a line is displayed (in the same format as trace) which indicates the expression that is being evaluated. If the evaluation step produces a result, the result is also displayed on another line. A nested REPL is then entered after displaying a message which describes the next step of the computation. This command can only be used to continue a computation that was stopped due to a user interrupt, breakpoint or a single-step.

,l

This command is similar to ‘,s’ except that it “leaps” over procedure calls, that is procedure calls are treated like a single step. Single-stepping mode will resume when the procedure call returns, or if and when the execution of the called procedure encounters a breakpoint.

,N

Move to frame number N of the continuation. After changing the current frame, a one-line summary of the frame is displayed as if the ‘,y’ command was entered.

,N+

Move forward by N frames in the chain of continuation frames (i.e. towards older continuation frames). After changing the current frame, a one-line summary of the frame is displayed as if the ‘,y’ command was entered.

,N-

Move backward by N frames in the chain of continuation frames (i.e. towards more recent continuation frames). After changing the current frame, a one-line summary of the frame is displayed as if the ‘,y’ command was entered.

,+

Equivalent to ‘,1+’.

,-

Equivalent to ‘,1-’.

,++

Equivalent to ‘,N+’ where N is the number of continuation frames displayed at the head of a backtrace.

,--

Equivalent to ‘,N-’ where N is the number of continuation frames displayed at the head of a backtrace.

,y

Display a one-line summary of the current frame. The information is displayed in four fields. The first field is the frame number. The second field is the procedure that created the frame or ‘(interaction)’ if the frame was created by an expression entered at the REPL. The remaining fields describe the subproblem associated with the frame, that is the expression whose value is being computed. The third field is the location of the subproblem’s source code and the fourth field is a reproduction of the source code, possibly truncated to fit on the line. The last two fields may be missing if that information is not available. In particular, the third field is missing when the frame was created by a user call to the ‘eval’ procedure or by a compiled procedure not compiled with the ‘-debug’ or ‘-debug-location’ options, and the last field is missing when the frame was created by a compiled procedure not compiled with the ‘-debug’ or ‘-debug-source’ options.

,b

Display a backtrace summarizing each frame in the chain of continuation frames starting with the current frame. For each frame, the same information as for the ‘,y’ command is displayed (except that location information is displayed in the format ‘stream@line:column’). If there are more than 15 frames in the chain of continuation frames, some of the middle frames will be omitted.

,be

Like the ‘,b’ command but also display the environment.

,bed

Like the ‘,be’ command but also display the dynamic environment.

,(b expr)

Display the backtrace of expr’s value, X, which is obtained by evaluating expr in the current frame. X must be a continuation or a thread. When X is a continuation, the frames in that continuation are displayed. When X is a thread, the backtrace of the current continuation of that thread is displayed.

,(be expr)

Like the ‘,(b expr)’ command but also display the environment.

,(bed expr)

Like the ‘,(be expr)’ command but also display the dynamic environment.

,i

Pretty print the procedure that created the current frame or ‘(interaction)’ if the frame was created by an expression entered at the REPL. Compiled procedures will only be pretty printed when they are compiled with the ‘-debug’ or ‘-debug-source’ options.

,e

Display the environment which is accessible from the current frame. The lexical environment is displayed, followed by the dynamic environment if the parameter object repl-display-dynamic-environment? is not false. Global lexical variables are not displayed. Moreover the frame must have been created by interpreted code or code compiled with the ‘-debug’ or ‘-debug-environments’ options. Due to space safety considerations and compiler optimizations, some of the lexical variable bindings may be missing. Lexical variable bindings are displayed using the format ‘variable = expression’ (when variable is mutable) or ‘variable == expression’ (when variable is immutable, which may happen in compiled code due to compiler optimization) and dynamically-bound parameter bindings are displayed using the format ‘(parameter) = expression’. Note that expression can be a self-evaluating expression (number, string, boolean, character, ...), a quoted expression, a lambda expression or a global variable (the last two cases, which are only used when the value of the variable or parameter is a procedure, simplifies the debugging of higher-order procedures). A parameter can be a quoted expression or a global variable. Lexical bindings are displayed in inverse binding order (most deeply nested first) and shadowed variables are included in the list.

,ed

Like the ‘,e’ command but the dynamic environment is always displayed.

,(e expr)

Display the environment of expr’s value, X, which is obtained by evaluating expr in the current frame. X must be a continuation, a thread, a procedure, or a nonnegative integer. When X is a continuation, the environment at that point in the code is displayed. When X is a thread, the environment of the current continuation of that thread is displayed. When X is a procedure, the lexical environment where X was created is combined with the current continuation and this combined environment is displayed. When X is an integer, the environment at frame number X of the continuation is displayed.

,(ed expr)

Like the ‘,(e expr)’ command but the dynamic environment is always displayed.

,st

Display the state of the threads in the current thread’s thread group. A thread can be: uninitialized, initialized, active, and terminated (normally or abnormally). Active threads can be running, sleeping and waiting on a synchronization object (mutex, condition variable or port) possibly with a timeout.

,(st expr)

Display the state of a specific thread or thread group. The value of expr must be a thread or thread group.

,(v expr)

Start a new REPL visiting expr’s value, X, which is obtained by evaluating expr in the current frame. X must be a continuation, a thread, a procedure, or a nonnegative integer. When X is a continuation, the new REPL’s continuation is X and evaluations are done in the environment at that point in the code. When X is a thread, the thread is interrupted and the new REPL’s continuation is the point where the thread was interrupted. When X is a procedure, the lexical environment where X was created is combined with the current continuation and evaluations are done in this combined environment. When X is an integer, the REPL is started in frame number X of the continuation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.3 Debugging example

Here is a sample interaction with gsi:

 
$ gsi
Gambit v4.6.0

> (define (invsqr x) (/ 1 (expt x 2)))
> (define (mymap fn lst)
    (define (mm in)
      (if (null? in)
          '()
          (cons (fn (car in)) (mm (cdr in)))))
    (mm lst))
> (mymap invsqr '(5 2 hello 9 1))
*** ERROR IN invsqr, (console)@1.25 -- (Argument 1) NUMBER expected
(expt 'hello 2)
1> ,i
#<procedure #2 invsqr> =
(lambda (x) (/ 1 (expt x 2)))
1> ,e
x = 'hello
1> ,b
0  invsqr                    (console)@1:25          (expt x 2)
1  #<procedure #4>           (console)@6:17          (fn (car in))
2  #<procedure #4>           (console)@6:31          (mm (cdr in))
3  #<procedure #4>           (console)@6:31          (mm (cdr in))
4  (interaction)             (console)@8:1           (mymap invsqr '(5 2 hel...
1> ,+
1  #<procedure #4>           (console)@6.17          (fn (car in))
1\1> (pp #4)
(lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
1\1> ,e
in = '(hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> ,(e mm)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> fn
#<procedure #2 invsqr>
1\1> (pp fn)
(lambda (x) (/ 1 (expt x 2)))
1\1> ,+
2  #<procedure #4>           (console)@6.31          (mm (cdr in))
1\2> ,e
in = '(2 hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\2> ,(c (list 3 4 5))
(1/25 1/4 3 4 5)
> ,q

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.4 Procedures related to debugging

(help subject)procedure
(help-browser [new-value])procedure

The help procedure displays the section of the Gambit manual with the definition of the procedure or special form subject, which must be a procedure or symbol. For example the call (help gensym) will show the section documenting the gensym procedure and the call (help 'time) will show the section documenting the time special form. The help procedure returns the void object.

The parameter object help-browser is bound to a string naming the external program that is used by the help procedure to view the documentation. Initially it is bound to the empty string. In normal circumstances when help-browser is bound to an empty string the help procedure runs the script ~~bin/gambc-doc.bat which searches for a suitable web browser to open the documentation in HTML format. Unless the system was built with the command ‘configure --enable-help-browser=...’, the text-only browser ‘lynx’ (see http://lynx.isc.org/) will be used by default if it is available. We highly recommend that you install this browser if you are interested in viewing the documentation within the console in which the REPL is running. You can exit ‘lynx’ conveniently by typing an end of file (usually <^D>).

For example:

 
> (help-browser "firefox") ; use firefox instead of lynx
> (help 'gensym)
> (help gensym) ; OK because gensym is a procedure
> (help 'time)
> (help time) ; not OK because time is a special form
*** ERROR IN (console)@5.7 -- Macro name can't be used as a variable: time
> 
(repl-result-history-ref i)procedure
(repl-result-history-max-length-set! n)procedure

The REPL keeps a history of the last few results printed by the REPL. The call (repl-result-history-ref i) returns the ith previous result (the last for i=0, the next to last for i=1, etc). By default the REPL result history remembers up to 3 results. The maximal length of the history can be set to n between 0 and 10 by a call to (repl-result-history-max-length-set! n).

For convenience the reader defines an abbreviation for calling repl-result-history-ref. Tokens formed by a sequence of one or more hash signs, such as ‘#’, ‘##’, etc, are expanded by the reader into the list (repl-result-history-ref i), where i is the number of hash signs minus 1. In other words, ‘#’ will return the last result printed by the REPL, ‘##’ will return the next to last, etc.

For example:

 
> (map (lambda (x) (* x x)) '(1 2 3))
(1 4 9)
> (reverse #)
(9 4 1)
> (append # ##)
(9 4 1 1 4 9)
> 1
1
> 1
1
> (+ # ##)
2
> (+ # ##)
3
> (+ # ##)
5
> ####
*** ERROR IN (console)@9.1 -- (Argument 1) Out of range
(repl-result-history-ref 3)
1> 
(trace proc)procedure
(untrace proc)procedure

The trace procedure starts tracing calls to the specified procedures. When a traced procedure is called, a line containing the procedure and its arguments is displayed (using the procedure call expression syntax). The line is indented with a sequence of vertical bars which indicate the nesting depth of the procedure’s continuation. After the vertical bars is a greater-than sign which indicates that the evaluation of the call is starting.

When a traced procedure returns a result, it is displayed with the same indentation as the call but without the greater-than sign. This makes it easy to match calls and results (the result of a given call is the value at the same indentation as the greater-than sign). If a traced procedure P1 performs a tail call to a traced procedure P2, then P2 will use the same indentation as P1. This makes it easy to spot tail calls. The special handling for tail calls is needed to preserve the space complexity of the program (i.e. tail calls are implemented as required by Scheme even when they involve traced procedures).

The untrace procedure stops tracing calls to the specified procedures. When no argument is passed to the trace procedure, the list of procedures currently being traced is returned. The void object is returned by the trace procedure when it is passed one or more arguments. When no argument is passed to the untrace procedure stops all tracing and returns the void object. A compiled procedure may be traced but only if it is bound to a global variable.

For example:

 
> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
> (trace fact)
> (fact 5)
| > (fact 5)
| | > (fact 4)
| | | > (fact 3)
| | | | > (fact 2)
| | | | | > (fact 1)
| | | | | 1
| | | | 2
| | | 6
| | 24
| 120
120
> (trace -)
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> (define (fact-iter n r) (if (< n 2) r (fact-iter (- n 1) (* n r))))
> (trace fact-iter)
> (fact-iter 5 1)
| > (fact-iter 5 1)
| | > (- 5 1)
| | 4
| > (fact-iter 4 5)
| | > (- 4 1)
| | 3
| > (fact-iter 3 20)
| | > (- 3 1)
| | 2
| > (fact-iter 2 60)
| | > (- 2 1)
| | 1
| > (fact-iter 1 120)
| 120
120
> (trace)
(#<procedure #2 fact-iter> #<procedure #3 -> #<procedure #4 fact>)
> (untrace)
> (fact 5)
120
(step)procedure
(step-level-set! level)procedure

The step procedure enables single-stepping mode. After the call to step the computation will stop just before the interpreter executes the next evaluation step (as defined by step-level-set!). A nested REPL is then started. Note that because single-stepping is stopped by the REPL whenever the prompt is displayed it is pointless to enter (step) by itself. On the other hand entering (begin (step) expr) will evaluate expr in single-stepping mode.

The procedure step-level-set! sets the stepping level which determines the granularity of the evaluation steps when single-stepping is enabled. The stepping level level must be an exact integer in the range 0 to 7. At a level of 0, the interpreter ignores single-stepping mode. At higher levels the interpreter stops the computation just before it performs the following operations, depending on the stepping level:

  1. procedure call
  2. delay special form and operations at lower levels
  3. lambda special form and operations at lower levels
  4. define special form and operations at lower levels
  5. set! special form and operations at lower levels
  6. variable reference and operations at lower levels
  7. constant reference and operations at lower levels

The default stepping level is 7.

For example:

 
> (define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))
> (step-level-set! 1)
> (begin (step) (fact 5))
*** STOPPED IN (console)@3.15
1> ,s
| > (fact 5)
*** STOPPED IN fact, (console)@1.22
1> ,s
| | > (< n 2)
| | #f
*** STOPPED IN fact, (console)@1.43
1> ,s
| | > (- n 1)
| | 4
*** STOPPED IN fact, (console)@1.37
1> ,s
| | > (fact (- n 1))
*** STOPPED IN fact, (console)@1.22
1> ,s
| | | > (< n 2)
| | | #f
*** STOPPED IN fact, (console)@1.43
1> ,s
| | | > (- n 1)
| | | 3
*** STOPPED IN fact, (console)@1.37
1> ,l
| | | > (fact (- n 1))
*** STOPPED IN fact, (console)@1.22
1> ,l
| | > (* n (fact (- n 1)))
| | 24
*** STOPPED IN fact, (console)@1.32
1> ,l
| > (* n (fact (- n 1)))
| 120
120
(break proc)procedure
(unbreak proc)procedure

The break procedure places a breakpoint on each of the specified procedures. When a procedure is called that has a breakpoint, the interpreter will enable single-stepping mode (as if step had been called). This typically causes the computation to stop soon inside the procedure if the stepping level is high enough.

The unbreak procedure removes the breakpoints on the specified procedures. With no argument, break returns the list of procedures currently containing breakpoints. The void object is returned by break if it is passed one or more arguments. With no argument unbreak removes all the breakpoints and returns the void object. A breakpoint can be placed on a compiled procedure but only if it is bound to a global variable.

For example:

 
> (define (double x) (+ x x))
> (define (triple y) (- (double (double y)) y))
> (define (f z) (* (triple z) 10))
> (break double)
> (break -)
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> (f 5)
*** STOPPED IN double, (console)@1.21
1> ,b
0  double                    (console)@1:21          +
1  triple                    (console)@2:31          (double y)
2  f                         (console)@3:18          (triple z)
3  (interaction)             (console)@6:1           (f 5)
1> ,e
x = 5
1> ,c
*** STOPPED IN double, (console)@1.21
1> ,c
*** STOPPED IN f, (console)@3.29
1> ,c
150
> (break)
(#<procedure #3 -> #<procedure #4 double>)
> (unbreak)
> (f 5)
150
(generate-proper-tail-calls [new-value])procedure

[Note: this procedure is DEPRECATED and will be removed in a future version of Gambit. Use the ‘proper-tail-calls’ declaration instead.]

The parameter object generate-proper-tail-calls is bound to a boolean value controlling how the interpreter handles tail calls. When it is bound to #f the interpreter will treat tail calls like nontail calls, that is a new continuation will be created for the call. This setting is useful for debugging, because when a primitive signals an error the location information will point to the call site of the primitive even if this primitive was called with a tail call. The initial value of this parameter object is #t, which means that a tail call will reuse the continuation of the calling function.

This parameter object only affects code that is subsequently processed by load or eval, or entered at the REPL.

For example:

 
> (generate-proper-tail-calls)
#t
> (let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))
*** ERROR IN #<procedure #2>, (console)@2.47 -- Unbound variable: oops
1> ,b
0  #<procedure #2>           (console)@2:47          oops
1  (interaction)             (console)@2:1           ((letrec ((loop (lambda...
1> ,t
> (generate-proper-tail-calls #f)
> (let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))
*** ERROR IN #<procedure #3>, (console)@6.47 -- Unbound variable: oops
1> ,b
0  #<procedure #3>           (console)@6:47          oops
1  #<procedure #3>           (console)@6:32          (loop (* i 2))
2  #<procedure #3>           (console)@6:32          (loop (* i 2))
3  #<procedure #3>           (console)@6:32          (loop (* i 2))
4  #<procedure #3>           (console)@6:32          (loop (* i 2))
5  (interaction)             (console)@6:1           ((letrec ((loop (lambda...

(display-environment-set! display?)procedure

[Note: this procedure is DEPRECATED and will be removed in a future version of Gambit. Use the parameter object repl-display-environment? instead.]

This procedure sets a flag that controls the automatic display of the environment by the REPL. If display? is true, the environment is displayed by the REPL before the prompt. The default setting is not to display the environment.

(repl-display-environment? display?)procedure

The parameter object repl-display-environment? is bound to a boolean value that controls the automatic display of the environment by the REPL. If display? is true, the environment is displayed by the REPL before the prompt. This is particularly useful in single-stepping mode. The default setting is not to display the environment.

(display-dynamic-environment? display?)procedure

The parameter object display-dynamic-environment? is bound to a boolean value that controls wether the dynamic environment is displayed when the environment is displayed. The default setting is not to display the dynamic environment.

(pretty-print obj [port])procedure

This procedure pretty-prints obj on the port port. If it is not specified, port defaults to the current output-port.

For example:

 
> (pretty-print
    (let* ((x '(1 2 3 4)) (y (list x x x))) (list y y y)))
(((1 2 3 4) (1 2 3 4) (1 2 3 4))
 ((1 2 3 4) (1 2 3 4) (1 2 3 4))
 ((1 2 3 4) (1 2 3 4) (1 2 3 4)))
(pp obj [port])procedure

This procedure pretty-prints obj on the port port. When obj is a procedure created by the interpreter or a procedure created by code compiled with the ‘-debug’ or ‘-debug-source’ options, the procedure’s source code is displayed. If it is not specified, port defaults to the interaction channel (i.e. the output will appear at the REPL).

For example:

 
> (define (f g) (+ (time (g 100)) (time (g 1000))))
> (pp f)
(lambda (g)
  (+ (##time (lambda () (g 100)) '(g 100))
     (##time (lambda () (g 1000)) '(g 1000))))
(gc-report-set! report?)procedure

This procedure controls the generation of reports during garbage collections. If the argument is true, a brief report of memory usage is generated after every garbage collection. It contains: the time taken for this garbage collection, the amount of memory allocated in megabytes since the program was started, the size of the heap in megabytes, the heap memory in megabytes occupied by live data, the proportion of the heap occupied by live data, and the number of bytes occupied by movable and nonmovable objects.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.5 Console line-editing

The console implements a simple Scheme-friendly line-editing user-interface that is enabled by default. It offers parentheses balancing, a history of previous commands, symbol completion, and several emacs-compatible keyboard commands. The user’s input is displayed in a bold font and the output produced by the system is in a plain font. The history of previous commands is saved in the file ‘~/.gambc_history’. It is restored when a REPL is started.

Symbol completion is triggered with the tab key. When the cursor is after a sequence of characters that can form a symbol, typing the tab key will search the symbol table for the first symbol (in alphabetical order) that begins with that sequence and insert that symbol. Typing the tab key in succession will cycle through all symbols with that prefix. When all possible symbols have been shown or there are no possible completions, the text reverts to the uncompleted symbol and the bell is rung.

Here are the keyboard commands available (where the ‘M-’ prefix means the escape key is typed and the ‘C-’ prefix means the control key is pressed):

C-d

Generate an end-of-file when the line is empty, otherwise delete character at cursor.

delete or backspace

Delete character before cursor.

M-C-d

Delete word forward and keep a copy of this text on the clipboard.

M-delete

Delete word backward and keep a copy of this text on the clipboard.

M-backspace

Delete S-expression backward and keep a copy of this text on the clipboard.

C-a

Move cursor to beginning of line.

C-e

Move cursor to end of line.

C-b or left-arrow

Move cursor left one character.

M-b

Move cursor left one word.

M-C-b or M-left-arrow

Move cursor left one S-expression.

C-f or right-arrow

Move cursor right one character.

M-f

Move cursor right one word.

M-C-f or M-right-arrow

Move cursor right one S-expression.

C-p or M-p or up-arrow

Move to previous line in history.

C-n or M-n or down-arrow

Move to next line in history.

C-t

Transpose character at cursor with previous character.

M-t

Transpose word after cursor with previous word.

M-C-t

Transpose S-expression after cursor with previous S-expression.

C-l

Clear console and redraw line being edited.

C-nul

Set the mark to the cursor.

C-w

Delete the text between the cursor and the mark and keep a copy of this text on the clipboard.

C-k

Delete the text from the cursor to the end of the line and keep a copy of this text on the clipboard.

C-y

Paste the text that is on the clipboard.

F8

Same as typing ‘#||#,c;’ (REPL command to continue the computation).

F9

Same as typing ‘#||#,-;’ (REPL command to move to newer frame).

F10

Same as typing ‘#||#,+;’ (REPL command to move to older frame).

F11

Same as typing ‘#||#,s;’ (REPL command to step the computation).

F12

Same as typing ‘#||#,l;’ (REPL command to leap the computation).

On Mac OS X, depending on your configuration, you may have to press the fn key to access the function key F12 and the option key to access the other function keys.

On Microsoft Windows the clipboard is the system clipboard. This allows text to be copied and pasted between the program and other applications. On other operating systems the clipboard is internal to the program (it is not integrated with the operating system).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.6 Emacs interface

Gambit comes with the Emacs package ‘gambit.el’ which provides a nice environment for running Gambit from within the Emacs editor. This package filters the standard output of the Gambit process and when it intercepts a location information (in the format ‘stream@line.column’ where stream is either ‘(stdin)’ when the expression was obtained from standard input, ‘(console)’ when the expression was obtained from the console, or a string naming a file) it opens a window to highlight the corresponding expression.

To use this package, make sure the file ‘gambit.el’ is accessible from your load-path and that the following lines are in your ‘.emacs’ file:

 
(autoload 'gambit-inferior-mode "gambit" "Hook Gambit mode into cmuscheme.")
(autoload 'gambit-mode "gambit" "Hook Gambit mode into scheme.")
(add-hook 'inferior-scheme-mode-hook (function gambit-inferior-mode))
(add-hook 'scheme-mode-hook (function gambit-mode))
(setq scheme-program-name "gsi -:d-")

Alternatively, if you don’t mind always loading this package, you can simply add this line to your ‘.emacs’ file:

 
(require 'gambit)

You can then start an inferior Gambit process by typing ‘M-x run-scheme’. The commands provided in ‘cmuscheme’ mode will be available in the Gambit interaction buffer (i.e. ‘*scheme*’) and in buffers attached to Scheme source files. Here is a list of the most useful commands (for a complete list type ‘C-h m’ in the Gambit interaction buffer):

C-x C-e

Evaluate the expression which is before the cursor (the expression will be copied to the Gambit interaction buffer).

C-c C-z

Switch to Gambit interaction buffer.

C-c C-l

Load a file (file attached to current buffer is default) using (load file).

C-c C-k

Compile a file (file attached to current buffer is default) using (compile-file file).

The file ‘gambit.el’ provides these additional commands:

F8 or C-c c

Continue the computation (same as typing ‘#||#,c;’ to the REPL).

F9 or C-c ]

Move to newer frame (same as typing ‘#||#,-;’ to the REPL).

F10 or C-c [

Move to older frame (same as typing ‘#||#,+;’ to the REPL).

F11 or C-c s

Step the computation (same as typing ‘#||#,s;’ to the REPL).

F12 or C-c l

Leap the computation (same as typing ‘#||#,l;’ to the REPL).

C-c _

Removes the last window that was opened to highlight an expression.

The two keystroke version of these commands can be shortened to ‘M-c’, ‘M-[’, ‘M-]’, ‘M-s’, ‘M-l’, and ‘M-_’ respectively by adding this line to your ‘.emacs’ file:

 
(setq gambit-repl-command-prefix "\e")

This is more convenient to type than the two keystroke ‘C-c’ based sequences but the purist may not like this because it does not follow normal Emacs conventions.

Here is what a typical ‘.emacs’ file will look like:

 
(setq load-path ; add directory containing gambit.el
  (cons "/usr/local/Gambit-C/share/emacs/site-lisp"
        load-path))
(setq scheme-program-name "/tmp/gsi -:d-") ; if gsi not in executable path
(setq gambit-highlight-color "gray") ; if you don't like the default
(setq gambit-repl-command-prefix "\e") ; if you want M-c, M-s, etc
(require 'gambit)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.7 GUIDE

The implementation and documentation for GUIDE, the Gambit Universal IDE, are not yet complete.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6. Scheme extensions


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.1 Extensions to standard procedures

(transcript-on file)procedure
(transcript-off)procedure

These procedures do nothing.

(call-with-current-continuation proc)procedure
(call/cc proc)procedure

The procedure call-with-current-continuation is bound to the global variables call-with-current-continuation and call/cc.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.2 Extensions to standard special forms

(lambda lambda-formals body)special form
(define (variable define-formals) body)special form

These forms are extended versions of the lambda and define special forms of standard Scheme. They allow the use of optional formal arguments, either positional or named, and support the syntax and semantics of the DSSSL standard.

When the procedure introduced by a lambda (or define) is applied to a list of actual arguments, the formal and actual arguments are processed as specified in the R4RS if the lambda-formals (or define-formals) is a r4rs-lambda-formals (or r4rs-define-formals).

If the formal-argument-list matches dsssl-formal-argument-list or extended-formal-argument-list they are processed as follows:

  1. Variables in required-formal-arguments are bound to successive actual arguments starting with the first actual argument. It shall be an error if there are fewer actual arguments than required-formal-arguments.
  2. Next variables in optional-formal-arguments are bound to remaining actual arguments. If there are fewer remaining actual arguments than optional-formal-arguments, then the variables are bound to the result of evaluating initializer, if one was specified, and otherwise to #f. The initializer is evaluated in an environment in which all previous formal arguments have been bound.
  3. If #!key does not appear in the formal-argument-list and there is no rest-formal-argument then it shall be an error if there are any remaining actual arguments.
  4. If #!key does not appear in the formal-argument-list and there is a rest-formal-argument then the rest-formal-argument is bound to a list of all remaining actual arguments.
  5. If #!key appears in the formal-argument-list and there is no rest-formal-argument then there shall be an even number of remaining actual arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the argument name, and the second is the corresponding value. It shall be an error if the first member of a pair is not a keyword. It shall be an error if the argument name is not the same as a variable in a keyword-formal-argument. If the same argument name occurs more than once in the list of actual arguments, then the first value is used. If there is no actual argument for a particular keyword-formal-argument, then the variable is bound to the result of evaluating initializer if one was specified, and otherwise to #f. The initializer is evaluated in an environment in which all previous formal arguments have been bound.
  6. If #!key appears in the formal-argument-list and there is a rest-formal-argument before the #!key then there may be an even or odd number of remaining actual arguments and the rest-formal-argument is bound to a list of all remaining actual arguments. Then, these remaining actual arguments are scanned from left to right in pairs, stopping at the first pair whose first element is not a keyword. Each pair whose first element is a keyword matching the name of a keyword-formal-argument gives the value (i.e. the second element of the pair) of the corresponding formal argument. If the same argument name occurs more than once in the list of actual arguments, then the first value is used. If there is no actual argument for a particular keyword-formal-argument, then the variable is bound to the result of evaluating initializer if one was specified, and otherwise to #f. The initializer is evaluated in an environment in which all previous formal arguments have been bound.
  7. If #!key appears in the formal-argument-list and there is a rest-formal-argument after the #!key then there may be an even or odd number of remaining actual arguments. The remaining actual arguments are scanned from left to right in pairs, stopping at the first pair whose first element is not a keyword. Each pair shall have as its first element a keyword matching the name of a keyword-formal-argument; the second element gives the value of the corresponding formal argument. If the same argument name occurs more than once in the list of actual arguments, then the first value is used. If there is no actual argument for a particular keyword-formal-argument, then the variable is bound to the result of evaluating initializer if one was specified, and otherwise to #f. The initializer is evaluated in an environment in which all previous formal arguments have been bound. Finally, the rest-formal-argument is bound to the list of the actual arguments that were not scanned (i.e. after the last keyword/value pair).

In all cases it is an error for a variable to appear more than once in a formal-argument-list.

Note that this specification is compatible with the DSSSL language standard (i.e. a correct DSSSL program will have the same semantics when run with Gambit).

It is unspecified whether variables receive their value by binding or by assignment. Currently the compiler and interpreter use different methods, which can lead to different semantics if call-with-current-continuation is used in an initializer. Note that this is irrelevant for DSSSL programs because call-with-current-continuation does not exist in DSSSL.

For example:

 
> ((lambda (#!rest x) x) 1 2 3)
(1 2 3)
> (define (f a #!optional b) (list a b))
> (define (g a #!optional (b a) #!key (k (* a b))) (list a b k))
> (define (h1 a #!rest r #!key k) (list a k r))
> (define (h2 a #!key k #!rest r) (list a k r))
> (f 1)
(1 #f)
> (f 1 2)
(1 2)
> (g 3)
(3 3 9)
> (g 3 4)
(3 4 12)
> (g 3 4 k: 5)
(3 4 5)
> (g 3 4 k: 5 k: 6)
(3 4 5)
> (h1 7)
(7 #f ())
> (h1 7 k: 8 9)
(7 8 (k: 8 9))
> (h1 7 k: 8 z: 9)
(7 8 (k: 8 z: 9))
> (h2 7)
(7 #f ())
> (h2 7 k: 8 9)
(7 8 (9))
> (h2 7 k: 8 z: 9)
*** ERROR IN (console)@17.1 -- Unknown keyword argument passed to procedure
(h2 7 k: 8 z: 9)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3 Miscellaneous extensions

(vector-copy vector)procedure

This procedure returns a newly allocated vector with the same content as the vector vector. Note that the elements are not recursively copied.

For example:

 
> (define v1 '#(1 2 3))
> (define v2 (vector-copy v1))
> v2
#(1 2 3)
> (eq? v1 v2)
#f
(subvector vector start end)procedure

This procedure is the vector analog of the substring procedure. It returns a newly allocated vector formed from the elements of the vector vector beginning with index start (inclusive) and ending with index end (exclusive).

For example:

 
> (subvector '#(a b c d e f) 3 5)
#(d e)
(vector-append vector)procedure

This procedure is the vector analog of the string-append procedure. It returns a newly allocated vector whose elements form the concatenation of the given vectors.

For example:

 
> (define v '#(1 2 3))
> (vector-append v v v)
#(1 2 3 1 2 3 1 2 3)
(append-vectors lst)procedure

This procedure returns a newly allocated vector whose elements form the concatenation of all the vectors in the list lst. It is equivalent to (apply vector-append lst).

For example:

 
> (define v '#(1 2 3))
> (append-vectors (list v v v))
#(1 2 3 1 2 3 1 2 3)
(subvector-fill! vector start end fill)procedure

This procedure is like vector-fill!, but fills a selected part of the given vector. It sets the elements of the vector vector, beginning with index start (inclusive) and ending with index end (exclusive) to fill. The value returned is unspecified.

For example:

 
> (define v (vector 'a 'b 'c 'd 'e 'f))
> (subvector-fill! v 3 5 'x)
> v
#(a b c x x f)
(subvector-move! src-vector src-start src-end dst-vector dst-start)procedure

This procedure replaces part of the contents of vector dst-vector with part of the contents of vector src-vector. It copies elements from src-vector, beginning with index src-start (inclusive) and ending with index src-end (exclusive) to dst-vector beginning with index dst-start (inclusive). The value returned is unspecified.

For example:

 
> (define v1 '#(1 2 3 4 5 6))
> (define v2 (vector 'a 'b 'c 'd 'e 'f))
> (subvector-move! v1 3 5 v2 1)
> v2
#(a 4 5 d e f)
(vector-shrink! vector k)procedure

This procedure shortens the vector vector so that its new size is k. The value returned is unspecified.

For example:

 
> (define v (vector 'a 'b 'c 'd 'e 'f))
> v
#(a b c d e f)
> (vector-shrink! v 3)
> v
#(a b c)
(append-strings lst)procedure

This procedure returns a newly allocated string whose elements form the concatenation of all the strings in the list lst. It is equivalent to (apply string-append lst).

For example:

 
> (define s "abc")
> (append-strings (list s s s))
"abcabcabc"
(substring-fill! string start end fill)procedure

This procedure is like string-fill!, but fills a selected part of the given string. It sets the elements of the string string, beginning with index start (inclusive) and ending with index end (exclusive) to fill. The value returned is unspecified.

For example:

 
> (define s (string #\a #\b #\c #\d #\e #\f))
> (substring-fill! s 3 5 #\x)
> s
"abcxxf"
(substring-move! src-string src-start src-end dst-string dst-start)procedure

This procedure replaces part of the contents of string dst-string with part of the contents of string src-string. It copies elements from src-string, beginning with index src-start (inclusive) and ending with index src-end (exclusive) to dst-string beginning with index dst-start (inclusive). The value returned is unspecified.

For example:

 
> (define s1 "123456")
> (define s2 (string #\a #\b #\c #\d #\e #\f))
> (substring-move! s1 3 5 s2 1)
> s2
"a45def"
(string-shrink! string k)procedure

This procedure shortens the string string so that its new size is k. The value returned is unspecified.

For example:

 
> (define s (string #\a #\b #\c #\d #\e #\f))
> s
"abcdef"
> (string-shrink! s 3)
> s
"abc"
(box obj)procedure
(box? obj)procedure
(unbox box)procedure
(set-box! box obj)procedure

These procedures implement the box data type. A box is a cell containing a single mutable field. The lexical syntax of a box containing the object obj is #&obj (see section Box syntax).

The procedure box returns a new box object whose content is initialized to obj. The procedure box? returns #t if obj is a box, and otherwise returns #f. The procedure unbox returns the content of the box box. The procedure set-box! changes the content of the box box to obj. The procedure set-box! returns an unspecified value.

For example:

 
> (define b (box 0))
> b
#&0
> (define (inc!) (set-box! b (+ (unbox b) 1)))
> (inc!)
> b
#&1
> (unbox b)
1
(keyword? obj)procedure
(keyword->string keyword)procedure
(string->keyword string)procedure

These procedures implement the keyword data type. Keywords are similar to symbols but are self evaluating and distinct from the symbol data type. The lexical syntax of keywords is specified in Keyword syntax.

The procedure keyword? returns #t if obj is a keyword, and otherwise returns #f. The procedure keyword->string returns the name of keyword as a string. The procedure string->keyword returns the keyword whose name is string.

For example:

 
> (keyword? 'color)
#f
> (keyword? color:)
#t
> (keyword->string color:)
"color"
> (string->keyword "color")
color:
(gensym [prefix])procedure

This procedure returns a new uninterned symbol. Uninterned symbols are guaranteed to be distinct from the symbols generated by the procedures read and string->symbol. The symbol prefix is the prefix used to generate the new symbol’s name. If it is not specified, the prefix defaults to ‘g’.

For example:

 
> (gensym)
#:g0
> (gensym)
#:g1
> (gensym 'star-trek-)
#:star-trek-2
(make-uninterned-symbol name [hash])procedure
(uninterned-symbol? obj)procedure

The procedure make-uninterned-symbol returns a new uninterned symbol whose name is name and hash is hash. The name must be a string and the hash must be a nonnegative fixnum.

The procedure uninterned-symbol? returns #t when obj is a symbol that is uninterned and #f otherwise.

For example:

 
> (uninterned-symbol? (gensym))
#t
> (make-uninterned-symbol "foo")
#:foo:
> (uninterned-symbol? (make-uninterned-symbol "foo"))
#t
> (uninterned-symbol? 'hello)
#f
> (uninterned-symbol? 123)
#f
(make-uninterned-keyword name [hash])procedure
(uninterned-keyword? obj)procedure

The procedure make-uninterned-keyword returns a new uninterned keyword whose name is name and hash is hash. The name must be a string and the hash must be a nonnegative fixnum.

The procedure uninterned-keyword? returns #t when obj is a keyword that is uninterned and #f otherwise.

For example:

 
> (make-uninterned-keyword "foo")
#:foo:
> (uninterned-keyword? (make-uninterned-keyword "foo"))
#t
> (uninterned-keyword? hello:)
#f
> (uninterned-keyword? 123)
#f
(void)procedure

This procedure returns the void object. The read-eval-print loop prints nothing when the result is the void object.

(eval expr [env])procedure

The first parameter is a datum representing an expression. The eval procedure evaluates this expression in the global interaction environment and returns the result. If present, the second parameter is ignored (it is provided for compatibility with R5RS).

For example:

 
> (eval '(+ 1 2))
3
> ((eval 'car) '(1 2))
1
> (eval '(define x 5))
> x
5
(include file)special form

The file parameter must be a string naming an existing file containing Scheme source code. The include special form splices the content of the specified source file. This form can only appear where a define form is acceptable.

For example:

 
(include "macros.scm")

(define (f lst)
  (include "sort.scm")
  (map sqrt (sort lst)))
(define-macro (name define-formals) body)special form

Define name as a macro special form which expands into body. This form can only appear where a define form is acceptable. Macros are lexically scoped. The scope of a local macro definition extends from the definition to the end of the body of the surrounding binding construct. Macros defined at the top level of a Scheme module are only visible in that module. To have access to the macro definitions contained in a file, that file must be included using the include special form. Macros which are visible from the REPL are also visible during the compilation of Scheme source files.

For example:

 
(define-macro (unless test . body)
  `(if ,test #f (begin ,@body)))

(define-macro (push var #!optional val)
  `(set! ,var (cons ,val ,var)))

To examine the code into which a macro expands you can use the compiler’s ‘-expansion’ option or the pp procedure. For example:

 
> (define-macro (push var #!optional val)
    `(set! ,var (cons ,val ,var)))
> (pp (lambda () (push stack 1) (push stack) (push stack 3)))
(lambda ()
  (set! stack (cons 1 stack))
  (set! stack (cons #f stack))
  (set! stack (cons 3 stack)))
(define-syntax name expander)special form

Define name as a macro special form whose expansion is specified by expander. This form is available only when the runtime option ‘-:s’ is used. This option causes the loading of the ~~lib/syntax-case support library, which is the Hieb and Dybvig portable syntax-case implementation which has been ported to the Gambit interpreter and compiler. Note that this implementation of syntax-case does not support special forms that are specific to Gambit.

For example:

 
$ gsi -:s
Gambit v4.6.0

> (define-syntax unless
    (syntax-rules ()
      ((unless test body ...)
       (if test #f (begin body ...)))))
> (let ((test 111)) (unless (= 1 2) (list test test)))
(111 111)
> (pp (lambda () (let ((test 111)) (unless (= 1 2) (list test test)))))
(lambda () ((lambda (%%test14) (if (= 1 2) #f (list %%test14 %%test14))) 111))
> (unless #f (pp xxx))
*** ERROR IN (console)@7.16 -- Unbound variable: xxx
(declare declaration)special form

This form introduces declarations to be used by the compiler (currently the interpreter ignores the declarations). This form can only appear where a define form is acceptable. Declarations are lexically scoped in the same way as macros. The following declarations are accepted by the compiler:

(dialect)

Use the given dialect’s semantics. dialect can be: ‘ieee-scheme’, ‘r4rs-scheme’, ‘r5rs-scheme’ or ‘gambit-scheme’.

(strategy)

Select block compilation or separate compilation. In block compilation, the compiler assumes that global variables defined in the current file that are not mutated in the file will never be mutated. strategy can be: ‘block’ or ‘separate’.

([not] inline)

Allow (or disallow) inlining of user procedures.

([not] inline-primitives primitive…)

The given primitives should (or should not) be inlined if possible (all primitives if none specified).

(inlining-limit n)

Select the degree to which the compiler inlines user procedures. n is the upper-bound, in percent, on code expansion that will result from inlining. Thus, a value of 300 indicates that the size of the program will not grow by more than 300 percent (i.e. it will be at most 4 times the size of the original). A value of 0 disables inlining. The size of a program is the total number of subexpressions it contains (i.e. the size of an expression is one plus the size of its immediate subexpressions). The following conditions must hold for a procedure to be inlined: inlining the procedure must not cause the size of the call site to grow more than specified by the inlining limit, the site of definition (the define or lambda) and the call site must be declared as (inline), and the compiler must be able to find the definition of the procedure referred to at the call site (if the procedure is bound to a global variable, the definition site must have a (block) declaration). Note that inlining usually causes much less code expansion than specified by the inlining limit (an expansion around 10% is common for n=350).

([not] lambda-lift)

Lambda-lift (or don’t lambda-lift) locally defined procedures.

([not] constant-fold)

Allow (or disallow) constant-folding of primitive procedures.

([not] standard-bindings var…)

The given global variables are known (or not known) to be equal to the value defined for them in the dialect (all variables defined in the standard if none specified).

([not] extended-bindings var…)

The given global variables are known (or not known) to be equal to the value defined for them in the runtime system (all variables defined in the runtime if none specified).

([not] run-time-bindings var…)

The given global variables will be tested at run time to see if they are equal to the value defined for them in the runtime system (all variables defined in the runtime if none specified).

([not] safe)

Generate (or don’t generate) code that will prevent fatal errors at run time. Note that in ‘safe’ mode certain semantic errors will not be checked as long as they can’t crash the system. For example the primitive char=? may disregard the type of its arguments in ‘safe’ as well as ‘not safe’ mode.

([not] interrupts-enabled)

Generate (or don’t generate) interrupt checks. Interrupt checks are used to detect user interrupts and also to check for stack overflows. Interrupt checking should not be turned off casually.

([not] proper-tail-calls)

Generate (or don’t generate) proper tail calls. When proper tail calls are turned off, tail calls are handled like non-tail calls, that is a continuation frame will be created for all calls regardless of their kind. This is useful for debugging because the caller of a procedure will be visible in the backtrace produced by the REPL’s ‘,b’ command even when the call is a tail call. Be advised that this does cause stack space to be consumed for tail calls which may cause the stack to overflow when performing long iterations with tail calls (whether they are expressed with a letrec, named let, do, or other form).

([not] optimize-dead-local-variables)

Remove (or preserve) the dead local variables in the environment. Preserving the dead local variables is useful for debugging because continuations will contain the dead variables. Thus, if the code is also compiled with the ‘-debug’ or ‘-debug-environments’ options the ‘,e’, ‘,ed’, ‘,be’, and ‘,bed’ REPL commands will display the dead variables. On the other hand, preserving the dead local variables may change the space complexity of the program (i.e. some of the data that would normally be reclaimed by the garbage collector will not be). Note that due to other compiler optimizations some dead local variables may be removed regardless of this declaration.

(number-type primitive…)

Numeric arguments and result of the specified primitives are known to be of the given type (all primitives if none specified). number-type can be: ‘generic’, ‘fixnum’, or ‘flonum’.

(mostly-number-type primitive…)

Numeric arguments and result of the specified primitives are expected to be most often of the given type (all primitives if none specified). mostly-number-type can be: ‘mostly-generic’, ‘mostly-fixnum’, ‘mostly-fixnum-flonum’, ‘mostly-flonum’, or ‘mostly-flonum-fixnum’.

The default declarations used by the compiler are equivalent to:

 
(declare
  (gambit-scheme)
  (separate)
  (inline)
  (inline-primitives)
  (inlining-limit 350)
  (constant-fold)
  (lambda-lift)
  (not standard-bindings)
  (not extended-bindings)
  (run-time-bindings)
  (safe)
  (interrupts-enabled)
  (proper-tail-calls)
  (optimize-dead-local-variables)
  (generic)
  (mostly-fixnum-flonum)
)

These declarations are compatible with the semantics of R5RS Scheme and includes a few procedures from R6RS (mainly fixnum specific and flonum specific procedures). Typically used declarations that enhance performance, at the cost of violating the R5RS Scheme semantics, are: (standard-bindings), (block), (not safe) and (fixnum).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.4 Undocumented extensions

The procedures in this section are not yet documented.

(continuation? obj)procedure
(continuation-capture proc)procedure
(continuation-graft cont proc obj)procedure
(continuation-return cont obj)procedure

These procedures provide access to internal first-class continuations which are represented using continuation objects distinct from procedures.

The procedure continuation? returns #t when obj is a continuation object and #f otherwise.

The procedure continuation-capture is similar to the call/cc procedure but it represents the continuation with a continuation object. The proc parameter must be a procedure accepting a single argument. The procedure continuation-capture reifies its continuation and calls proc with the corresponding continuation object as its sole argument. Like for call/cc, the implicit continuation of the call to proc is the implicit continuation of the call to continuation-capture.

The procedure continuation-graft performs a procedure call to the procedure proc with arguments obj… and the implicit continuation corresponding to the continuation object cont. The current continuation of the call to procedure continuation-graft is ignored.

The procedure continuation-return invokes the implicit continuation corresponding to the continuation object cont with the result(s) obj…. This procedure can be easily defined in terms of continuation-graft:

 
(define (continuation-return cont . objs)
  (continuation-graft (lambda () (apply values objs))))

For example:

 
> (define x #f)
> (define p (make-parameter 11))
> (pp (parameterize ((p 22))
        (cons 33 (continuation-capture
                  (lambda (c) (set! x c) 44)))))
(33 . 44)
> x
#<continuation #2>
> (continuation-return x 55)
(33 . 55)
> (continuation-graft x (lambda () (expt 2 10)))
(33 . 1024)
> (continuation-graft x expt 2 10)
(33 . 1024)
> (continuation-graft x (lambda () (p)))
(33 . 22)
> (define (map-sqrt1 lst)
    (call/cc
     (lambda (k)
       (map (lambda (x)
              (if (< x 0)
                  (k 'error)
                  (sqrt x)))
            lst))))
> (map-sqrt1 '(1 4 9))
(1 2 3)
> (map-sqrt1 '(1 -1 9))
error
> (define (map-sqrt2 lst)
    (continuation-capture
     (lambda (c)
       (map (lambda (x)
              (if (< x 0)
                  (continuation-return c 'error)
                  (sqrt x)))
            lst))))
> (map-sqrt2 '(1 4 9))
(1 2 3)
> (map-sqrt2 '(1 -1 9))
error
(display-exception exc [port])procedure
(display-exception-in-context exc cont [port])procedure
(display-procedure-environment proc [port])procedure
(display-continuation-environment cont [port])procedure
(display-continuation-dynamic-environment cont [port])procedure
(display-continuation-backtrace cont [port [all-frames? [display-env? [max-head [max-tail [depth]]]]]])procedure

The procedure display-continuation-backtrace displays the frames of the continuation corresponding to the continuation object cont on the port port. If it is not specified, port defaults to the current output-port. The frames are displayed in the same format as the REPL’s ‘,b’ command.

The parameter all-frames?, which defaults to #f, controls which frames are displayed. Some frames of ancillary importance, such as internal frames created by the interpreter, are not displayed when all-frames? is #f. Otherwise all frames are displayed.

The parameter display-env?, which defaults to #f, controls if the frames are displayed with its environment (the variables accessible and their bindings).

The parameters max-head and max-tail, which default to 10 and 4 respectively, control how many frames are displayed at the head and tail of the continuation.

The parameter depth, which defaults to 0, causes the frame numbers to be offset by that value.

For example:

 
> (define x #f)
> (define (fib n)
    (if (< n 2)
        (continuation-capture
         (lambda (c) (set! x c) 1))
        (+ (fib (- n 1))
           (fib (- n 2)))))
> (fib 10)
89
> (display-continuation-backtrace x)
0  fib             (console)@7:12     (fib (- n 2))
1  fib             (console)@7:12     (fib (- n 2))
2  fib             (console)@7:12     (fib (- n 2))
3  fib             (console)@7:12     (fib (- n 2))
4  fib             (console)@7:12     (fib (- n 2))
5  (interaction)   (console)@8:1      (fib 10)
#f
> (display-continuation-backtrace x (current-output-port) #t)
0  fib             (console)@7:12     (fib (- n 2))
1  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
2  fib             (console)@7:12     (fib (- n 2))
3  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
4  fib             (console)@7:12     (fib (- n 2))
5  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
6  fib             (console)@7:12     (fib (- n 2))
7  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
8  fib             (console)@7:12     (fib (- n 2))
9  fib             (console)@6:9      (+ (fib (- n 1)) (fib (- ...
...
13 ##with-no-result-expected-toplevel 
14 ##repl-debug            
15 ##repl-debug-main       
16 ##kernel-handlers       
#f
> (display-continuation-backtrace x (current-output-port) #f #t)
0  fib             (console)@7:12     (fib (- n 2))
        n = 2
1  fib             (console)@7:12     (fib (- n 2))
        n = 4
2  fib             (console)@7:12     (fib (- n 2))
        n = 6
3  fib             (console)@7:12     (fib (- n 2))
        n = 8
4  fib             (console)@7:12     (fib (- n 2))
        n = 10
5  (interaction)   (console)@8:1      (fib 10)
#f
> (display-continuation-backtrace x (current-output-port) #f #f 2 1 100)
100 fib            (console)@7:12     (fib (- n 2))
101 fib            (console)@7:12     (fib (- n 2))
...
105 (interaction)  (console)@8:1      (fib 10)
#f
(make-thread-group [name [thread-group]])procedure
(thread-group? obj)procedure
(thread-group-name thread-group)procedure
(thread-group-parent thread-group)procedure
(thread-group-resume! thread-group)procedure
(thread-group-suspend! thread-group)procedure
(thread-group-terminate! thread-group)procedure
(thread-group->thread-group-list thread-group)procedure
(thread-group->thread-group-vector thread-group)procedure
(thread-group->thread-list thread-group)procedure
(thread-group->thread-vector thread-group)procedure
(thread-state thread)procedure
(thread-state-uninitialized? thread-state)procedure
(thread-state-initialized? thread-state)procedure
(thread-state-active? thread-state)procedure
(thread-state-active-waiting-for thread-state)procedure
(thread-state-active-timeout thread-state)procedure
(thread-state-normally-terminated? thread-state)procedure
(thread-state-normally-terminated-result thread-state)procedure
(thread-state-abnormally-terminated? thread-state)procedure
(thread-state-abnormally-terminated-reason thread-state)procedure
(top [thread-group [port]])procedure
(thread-interrupt! thread [thunk])procedure
(thread-suspend! thread)procedure
(thread-resume! thread)procedure
(thread-thread-group thread)procedure
(define-type-of-thread name field)special form
(thread-init! thread thunk [name [thread-group]])procedure
(initialized-thread-exception? obj)procedure
(initialized-thread-exception-procedure exc)procedure
(initialized-thread-exception-arguments exc)procedure
(uninitialized-thread-exception? obj)procedure
(uninitialized-thread-exception-procedure exc)procedure
(uninitialized-thread-exception-arguments exc)procedure
(inactive-thread-exception? obj)procedure
(inactive-thread-exception-procedure exc)procedure
(inactive-thread-exception-arguments exc)procedure
(rpc-remote-error-exception? obj)procedure
(rpc-remote-error-exception-procedure exc)procedure
(rpc-remote-error-exception-arguments exc)procedure
(rpc-remote-error-exception-message exc)procedure
(timeout->time timeout)procedure
(open-dummy)procedure
(port-settings-set! port settings)procedure
(input-port-bytes-buffered port)procedure
(input-port-characters-buffered port)procedure
(nonempty-input-port-character-buffer-exception? obj)procedure
(nonempty-input-port-character-buffer-exception-arguments exc)procedure
(nonempty-input-port-character-buffer-exception-procedure exc)procedure
(repl-input-port)procedure
(repl-output-port)procedure
(console-port)procedure
(current-user-interrupt-handler [handler])procedure
(defer-user-interrupts)procedure
(primordial-exception-handler exc)procedure
(err-code->string code)procedure
(foreign? obj)procedure
(foreign-tags foreign)procedure
(foreign-address foreign)procedure
(foreign-release! foreign)procedure
(foreign-released? foreign)procedure
(invalid-hash-number-exception? obj)procedure
(invalid-hash-number-exception-procedure exc)procedure
(invalid-hash-number-exception-arguments exc)procedure
(tcp-client-peer-socket-info tcp-client-port)procedure
(tcp-client-self-socket-info tcp-client-port)procedure
(tcp-server-socket-info tcp-server-port)procedure
(socket-info? obj)procedure
(socket-info-address socket-info)procedure
(socket-info-family socket-info)procedure
(socket-info-port-number socket-info)procedure
(system-version)procedure
(system-version-string)procedure
(system-type)procedure
(system-type-string)procedure
(configure-command-string)procedure
(system-stamp)procedure
(future expr)special form
(touch obj)procedure
(tty? obj)procedure
(tty-history tty)procedure
(tty-history-set! tty history)procedure
(tty-history-max-length-set! tty n)procedure
(tty-paren-balance-duration-set! tty duration)procedure
(tty-text-attributes-set! tty attributes)procedure
(tty-mode-set! tty mode)procedure
(tty-type-set! tty type)procedure
(with-input-from-port port thunk)procedure
(with-output-to-port port thunk)procedure
(input-port-char-position port)procedure
(output-port-char-position port)procedure
(open-event-queue n)procedure
(main)procedure
(define-record-type)special form
(define-type)special form
(namespace)special form
(this-source-file)special form
(receive)special form
(cond-expand)special form
(define-cond-expand-feature ident)special form
(finite? x)procedure
(infinite? x)procedure
(nan? x)procedure
(six.!)undefined
(six.!x x)special form
(six.&x x)special form
(six.*x x)special form
(six.++x x)special form
(six.+x x)special form
(six.--x x)special form
(six.-x x)special form
(six.arrow expr ident)special form
(six.break)undefined
(six.call func arg)special form
(six.case)undefined
(six.clause)undefined
(six.compound statement)special form
(six.cons x y)special form
(six.continue)undefined
(six.define-procedure ident proc)special form
(six.define-variable ident type dims init)special form
(six.do-while stat expr)special form
(six.dot expr ident)special form
(six.for stat1 expr2 expr3 stat2)special form
(six.goto)undefined
(six.identifier ident)special form
(six.if expr stat1 [stat2])special form
(six.index expr1 expr2)special form
(six.label)undefined
(six.list x y)special form
(six.literal value)special form
(six.make-array init dim)procedure
(six.new ident arg)special form
(six.null)special form
(six.prefix datum)special form
(six.procedure type params stat)special form
(six.procedure-body stat)special form
(six.return)undefined
(six.switch)undefined
(six.while expr stat)special form
(six.x!=y x y)special form
(six.x%=y x y)special form
(six.x%y x y)special form
(six.x&&y x y)special form
(six.x&=y x y)special form
(six.x&y x y)special form
(six.x*=y x y)special form
(six.x*y x y)special form
(six.x++ x)special form
(six.x+=y x y)special form
(six.x+y x y)special form
(|six.x,y| x y)special form
(six.x-- x)special form
(six.x-=y x y)special form
(six.x-y x y)special form
(six.x/=y x y)special form
(six.x/y x y)special form
(six.x:-y x y)undefined
(six.x:=y x y)special form
(six.x:y x y)special form
(six.x<<=y x y)special form
(six.x<<y x y)special form
(six.x<=y x y)special form
(six.x<y x y)special form
(six.x==y x y)special form
(six.x=y x y)special form
(six.x>=y x y)special form
(six.x>>=y x y)special form
(six.x>>y x y)special form
(six.x>y x y)special form
(six.x?y:z x y z)special form
(six.x^=y x y)special form
(six.x^y x y)special form
(|six.x\|=y| x y)special form
(|six.x\|y| x y)special form
(|six.x\|\|y| x y)special form
(six.~x x)special form

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7. Namespaces

TO DO!


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8. Characters and strings

Gambit supports the Unicode character encoding standard. Scheme characters can be any of the characters whose Unicode encoding is in the range 0 to #x10ffff (inclusive) but not in the range #xd800 to #xdfff. Source code can also contain any Unicode character, however to read such source code properly gsi and gsc must be told which character encoding to use for reading the source code (i.e. ASCII, ISO-8859-1, UTF-8, etc). This can be done by specifying the runtime option ‘-:f’ when gsi and gsc are started.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.1 Extensions to character procedures

(char->integer char)procedure
(integer->char n)procedure

The procedure char->integer returns the Unicode encoding of the character char.

The procedure integer->char returns the character whose Unicode encoding is the exact integer n.

For example:

 
> (char->integer #\!)
33
> (integer->char 65)
#\A
> (integer->char (char->integer #\u1234))
#\u1234
> (integer->char #xd800)
*** ERROR IN (console)@4.1 -- (Argument 1) Out of range
(integer->char 55296)
(char=? char1)procedure
(char<? char1)procedure
(char>? char1)procedure
(char<=? char1)procedure
(char>=? char1)procedure
(char-ci=? char1)procedure
(char-ci<? char1)procedure
(char-ci>? char1)procedure
(char-ci<=? char1)procedure
(char-ci>=? char1)procedure

These procedures take any number of arguments including no argument. This is useful to test if the elements of a list are sorted in a particular order. For example, testing that the list of characters lst is sorted in nondecreasing order can be done with the call (apply char<? lst).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

8.2 Extensions to string procedures

(string=? string1)procedure
(string<? string1)procedure
(string>? string1)procedure
(string<=? string1)procedure
(string>=? string1)procedure
(string-ci=? string1)procedure
(string-ci<? string1)procedure
(string-ci>? string1)procedure
(string-ci<=? string1)procedure
(string-ci>=? string1)procedure

These procedures take any number of arguments including no argument. This is useful to test if the elements of a list are sorted in a particular order. For example, testing that the list of strings lst is sorted in nondecreasing order can be done with the call (apply string<? lst).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9. Numbers


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.1 Extensions to numeric procedures

(= z1)procedure
(< x1)procedure
(> x1)procedure
(<= x1)procedure
(>= x1)procedure

These procedures take any number of arguments including no argument. This is useful to test if the elements of a list are sorted in a particular order. For example, testing that the list of numbers lst is sorted in nondecreasing order can be done with the call (apply < lst).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.2 IEEE floating point arithmetic

To better conform to IEEE floating point arithmetic the standard numeric tower is extended with these special inexact reals:

+inf.0

positive infinity

-inf.0

negative infinity

+nan.0

“not a number”

-0.

negative zero (‘0.’ is the positive zero)

The infinities and “not a number” are reals (i.e. (real? +inf.0) is #t) but are not rational (i.e. (rational? +inf.0) is #f).

Both zeros are numerically equal (i.e. (= -0. 0.) is #t) but are not equivalent (i.e. (eqv? -0. 0.) and (equal? -0. 0.) are #f). All numerical comparisons with “not a number”, including (= +nan.0 +nan.0), are #f.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.3 Integer square root and nth root

(integer-sqrt n)procedure

This procedure returns the integer part of the square root of the nonnegative exact integer n.

For example:

 
> (integer-sqrt 123)
11
(integer-nth-root n1 n2)procedure

This procedure returns the integer part of n1 raised to the power 1/n2, where n1 is a nonnegative exact integer and n2 is a positive exact integer.

For example:

 
> (integer-nth-root 100 3)
4

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.4 Bitwise-operations on exact integers

The procedures defined in this section are compatible with the withdrawn “Integer Bitwise-operation Library SRFI” (SRFI 33). Note that some of the procedures specified in SRFI 33 are not provided.

Most procedures in this section are specified in terms of the binary representation of exact integers. The two’s complement representation is assumed where an integer is composed of an infinite number of bits. The upper section of an integer (the most significant bits) are either an infinite sequence of ones when the integer is negative, or they are an infinite sequence of zeros when the integer is nonnegative.

(arithmetic-shift n1 n2)procedure

This procedure returns n1 shifted to the left by n2 bits, that is (floor (* n1 (expt 2 n2))). Both n1 and n2 must be exact integers.

For example:

 
> (arithmetic-shift 1000 7)  ; n1=...0000001111101000
128000
> (arithmetic-shift 1000 -6) ; n1=...0000001111101000
15
> (arithmetic-shift -23 -3)  ; n1=...1111111111101001
-3
(bitwise-merge n1 n2 n3)procedure

This procedure returns an exact integer whose bits combine the bits from n2 and n3 depending on n1. The bit at index i of the result depends only on the bits at index i in n1, n2 and n3: it is equal to the bit in n2 when the bit in n1 is 0 and it is equal to the bit in n3 when the bit in n1 is 1. All arguments must be exact integers.

For example:

 
> (bitwise-merge -4 -11 10) ; ...11111100 ...11110101 ...00001010
9
> (bitwise-merge 12 -11 10) ; ...00001100 ...11110101 ...00001010
-7
(bitwise-and n)procedure

This procedure returns the bitwise “and” of the exact integers n…. The value -1 is returned when there are no arguments.

For example:

 
> (bitwise-and 6 12)  ; ...00000110 ...00001100
4
> (bitwise-and 6 -4)  ; ...00000110 ...11111100
4
> (bitwise-and -6 -4) ; ...11111010 ...11111100
-8
> (bitwise-and)
-1
(bitwise-ior n)procedure

This procedure returns the bitwise “inclusive-or” of the exact integers n…. The value 0 is returned when there are no arguments.

For example:

 
> (bitwise-ior 6 12)  ; ...00000110 ...00001100
14
> (bitwise-ior 6 -4)  ; ...00000110 ...11111100
-2
> (bitwise-ior -6 -4) ; ...11111010 ...11111100
-2
> (bitwise-ior)
0
(bitwise-xor n)procedure

This procedure returns the bitwise “exclusive-or” of the exact integers n…. The value 0 is returned when there are no arguments.

For example:

 
> (bitwise-xor 6 12)  ; ...00000110 ...00001100
10
> (bitwise-xor 6 -4)  ; ...00000110 ...11111100
-6
> (bitwise-xor -6 -4) ; ...11111010 ...11111100
6
> (bitwise-xor)
0
(bitwise-not n)procedure

This procedure returns the bitwise complement of the exact integer n.

For example:

 
> (bitwise-not 3)  ; ...00000011
-4
> (bitwise-not -1) ; ...11111111
0
(bit-count n)procedure

This procedure returns the bit count of the exact integer n. If n is nonnegative, the bit count is the number of 1 bits in the two’s complement representation of n. If n is negative, the bit count is the number of 0 bits in the two’s complement representation of n.

For example:

 
> (bit-count 0)   ; ...00000000
0
> (bit-count 1)   ; ...00000001
1
> (bit-count 2)   ; ...00000010
1
> (bit-count 3)   ; ...00000011
2
> (bit-count 4)   ; ...00000100
1
> (bit-count -23) ; ...11101001
3
(integer-length n)procedure

This procedure returns the bit length of the exact integer n. If n is a positive integer the bit length is one more than the index of the highest 1 bit (the least significant bit is at index 0). If n is a negative integer the bit length is one more than the index of the highest 0 bit. If n is zero, the bit length is 0.

For example:

 
> (integer-length 0)   ; ...00000000
0
> (integer-length 1)   ; ...00000001
1
> (integer-length 2)   ; ...00000010
2
> (integer-length 3)   ; ...00000011
2
> (integer-length 4)   ; ...00000100
3
> (integer-length -23) ; ...11101001
5
(bit-set? n1 n2)procedure

This procedure returns a boolean indicating if the bit at index n1 of n2 is set (i.e. equal to 1) or not. Both n1 and n2 must be exact integers, and n1 must be nonnegative.

For example:

 
> (map (lambda (i) (bit-set? i -23)) ; ...11101001
       '(7 6 5 4 3 2 1 0))
(#t #t #t #f #t #f #f #t)
(any-bits-set? n1 n2)procedure

This procedure returns a boolean indicating if the bitwise and of n1 and n2 is different from zero or not. This procedure is implemented more efficiently than the naive definition:

 
(define (any-bits-set? n1 n2) (not (zero? (bitwise-and n1 n2))))

For example:

 
> (any-bits-set? 5 10)   ; ...00000101 ...00001010
#f
> (any-bits-set? -23 32) ; ...11101001 ...00100000
#t
(all-bits-set? n1 n2)procedure

This procedure returns a boolean indicating if the bitwise and of n1 and n2 is equal to n1 or not. This procedure is implemented more efficiently than the naive definition:

 
(define (all-bits-set? n1 n2) (= n1 (bitwise-and n1 n2)))

For example:

 
> (all-bits-set? 1 3) ; ...00000001 ...00000011
#t
> (all-bits-set? 7 3) ; ...00000111 ...00000011
#f
(first-bit-set n)procedure

This procedure returns the bit index of the least significant bit of n equal to 1 (which is also the number of 0 bits that are below the least significant 1 bit). This procedure returns -1 when n is zero.

For example:

 
> (first-bit-set 24) ; ...00011000
3
> (first-bit-set 0)  ; ...00000000
-1
(extract-bit-field n1 n2 n3)procedure
(test-bit-field? n1 n2 n3)procedure
(clear-bit-field n1 n2 n3)procedure
(replace-bit-field n1 n2 n3 n4)procedure
(copy-bit-field n1 n2 n3 n4)procedure

These procedures operate on a bit-field which is n1 bits wide starting at bit index n2. All arguments must be exact integers and n1 and n2 must be nonnegative.

The procedure extract-bit-field returns the bit-field of n3 shifted to the right so that the least significant bit of the bit-field is the least significant bit of the result.

The procedure test-bit-field? returns #t if any bit in the bit-field of n3 is equal to 1, otherwise #f is returned.

The procedure clear-bit-field returns n3 with all bits in the bit-field replaced with 0.

The procedure replace-bit-field returns n4 with the bit-field replaced with the least-significant n1 bits of n3.

The procedure copy-bit-field returns n4 with the bit-field replaced with the (same index and size) bit-field in n3.

For example:

 
> (extract-bit-field 5 2 -37)    ; ...11011011
22
> (test-bit-field? 5 2 -37)      ; ...11011011
#t
> (test-bit-field? 1 2 -37)      ; ...11011011
#f
> (clear-bit-field 5 2 -37)      ; ...11011011
-125
> (replace-bit-field 5 2 -6 -37) ; ...11111010 ...11011011
-21
> (copy-bit-field 5 2 -6 -37)    ; ...11111010 ...11011011
-5

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.5 Fixnum specific operations

(fixnum? obj)procedure
(fx* n1)procedure
(fx+ n1)procedure
(fx- n1 n2)procedure
(fx< n1)procedure
(fx<= n1)procedure
(fx= n1)procedure
(fx> n1)procedure
(fx>= n1)procedure
(fxabs n)procedure
(fxand n1)procedure
(fxarithmetic-shift n1 n2)procedure
(fxarithmetic-shift-left n1 n2)procedure
(fxarithmetic-shift-right n1 n2)procedure
(fxbit-count n)procedure
(fxbit-set? n1 n2)procedure
(fxeven? n)procedure
(fxfirst-bit-set n)procedure
(fxif n1 n2 n3)procedure
(fxior n1)procedure
(fxlength n)procedure
(fxmax n1 n2)procedure
(fxmin n1 n2)procedure
(fxmodulo n1 n2)procedure
(fxnegative? n)procedure
(fxnot n)procedure
(fxodd? n)procedure
(fxpositive? n)procedure
(fxquotient n1 n2)procedure
(fxremainder n1 n2)procedure
(fxwrap* n1)procedure
(fxwrap+ n1)procedure
(fxwrap- n1 n2)procedure
(fxwrapabs n)procedure
(fxwraparithmetic-shift n1 n2)procedure
(fxwraparithmetic-shift-left n1 n2)procedure
(fxwraplogical-shift-right n1 n2)procedure
(fxwrapquotient n1 n2)procedure
(fxxor n1)procedure
(fxzero? n)procedure
(fixnum-overflow-exception? obj)procedure
(fixnum-overflow-exception-procedure exc)procedure
(fixnum-overflow-exception-arguments exc)procedure

Fixnum-overflow-exception objects are raised by some of the fixnum specific procedures when the result is larger than can fit in a fixnum. The parameter exc must be a fixnum-overflow-exception object.

The procedure fixnum-overflow-exception? returns #t when obj is a fixnum-overflow-exception object and #f otherwise.

The procedure fixnum-overflow-exception-procedure returns the procedure that raised exc.

The procedure fixnum-overflow-exception-arguments returns the list of arguments of the procedure that raised exc.

For example:

 
> (define (handler exc)
    (if (fixnum-overflow-exception? exc)
        (list (fixnum-overflow-exception-procedure exc)
              (fixnum-overflow-exception-arguments exc))
        'not-fixnum-overflow-exception))
> (with-exception-catcher
    handler
    (lambda () (fx* 100000 100000)))
(#<procedure #2 fx*> (100000 100000))

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.6 Flonum specific operations

(flonum? obj)procedure
(fixnum->flonum n)procedure
(fl* x1)procedure
(fl+ x1)procedure
(fl- x1 x2)procedure
(fl/ x1 x2)procedure
(fl< x1)procedure
(fl<= x1)procedure
(fl= x1)procedure
(fl> x1)procedure
(fl>= x1)procedure
(flabs x)procedure
(flacos x)procedure
(flasin x)procedure
(flatan x)procedure
(flatan y x)procedure
(flceiling x)procedure
(flcos x)procedure
(fldenominator x)procedure
(fleven? x)procedure
(flexp x)procedure
(flexpt x y)procedure
(flfinite? x)procedure
(flfloor x)procedure
(flinfinite? x)procedure
(flinteger? x)procedure
(fllog x)procedure
(flmax x1 x2)procedure
(flmin x1 x2)procedure
(flnan? x)procedure
(flnegative? x)procedure
(flnumerator x)procedure
(flodd? x)procedure
(flpositive? x)procedure
(flround x)procedure
(flsin x)procedure
(flsqrt x)procedure
(fltan x)procedure
(fltruncate x)procedure
(flzero? x)procedure

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

9.7 Pseudo random numbers

The procedures and variables defined in this section are compatible with the “Sources of Random Bits SRFI” (SRFI 27). The implementation is based on Pierre L’Ecuyer’s MRG32k3a pseudo random number generator. At the heart of SRFI 27’s interface is the random source type which encapsulates the state of a pseudo random number generator. The state of a random source object changes every time a pseudo random number is generated from this random source object.

(default-random-source)variable

The global variable default-random-source is bound to the random source object which is used by the random-integer, random-real, random-u8vector and random-f64vector procedures.

(random-integer n)procedure

This procedure returns a pseudo random exact integer in the range 0 to n-1. The random source object in the global variable default-random-source is used to generate this number. The parameter n must be a positive exact integer.

For example:

 
> (random-integer 100)
24
> (random-integer 100)
2
> (random-integer 10000000000000000000000000000000000000000)
6143360270902284438072426748425263488507
(random-real)procedure

This procedure returns a pseudo random inexact real between, but not including, 0 and 1. The random source object in the global variable default-random-source is used to generate this number.

For example:

 
> (random-real)
.24230672079133753
> (random-real)
.02317001922506932
(random-u8vector n)procedure

This procedure returns a u8vector of length n containing pseudo random exact integers in the range 0 to 255. The random source object in the global variable default-random-source is used to generate these numbers. The parameter n must be a nonnegative exact integer.

For example:

 
> (random-u8vector 10)
#u8(200 53 29 202 3 85 208 187 73 219)
(random-f64vector n)procedure

This procedure returns a f64vector of length n containing pseudo random inexact reals between, but not including, 0 and 1. The random source object in the global variable default-random-source is used to generate these numbers. The parameter n must be a nonnegative exact integer.

For example:

 
> (random-f64vector 3)
#f64(.7145854494613069 .47089632669147946 .5400124875182746)
(make-random-source)procedure

This procedure returns a new random source object initialized to a predetermined state (to initialize to a pseudo random state the procedure random-source-randomize! should be called).

For example:

 
> (define rs (make-random-source))
> ((random-source-make-integers rs) 10000000)
8583952
(random-source? obj)procedure

This procedure returns #t when obj is a random source object and #f otherwise.

For example:

 
> (random-source? default-random-source)
#t
> (random-source? 123)
#f
(random-source-state-ref random-source)procedure
(random-source-state-set! random-source state)procedure

The procedure random-source-state-ref extracts the state of the random source object random-source and returns a vector containing the state.

The procedure random-source-state-set! restores the state of the random source object random-source to state which must be a vector returned from a call to the procedure random-source-state-ref.

For example:

 
> (define s (random-source-state-ref default-random-source))
> (random-integer 10000000000000000000000000000000000000000)
7583880188903074396261960585615270693321
> (random-source-state-set! default-random-source s)
> (random-integer 10000000000000000000000000000000000000000)
7583880188903074396261960585615270693321
(random-source-randomize! random-source)procedure
(random-source-pseudo-randomize! random-source i j)procedure

These procedures change the state of the random source object random-source. The procedure random-source-randomize! sets the random source object to a state that depends on the current time (which for typical uses can be considered to randomly initialize the state). The procedure random-source-pseudo-randomize! sets the random source object to a state that is determined only by the current state and the nonnegative exact integers i and j. For both procedures the value returned is unspecified.

For example:

 
> (define s (random-source-state-ref default-random-source))
> (random-source-pseudo-randomize! default-random-source 5 99)
> (random-integer 10000000000000000000000000000000000000000)
9816755163910623041601722050112674079767
> (random-source-state-set! default-random-source s)
> (random-source-pseudo-randomize! default-random-source 5 99)
> (random-integer 10000000000000000000000000000000000000000)
9816755163910623041601722050112674079767
> (random-source-pseudo-randomize! default-random-source 5 99)
> (random-integer 10000000000000000000000000000000000000000)
9816755163910623041601722050112674079767
> (random-source-state-set! default-random-source s)
> (random-source-randomize! default-random-source)
> (random-integer 10000000000000000000000000000000000000000)
2271441220851914333384493143687768110622
> (random-source-state-set! default-random-source s)
> (random-source-randomize! default-random-source)
> (random-integer 10000000000000000000000000000000000000000)
6247966138948323029033944059178072366895
(random-source-make-integers random-source)procedure

This procedure returns a procedure for generating pseudo random exact integers using the random source object random-source. The returned procedure accepts a single parameter n, a positive exact integer, and returns a pseudo random exact integer in the range 0 to n-1.

For example:

 
> (define rs (make-random-source))
> (define ri (random-source-make-integers rs))
> (ri 10000000)
8583952
> (ri 10000000)
2879793
(random-source-make-reals random-source [precision])procedure

This procedure returns a procedure for generating pseudo random inexact reals using the random source object random-source. The returned procedure accepts no parameters and returns a pseudo random inexact real between, but not including, 0 and 1. The optional parameter precision specifies an upper bound on the minimum amount by which two generated pseudo-random numbers can be separated.

For example:

 
> (define rs (make-random-source))
> (define rr (random-source-make-reals rs))
> (rr)
.857402537562821
> (rr)
.2876463473845367
(random-source-make-u8vectors random-source)procedure

This procedure returns a procedure for generating pseudo random u8vectors using the random source object random-source. The returned procedure accepts a single parameter n, a nonnegative exact integer, and returns a u8vector of length n containing pseudo random exact integers in the range 0 to 255.

For example:

 
> (define rs (make-random-source))
> (define rv (random-source-make-u8vectors rs))
> (rv 10)
#u8(200 53 29 202 3 85 208 187 73 219)
> (rv 10)
#u8(113 8 182 120 138 103 53 192 40 176)
(random-source-make-f64vectors random-source [precision])procedure

This procedure returns a procedure for generating pseudo random f64vectors using the random source object random-source. The returned procedure accepts a single parameter n, a nonnegative exact integer, and returns an f64vector of length n containing pseudo random inexact reals between, but not including, 0 and 1. The optional parameter precision specifies an upper bound on the minimum amount by which two generated pseudo-random numbers can be separated.

For example:

 
> (define rs (make-random-source))
> (define rv (random-source-make-f64vectors rs))
> (rv 3)
#f64(.7342236104231586 .2876463473845367 .8574025375628211)
> (rv 3)
#f64(.013863292728449427 .33449296573515447 .8162050798467028)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10. Homogeneous vectors

Homogeneous vectors are vectors containing raw numbers of the same type (signed or unsigned exact integers or inexact reals). There are 10 types of homogeneous vectors: ‘s8vector’ (vector of exact integers in the range -2^7 to 2^7-1), ‘u8vector’ (vector of exact integers in the range 0 to 2^8-1), ‘s16vector’ (vector of exact integers in the range -2^15 to 2^15-1), ‘u16vector’ (vector of exact integers in the range 0 to 2^16-1), ‘s32vector’ (vector of exact integers in the range -2^31 to 2^31-1), ‘u32vector’ (vector of exact integers in the range 0 to 2^32-1), ‘s64vector’ (vector of exact integers in the range -2^63 to 2^63-1), ‘u64vector’ (vector of exact integers in the range 0 to 2^64-1), ‘f32vector’ (vector of 32 bit floating point numbers), and ‘f64vector’ (vector of 64 bit floating point numbers).

The lexical syntax of homogeneous vectors is specified in Homogeneous vector syntax.

The procedures available for homogeneous vectors, listed below, are the analog of the normal vector/string procedures for each of the homogeneous vector types.

(s8vector? obj)procedure
(make-s8vector k [fill])procedure
(s8vector exact-int8)procedure
(s8vector-length s8vector)procedure
(s8vector-ref s8vector k)procedure
(s8vector-set! s8vector k exact-int8)procedure
(s8vector->list s8vector)procedure
(list->s8vector list-of-exact-int8)procedure
(s8vector-fill! s8vector fill)procedure
(subs8vector-fill! vector start end fill)procedure
(append-s8vectors lst)procedure
(s8vector-copy s8vector)procedure
(s8vector-append s8vector)procedure
(subs8vector s8vector start end)procedure
(subs8vector-move! src-s8vector src-start src-end dst-s8vector dst-start)procedure
(s8vector-shrink! s8vector k)procedure
(u8vector? obj)procedure
(make-u8vector k [fill])procedure
(u8vector exact-int8)procedure
(u8vector-length u8vector)procedure
(u8vector-ref u8vector k)procedure
(u8vector-set! u8vector k exact-int8)procedure
(u8vector->list u8vector)procedure
(list->u8vector list-of-exact-int8)procedure
(u8vector-fill! u8vector fill)procedure
(subu8vector-fill! vector start end fill)procedure
(append-u8vectors lst)procedure
(u8vector-copy u8vector)procedure
(u8vector-append u8vector)procedure
(subu8vector u8vector start end)procedure
(subu8vector-move! src-u8vector src-start src-end dst-u8vector dst-start)procedure
(u8vector-shrink! u8vector k)procedure
(s16vector? obj)procedure
(make-s16vector k [fill])procedure
(s16vector exact-int16)procedure
(s16vector-length s16vector)procedure
(s16vector-ref s16vector k)procedure
(s16vector-set! s16vector k exact-int16)procedure
(s16vector->list s16vector)procedure
(list->s16vector list-of-exact-int16)procedure
(s16vector-fill! s16vector fill)procedure
(subs16vector-fill! vector start end fill)procedure
(append-s16vectors lst)procedure
(s16vector-copy s16vector)procedure
(s16vector-append s16vector)procedure
(subs16vector s16vector start end)procedure
(subs16vector-move! src-s16vector src-start src-end dst-s16vector dst-start)procedure
(s16vector-shrink! s16vector k)procedure
(u16vector? obj)procedure
(make-u16vector k [fill])procedure
(u16vector exact-int16)procedure
(u16vector-length u16vector)procedure
(u16vector-ref u16vector k)procedure
(u16vector-set! u16vector k exact-int16)procedure
(u16vector->list u16vector)procedure
(list->u16vector list-of-exact-int16)procedure
(u16vector-fill! u16vector fill)procedure
(subu16vector-fill! vector start end fill)procedure
(append-u16vectors lst)procedure
(u16vector-copy u16vector)procedure
(u16vector-append u16vector)procedure
(subu16vector u16vector start end)procedure
(subu16vector-move! src-u16vector src-start src-end dst-u16vector dst-start)procedure
(u16vector-shrink! u16vector k)procedure
(s32vector? obj)procedure
(make-s32vector k [fill])procedure
(s32vector exact-int32)procedure
(s32vector-length s32vector)procedure
(s32vector-ref s32vector k)procedure
(s32vector-set! s32vector k exact-int32)procedure
(s32vector->list s32vector)procedure
(list->s32vector list-of-exact-int32)procedure
(s32vector-fill! s32vector fill)procedure
(subs32vector-fill! vector start end fill)procedure
(append-s32vectors lst)procedure
(s32vector-copy s32vector)procedure
(s32vector-append s32vector)procedure
(subs32vector s32vector start end)procedure
(subs32vector-move! src-s32vector src-start src-end dst-s32vector dst-start)procedure
(s32vector-shrink! s32vector k)procedure
(u32vector? obj)procedure
(make-u32vector k [fill])procedure
(u32vector exact-int32)procedure
(u32vector-length u32vector)procedure
(u32vector-ref u32vector k)procedure
(u32vector-set! u32vector k exact-int32)procedure
(u32vector->list u32vector)procedure
(list->u32vector list-of-exact-int32)procedure
(u32vector-fill! u32vector fill)procedure
(subu32vector-fill! vector start end fill)procedure
(append-u32vectors lst)procedure
(u32vector-copy u32vector)procedure
(u32vector-append u32vector)procedure
(subu32vector u32vector start end)procedure
(subu32vector-move! src-u32vector src-start src-end dst-u32vector dst-start)procedure
(u32vector-shrink! u32vector k)procedure
(s64vector? obj)procedure
(make-s64vector k [fill])procedure
(s64vector exact-int64)procedure
(s64vector-length s64vector)procedure
(s64vector-ref s64vector k)procedure
(s64vector-set! s64vector k exact-int64)procedure
(s64vector->list s64vector)procedure
(list->s64vector list-of-exact-int64)procedure
(s64vector-fill! s64vector fill)procedure
(subs64vector-fill! vector start end fill)procedure
(append-s64vectors lst)procedure
(s64vector-copy s64vector)procedure
(s64vector-append s64vector)procedure
(subs64vector s64vector start end)procedure
(subs64vector-move! src-s64vector src-start src-end dst-s64vector dst-start)procedure
(s64vector-shrink! s64vector k)procedure
(u64vector? obj)procedure
(make-u64vector k [fill])procedure
(u64vector exact-int64)procedure
(u64vector-length u64vector)procedure
(u64vector-ref u64vector k)procedure
(u64vector-set! u64vector k exact-int64)procedure
(u64vector->list u64vector)procedure
(list->u64vector list-of-exact-int64)procedure
(u64vector-fill! u64vector fill)procedure
(subu64vector-fill! vector start end fill)procedure
(append-u64vectors lst)procedure
(u64vector-copy u64vector)procedure
(u64vector-append u64vector)procedure
(subu64vector u64vector start end)procedure
(subu64vector-move! src-u64vector src-start src-end dst-u64vector dst-start)procedure
(u64vector-shrink! u64vector k)procedure
(f32vector? obj)procedure
(make-f32vector k [fill])procedure
(f32vector inexact-real)procedure
(f32vector-length f32vector)procedure
(f32vector-ref f32vector k)procedure
(f32vector-set! f32vector k inexact-real)procedure
(f32vector->list f32vector)procedure
(list->f32vector list-of-inexact-real)procedure
(f32vector-fill! f32vector fill)procedure
(subf32vector-fill! vector start end fill)procedure
(append-f32vectors lst)procedure
(f32vector-copy f32vector)procedure
(f32vector-append f32vector)procedure
(subf32vector f32vector start end)procedure
(subf32vector-move! src-f32vector src-start src-end dst-f32vector dst-start)procedure
(f32vector-shrink! f32vector k)procedure
(f64vector? obj)procedure
(make-f64vector k [fill])procedure
(f64vector inexact-real)procedure
(f64vector-length f64vector)procedure
(f64vector-ref f64vector k)procedure
(f64vector-set! f64vector k inexact-real)procedure
(f64vector->list f64vector)procedure
(list->f64vector list-of-inexact-real)procedure
(f64vector-fill! f64vector fill)procedure
(subf64vector-fill! vector start end fill)procedure
(append-f64vectors lst)procedure
(f64vector-copy f64vector)procedure
(f64vector-append f64vector)procedure
(subf64vector f64vector start end)procedure
(subf64vector-move! src-f64vector src-start src-end dst-f64vector dst-start)procedure
(f64vector-shrink! f64vector k)procedure

For example:

 
> (define v (u8vector 10 255 13))
> (u8vector-set! v 2 99)
> v
#u8(10 255 99)
> (u8vector-ref v 1)
255
> (u8vector->list v)
(10 255 99)
> (u8vector-shrink! v 2)
> (v)
#u8(10 255)
(object->u8vector obj [encoder])procedure
(u8vector->object u8vector [decoder])procedure

The procedure object->u8vector returns a u8vector that contains the sequence of bytes that encodes the object obj. The procedure u8vector->object decodes the sequence of bytes contained in the u8vector u8vector, which was produced by the procedure object->u8vector, and reconstructs an object structurally equal to the original object. In other words the procedures object->u8vector and u8vector->object respectively perform serialization and deserialization of Scheme objects. Note that some objects are non-serializable (e.g. threads, wills, some types of ports, and any object containing a non-serializable object).

The optional encoder and decoder parameters are single parameter procedures which default to the identity function. The encoder procedure is called during serialization. As the serializer walks through obj, it calls the encoder procedure on each sub-object X that is encountered. The encoder transforms the object X into an object Y that will be serialized instead of X. Similarly the decoder procedure is called during deserialization. When an object Y is encountered, the decoder procedure is called to transform it into the object X that is the result of deserialization.

The encoder and decoder procedures are useful to customize the serialized representation of objects. In particular, it can be used to define the semantics of serializing objects, such as threads and ports, that would otherwise not be serializable. The decoder procedure is typically the inverse of the encoder procedure, i.e. (decoder (encoder X)) = X.

For example:

 
> (define (make-adder x) (lambda (y) (+ x y)))
> (define f (make-adder 10))
> (define a (object->u8vector f))
> (define b (u8vector->object a))
> (u8vector-length a)
1639
> (f 5)
15
> (b 5)
15
> (pp b)
(lambda (y) (+ x y))

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11. Hashing and weak references


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.1 Hashing

(object->serial-number obj)procedure
(serial-number->object n [default])procedure

All Scheme objects are uniquely identified with a serial number which is a nonnegative exact integer. The object->serial-number procedure returns the serial number of object obj. This serial number is only allocated the first time the object->serial-number procedure is called on that object. Objects which do not have an external textual representation that can be read by the read procedure, use an external textual representation that includes a serial number of the form #n. Consequently, the procedures write, pretty-print, etc will call the object->serial-number procedure to get the serial number, and this may cause the serial number to be allocated.

The serial-number->object procedure takes an exact integer parameter n and returns the object whose serial number is n. If no object currently exists with that serial number, default is returned if it is specified, otherwise an unbound-serial-number-exception object is raised. The reader defines the following abbreviation for calling serial-number->object: the syntax #n, where n is a sequence of decimal digits and it is not followed by ‘=’ or ‘#’, is equivalent to the list (serial-number->object n).

For example: