Language Reference

Pocket Scheme abides by the R4RS language standard. It extends the base language with richer control structures, additional intrinsic procedures in core domains such as I/O, and a number of optionally loaded extension libraries for application-specific domains such as networking.

  • Standards compliance
  • Control structures
  • Intrinsic procedures
  • Extension libraries

  • Standards compliance

    R4RS

    Pocket Scheme follows the standard specified in R4RS, with the following caveats:

    The following optional R4RS procedures are not supported in Pocket Scheme:

    make-rectangular make-polar real-part imag-part magnitude angle transcript-on transcript-off

    R5RS

    Pocket Scheme does not abide by R5RS, for want of standard macros, multiple return values and standard environments.

    Note that Pocket Scheme does support the R5RS dynamic-wind and eval procedures (though it doesn't support the R5RS notion of environments), and uses the R5RS definition of call-with-current-continuation . For completeness, here are the unsupported R5RS procedures:

    define-syntax let-syntax letrec-syntax syntax-rules values call-with-values scheme-report-environment null-environment interaction-environment
    Up

    Control structures

    Pocket Scheme extends the standard Scheme control mechanisms in two ways: an additional flavor of continuation, and an exception handling mechanism.

  • Continuations
  • Exceptions
  • Up

    Continuations

    In addition to the conventional Scheme reentrant continuations, Pocket Scheme also supports a cheaper, weaker flavor of continuation, the escape continuations of Rice University's MzScheme implementation. An escape continuation (also known as a "weak" continuation) is valid only for the duration of its dynamic extent, and can be used only to escape to the context of its creation. Escape continuations are much cheaper to create than regular reentrant continuations. To bind an escape continuation, use the call-with-escape-continuation function (abbreviated call/ec) in just the fashion that you would use call/cc.

    See also.

    Up

    Exception handling

    Pocket Scheme implements the Friedman/Haynes/Dybvig exception handling proposal of 4 September 1995. (Q.v. http://www.cs.indiana.edu/scheme-repository/doc.proposals.exceptions.html .)

    For more information on the procedures raise and current-exception-handler and the syntactic form with-handlers, go here.

    Exception structure

    By convention, Pocket Scheme uses cons structures as exception values. The car of the cons-cell is a symbol differentiating the type of exception, while the cdr is a value specific to the type of exception.

    Exception types

    Type Description
    exn:io I/O error. (cadr exn) is a description, (cddr exn) typically either the port on which the exception arose, or an integer error code.
    exn:read Unrecognized character name, mismatched parentheses, etc. (cadr exn) is a description, (cddr exn) an object.
    exn:eval Raised by the evaluator, typically in response to a syntax error. (cadr exn) is a description, (cddr exn) an object.
    exn:type Wrong type passed to a procedure. (cadr exn) is a description, (cddr exn) an object.
    exn:range Type was correct, but the value was out of the valid range. (cadr exn) is a description, (cddr exn) an object.
    exn:math Division by zero, etc. (cadr exn) is a description, (cddr exn) the number.
    exn:heap A recoverable memory panic.
    exn:system An access violation or datatype misalignment. (cadr exn) is the numeric exception code from the system.
    exn:user User code call to the error procedure. (cdr exn) is the list of parameters passed to the procedure.
    exn:break The user selected Scheme/Break from the UI.

    Extension libraries may define their own exception types as well.

    Example

    The following two equivalent expressions demonstrate the use of call/ec and with-handlers . Each expression prints Start, then returns the value 2.

    (call/ec
     (lambda (k) 
      (display "Start") 
      (newline) 
      (k 2) 
      (display "Later") 
      (newline) 
      1))
    (with-handlers (
      ((lambda (x) 
         (eq? (car x) 'two))
       (lambda (x) 2))
      ((lambda (x) 
         (eq? (car x) 'four)) 
       (lambda (x) 4)) 
                   ) 
     (display "Start") 
     (newline) 
     (raise (cons 'two '())) 
     1)

    Caveats

    The following expression looks tail-recursive, but isn't.

    (let loop ()
     (with-handlers (
       ((lambda (x) #t) 
        (lambda (x) #t)) 
                    )
      (do-something)
      (loop)))
    Up

    Procedures intrinsic to Pocket Scheme

    Pocket Scheme supports all built-in procedures of standard Scheme, excluding only a few optional routines. This document will not describe these standard procedures unless Pocket Scheme extends them in some fashion.

  • Flow of control
  • SRFI support
  • Read, eval
  • Macros
  • Debugging
  • Memory management
  • Loading programs
  • External programs
  • Files and directories
  • Low-level I/O
  • Text I/O
  • Soft ports
  • Raw vectors
  • Strings
  • Numerics
  • Foreigns
  • List utilities
  • Miscellaneous procedures
  • Up

    Flow of control

    call-with-escape-continuation

    procvalue of proc

    Calls its argument, passing that procedure the caller's continuation. This continuation is valid only for the dynamic extent of the current call, as contrasted to continuations captured by call-with-current-continuation which have unlimited extent. Abbreviation: call/ec. See also.

    raise

    exnvoid

    Invoke the current exception handler, passing that handler its argument as the exception. By convention, exceptions are conses of a symbol and additional information. See also.

    current-exception-handler

    [new-handler]procedure

    Called without an argument, returns the current exception handler; called with an argument, installs that argument as the new exception handler. An exception handler is an arity-1 procedure accepting an exception object. See also.

    with-handlers

    ((pred proc) ...) . bodysyntax

    Create an exception handler from the set of predicates and procedures, then evaluate the expressions in the body in the extent of that handler. The exception handler consists of cond-style predicates and procedures. See also.

    dynamic-wind

    before-thunk thunk after-thunkresults of thunk

    Per R5RS.

    default-exception-handler

    procedure

    Returns the system default exception handler. See also.

    with-fixed-system-stack

    thunkresults of thunk

    Executes a thunk while preventing the system stack from moving. Necessary for Windows wndprocs and certain system calls.

    reset

    void

    Return control to the top of the REPL. Intended for use in exception handling procedures.

    error

    [argument ...]void

    Raises an exception of type exn:user .

    quit

    void

    Ends the computation and closes the Pocket Scheme window.

    exit

    [code]void

    Synonymous with (quit) . Accepts an optional integer exit code, which is currently ignored.

    Up

    SRFI support

    Pocket Scheme supports the SRFI library standardization process, with intrinsic support for SRFIs 0, 6, and 23 For more information, see http://srfi.schemers.org/.

    SRFI-0

    SRFI 0 is the availability SRFI, a mechanism by which a program can conditionally make the use of optional features and libraries. For more information, see http://srfi.schemers.org/srfi-0/srfi-0.html.

    cond-expand

    (feature code) ...syntax

    For the purposes of expansion, Pocket Scheme 1.2 natively proclaims the following features:

    pocket-scheme r4rs windows-ce srfi-0 srfi-6 srfi-23

    Features may be related with and or or not. An else clause, if present, specifies a clause to take if no previous clause applies.

    Think of this as a compile-time cond form.

    Example
     (define *userdll* 
      (cond-expand 
       (windows-nt "user32.dll")
       (windows-ce "coredll.dll")))
     (define *kerneldll*
      (cond-expand
       (windows-nt "kernel32.dll")
       (windows-ce "coredll.dll")))

    SRFI-6

    SRFI 6 standardizes basic string ports. For more information, see http://srfi.schemers.org/srfi-6/srfi-6.html.

    open-input-string

    string [start end]input-port

    Open an input port on a string, allowing Scheme I/O from the string. The optional parameters start and end (not in SRFI 6) will restrict reads to the half-open range specified by those indices, as if substring was applied to the string.

    open-output-string

    output-port

    Create an output port that accumulates all text sent to it. Use get-output-string to retrieve the saved data as a string.

    get-output-string

    string-portstring

    Returns a string of all the data sent to an output string port.

    Up

    REPL: read/eval/print loop

    read

    [port]value

    Per R4RS.

    For compatibility with existing bodies of Scheme code, Pocket Scheme will force Latin-1 characters within read symbols to lowercase. All other read characters will enter the symbol as given. Whereas Pocket Scheme permits any printable Unicode character within a symbol, only characters in the Latin-1 subset will be mapped to lowercase.

    Nonprintable character literals use a syntax of hash (#), backslash (\), letter x (x), then one to four hexadecimal digits specifying the Unicode value of the character. E.g., a tab control character is #\x9, while the Hebrew yod is #\x5D9. (To remain portable to standard Scheme, use the integer->char function instead.)

    Pocket Scheme supports the #. reader macro of Common Lisp. Be careful using it on a macro, or on any form implemented by Pocket Scheme with a macro.

    eval

    expressionvalue

    Evaluates an expression in the top-level (i.e. global) environment. Note that Pocket Scheme does not support the R5RS environment parameter to eval.

    current-input-port

    [port]input-port

    Returns the default port for input procedures. Reads from this port will prompt the user for text input. The optional parameter, if supplied, specifies a new default input port.

    current-output-port

    [port]output-port

    Returns the default port for output procedures. Writes to this port will appear on the user's console. The optional parameter, if supplied, specifies a new default output port.

    current-error-port

    [port]output-port

    Returns the default port for diagnostic output. Writes to this port will appear on the user's console in a font that differentiates the output from standard output. The optional parameter, if supplied, specifies a new default error port.

    When user code redirects its output through procedures such as with-output-to-file, Pocket Scheme will continue to send its diagnostics to the output window unless the user code also redirects the error port.

    Up

    Macros

    define-macro

    lambda-list macro-bodysyntax

    Defines a macro, using the Gambit Scheme syntax. Here's a simple example:

    (define-macro (letcc c . body)
     `(call/cc (lambda (,c) ,@body)))

    Macro definitions must appear at the topmost level, and are not hygienic. Use gensym where appropriate

    Pocket Scheme does not support the official R5RS macro syntax. Yet.

    gensym

    symbol

    Returns a unique symbol that can never be returned by any call to read or string->symbol.

    Up

    Debugging

    debug

    enabled?Boolean

    Enables or disables whether Pocket Scheme displays a list of pending calculations when it stops with an error. Called with no parameters, returns whether these debugging callstacks are enabled.

    For best performance, always run with callstack disabled.

    trace

    [proc-name ...]void

    Trace the named procedure or procedures. With no parameters, displays a list of all traced procedures. Only user-defined procedures can be traced.

    A traced procedure is no longer tail-recursive.

    untrace

    [proc-nme ...]void

    Stop tracing the named procedure or procedures. With no parameters, untraces every traced procedure.

    Up

    Memory management

    gc-verbose

    [verbose?]Boolean

    Return whether the garbage collector announces its activity. With an argument, specifies the GC's behavior.

    By default, Pocket Scheme memory management runs silently. You must explicitly specify (gc-verbose #t) if you want notifications of GC activity.

    gc

    [verbose?]void

    Force an immediate garbage collection to reclaim unreferenced storage. The optional parameter specifies whether to emit diagnostic information about the GC, similar to the setting of gc-verbose.

    heap-info

    list

    Returns a list of four values: the current number of pages in the heap; the maximum number of pages in the heap; the number of cons-cells per page; and the number of cons-cells known to be available.

    gc-stats

    void

    Display statistics about garbage collection.

    gc-reset-stats

    void

    Reset collected statistics about garbage collection.

    Up

    Loading programs

    load

    filenamevoid

    Reads Scheme expressions and definitions from an external file. The file may be a text file, typically with the .scm suffix, or it may be a compiled binary file, typically with the .dll suffix.

    Note that continuations captured by evaluating an expression within a load cannot be restored outside the scope of that load.

    load-once

    filenamevoid

    Loads a file per the load procedure. Does nothing if it has already been called on the named file.

    find-library-file

    filenamestring

    Searches the standard load path for the specified filename and returns it as a fully qualified pathname, or #f if the file exists nowhere on the load path. The load path consists of first the installation directory, then the library directory.

    require

    filenamevoid

    Equivalent to (load-once (find-library-file filename)).

    library-directory

    [directory]string

    Returns the currently specified library directory. With an argument, sets that as the library directory. The library directory is a directory searched when loading files.

    install-directory

    [directory]string

    Returns the currently specified installation directory. With an argument, sets that as the installation directory. The installation directory is the first directory searched when loading files.

    Up

    External programs

    system

    command [param1 ...]void

    The first parameter is the name of the external program to execute. The second and subsequent parameters, if present, constitute the command-line arguments to that command. The procedure does not wait until its command completes, but instead returns immediately.

    If command is the name of a document file, this procedure will attempt to open that document with the correct application.

    system/wait

    command [timeout] [param1 ...]Boolean

    This procedure resembles system, except that it waits until either its command completes or its timeout lapses before returning to the caller. The procedure returns #f if the timeout lapsed without the command completing, #t otherwise.

    Timeout is an interval specified in milliseconds. If not supplied, the procedure will wait forever.

    Unlike system, this procedure does not handle document files.

    sleep

    millisecondsvoid

    Pauses Pocket Scheme for the specified duration.

    current-milliseconds

    void

    Returns the number of milliseconds that have passed since the device was started. (After 47 days, this counter will wrap to zero.)

    Up

    Files and directories

    copy-file

    original-file new-filevoid

    Make a copy of the file at the new location.

    move-file

    original-file new-filevoid

    Make a copy of the file, deleting the original.

    delete-file

    filenamevoid

    Delete the file from storage.

    directory-list

    [wildcard] [exclude]list

    Returns a list of all files in the specified directory. Optionally, takes a wildcard matching string specifying the files to return, and a flag symbol or list of symbols specifying files to exclude from the returned list. (By default, it excludes all hidden files.)

    The expression (directory-list "\My Documents" "*.smd") will return all Scheme command files in the documents directory, while (directory-list "\My Documents" "*" '(no-hidden no-directory)) will list all files that are neither hidden nor subdirectories.

    Flag Effect
    no-archive Do not return files with the ARCHIVE attribute.
    no-directories Do not return directories.
    no-hidden Do not return files with the HIDDEN attribute.
    no-readonly Do not return files with the READONLY attribute.
    no-system Do not return files with the SYSTEM attribute.

    file-exists?

    pathnameBoolean

    Returns #t if the file exists and is readable.

    directory-exists?

    pathnameBoolean

    Returns #t if the directory exists and is readable.

    create-directory

    pathnamevoid

    Create a new directory at the specified path.

    delete-directory

    pathnamevoid

    Delete the directory at the specified path.

    current-directory

    [pathname]string

    Return the current working directory. With an argument, set the working directory to the specified path.

    Up

    Low-level I/O

    Fundamentally, Pocket Scheme models low-level I/O as a (buffered) stream of octets: exact integers in the range 0..255, each representing a sequence of 8 bits of data.

  • Sources and sinks
  • Numeric I/O
  • Block numeric I/O
  • Character encoding
  • Up

    Sources and sinks

    open-raw-input-file

    filenameraw-input-source

    Takes a string naming an existing file and returns an object, a raw input source, capable of delivering unprocessed octets from the file.

    open-raw-output-file

    filenameraw-output-sink

    Takes a string naming a file to be created and returns a raw output sink, capable of delivering unprocessed octets to a new file of that name.

    open-input-raw-vector

    u8vec [start end]raw-input-source

    Creates a raw input source that delivers octets from a u8 raw vector. The optional start and end parameters, if supplied, specify a half-open range of indices into the raw vector. Compare with open-input-string.

    open-output-raw-vector

    raw-output-sink

    Creates a raw output sink that accumulates octets written to it. A subsequent call to get-output-raw-vector on this sink will return those octets. Compare with open-output-string.

    get-output-raw-vector

    osnku8-raw-vector

    Called on a raw output sink returned by open-output-raw-vector, returns a raw vector containing all octets written to that sink. Compare with get-output-string.

    open-output-raw-vector!

    u8vec [start end]raw-output-sink

    Creates a raw output sink that stores its octets in the given raw vector u8vec. Such an output sink requires no subsequent call to get-output-raw-vector. The optional start and end parameters, if supplied, specify a half-open range of indices into the raw vector.

    raw-input-source?

    objBoolean

    Returns #t if object is a raw input source, #f otherwise.

    raw-output-sink?

    objBoolean

    Returns #t if object is a raw output sink, #f otherwise.

    file-position

    isrc [offset]integer

    Returns the number of octets previously read from a raw input file, or written to a raw output file. With an offset, seeks within the stream as if the specified number.

    force-output

    osnkvoid

    Ensures that any octets potentially buffered in an output stream have been written to the backing device.

    octets-ready?

    isrc [count]Boolean

    Returns #t if the specified raw input source has data ready for the specified number of calls to read-octet (default 1), or at EOF, or if EOF is within the specified count; #f otherwise. A return value of #f means that a read call may potentially block. On streams associated with non-interactive devices and counts greater than 1, the system may use this as a hint to read ahead.

    close-raw-input-source

    isrcvoid

    Close the specified raw input source, making it incapable of producing octets.

    close-raw-output-sink

    osnkvoid

    Close the specified raw output sink, making it incapable of consuming octets.

    Up

    Numeric I/O

    read-octet

    isrcinteger

    Takes a single raw input source. Returns exact integer in range 0..255, or the eof object at end of stream.

    write-octet

    octet osnkvoid

    Takes two parameters, an exact integer in the range 0..255 and an raw output sink. Returns nothing.

    read-raw-number

    isrc count [endian signed?]integer

    Reads a sequence of octets from the stream, interpreting them as a raw machine integer. count is an exact nonnegative integer, specifying the number of octets to read; it must have the value 1, 2, 4, or 8. The optional Boolean signed? parameter, if supplied and true, specifies to interpret the sequence as a twos-complement representation of a signed integer; otherwise the result will be interpreted as unsigned, with the procedure returning a nonnegative value. The optional endian keyword symbol parameter specifies the order in which to interpret the octets as successive base-256 digits of an exact integer; unspecified, the implementation uses the host's default order. The procedure returns the eof object at end of file, or otherwise if it can read fewer than the specified count of octets.

    The endian parameter may take any one of the following values:

    Keyword Encoding
    big-endian most significant byte first
    little-endian least significant byte first
    network synonym for big-endian
    native use the ordering of the local hosting system
    host synonym for native

    write-raw-number

    osnk n count [endian]void

    Take the specified value n and encode it onto the output sink osnk as a sequence of octets. n must be an exact integer. If it is negative, the encoding will be two's complement signed; otherwise, it will be unsigned. The emitted encoding will occupy the specified count of base-256 digits, arranged per the endian attribute.

    read-raw-ieee754

    isrc count [endian]real

    Reads a sequence of octets from the stream, interpreting them as an IEEE-754 floating-point number and returning an inexact real quantity. count must be an exact integer, one of 4 or 8. The procedure will return #f if it cannot honor found NaN, -INF, or +INF values.

    write-raw-ieee754

    osnk x count [endian]void

    Take the specified value x and encode it onto the output sink osnk as a sequence of octets in IEEE754 format. and encode it as a sequence of octets in IEEE 754 format. count must be an exact integer, one of 4 or 8.

    Up

    Block numeric I/O

    read-raw-number-block

    isrc element-count octet-count [endian signed?]raw-vector or EOF

    Returns a raw vector, where each element of the vector has been read from the stream by read-raw-number. The procedure reads up to element-count items from the stream, or fewer upon encountering end of file. If the stream contains insufficient data to compose even a single raw number, i.e. fewer than octet-count octets, the procedure will return the eof object. The returned raw vector will be of a type that can accommodate the given values of octet-count and signed?: e.g., 2 and #t would return a 's16 raw vector. Note that this procedure does not test for (octets-ready? Stream (* octet-count element-count)): it reads for the entire amount, blocking, and taking what it can get. Also, since raw input sources support neither pushback nor read-ahead, any odd octets immediately before end of file will be lost, after the manner of the posix fread(3) call.

    read-raw-ieee754-block

    isrc element-count octet-count [endian]raw-vector or EOF

    Similar to read-raw-number-block, only decoding per IEEE 754 floating-point format, and returning a 'f32 or 'f64 raw vector. octet-count must be either 4 or 8.

    read-raw-number-block!

    uvec isrc [endian start end]integer or EOF

    Similar to read-raw-number-block or read-raw-ieee754-block, but destructively modifying an existing raw vector, reading elements into that vector at the half-open [start, end) interval. octet-count and signed? (cf. previous calls) are inferred from the type of the raw vector. Returns the number of elements read, or the EOF object at the end of file.

    write-raw-number-block

    uvec osnk [endian start end]void

    Writes the specified elements of the vector to the stream, as if by write-raw-number or write-raw-ieee754. octet-count and signed? (cf. previous calls) are inferred from the type of the raw vector, emitting single-precision floats from a f32, double-precision floats from a f64.

    Up

    Character encoding

    Many of these procedures take one or more external-format arguments, describing the manner in which a character is encoded on the stream.

    Symbol Encoding
    ascii 7 bits of ASCII character code within an 8 bit octet with the eighth bit clear
    latin-1 8 bits of Latin-1 character code in an 8 bit octet
    ucs-2be 16 bits of UCS-2 character code in two octets, big-endian
    ucs-2le 16 bits of UCS-2 character code in two octets, little-endian
    ucs-2 16 bits of UCS-2 character code in two octets, arranged host-native
    unicode Synonym for ucs-2
    system-ansi Default Windows codepage on the device. May represent one character in either one or two octets
    crlf-newline #\newline Scheme character represents two external characters CR, LF, as seen in TCP network protocols and Microsoft disk text files. This format is composable with any other external format.
    lf-newline #\newline Scheme character represents one external character LF, as seen in Unix disk text files. This format is composable with any other external format.
    emit-bom Emitted data includes a byte order mark. Output only. Composable with any Unicode external format.
    suppress-bom Emitted data does not include a byte order mark. Output only. Composable with any Unicode external format.

    unicode->char

    ncharacter or #f

    The fundamental character constructor. Returns the character corresponding to the specified Unicode codepoint. If it cannot represent the specified value, it will return #f.

    integer->char

    ncharacter

    Per R4RS. Synonym for unicode->char. Note that this does not deliver the "order-preserving isomorphisms" of R4RS.

    char->unicode

    cinteger

    Returns the Unicode codepoint value corresponding to the specified character.

    char->integer

    cinteger

    Per R4RS. Synonym for char->unicode. Again, note that this does not deliver the "order-preserving isomorphisms" of R4RS.

    read-raw-string

    isrc octet-count external-formatstring or EOF

    Reads octet-count octets from the specified input source, decoding them into characters per the specified external-format, and returning a new string of the characters. Will return EOF if insufficient octets remain on the stream to decode even a single character.

    raw-string-length

    str external-format [start end]integer

    Returns the number of octets that the given string str would require for the specified external format. The optional start and end are half-open indices into the string, per SRFI 13, the scsh read-string primitive, or the standard procedure substring.

    write-raw-string

    str osnk external-format [start end]void

    Encodes the characters in the given string str onto the output sink. start and end are half-open indices into the string.

    cook-input-source

    isrc octet-count external-formatinput-port

    Given a raw input source, create a proper input port that decodes from the stream. That input port will consume octet-count octets from the stream, returning EOF once it has consumed the specified count; octet-count may also be #f, in which case the input port will read from its backing stream until it completely exhausts the stream, or until close-input-port is called on the port. While this port is open, it is an error to call cook-input-source to create another such port on the same stream, and calling read-octet and its ilk will have unspecified effects (since the new port may be caching octets from its stream). A program may close a character port before it exhausts its specified octet count, whereupon any external format procedure will be called one last time with EOF. Subsequent calls to read-octet on the stream will then act as if a full octet-count number of calls to read-octet had taken place.

    cook-output-sink

    osnk external-formatoutput-port

    Given an output sink, create a proper output port that encodes onto the stream. While this port is open, it is an error to call cook-output-sink to create another such port on the same sink, and calling write-octet and its ilk will have unspecified effects (since the new port may be deferring encoding).

    cook-char-encoding

    portsymbol

    Returns a symbol representing the character encoding scheme on the given port. The port must be connected to external data, e.g., one created by open-output-file, but not open-output-string.

    cook-newline-encoding

    portsymbol

    Similar to cook-char-encoding, this procedure returns a symbol representing the newline encoding scheme on the given port. This will be either crlf-newline or lf-newline. The port must be connected to external data.

    Up

    Text I/O

    open-input-file

    filename [flags...]input-port

    Per R4RS.

    The flags may be any appropriate combination of external format specifiers.

    If no external format specifiers are supplied, the systems attempts to determine the format of the opened file and supply the correct data conversion.

    It is an error to open a file that does not exist or cannot be read. See file-exists?.

    with-input-from-file

    filename thunk [flags...]value

    Per R4RS, supporting the flags of open-input-file.

    call-with-input-file

    filename proc [flags...]value

    Per R4RS, supporting the flags of open-input-file.

    with-input-from-port

    port thunkvalue

    Generalization of with-input-from-file for any port.

    open-output-file

    filename [flags...]output-port

    Per R4RS.

    The flags may be a combination of external format specifiers or the following behavioral specifiers:

    Flag Behavior
    truncate-if-exists If opened file already exists, truncate it to length 0 before writing
    append-if-exists If opened file already exists, append data to its end
    error-if-exists If opened file already exists, raise an exception
    update-must-exist If opened file does not already exist, raise an exception

    with-output-to-file

    filename thunk [flags...]value

    Per R4RS, supporting the flags of open-output-file.

    call-with-output-file

    filename proc [flags...]value

    Per R4RS, supporting the flags of open-output-file.

    with-output-to-port

    port thunkvalue

    Generalization of with-output-to-file for any port.

    force-output

    [port]void

    Force an output port or raw octet sink to deliver any cached data. Without a parameter, defaults to the current output port.

    read-string

    [port count]string

    Read characters from the specified port, up to the number of characters specified. If no character count is specified, reads up to a newline character. Returns the string of characters, or the EOF object at end of file.

    read-string!

    string [port start end]integer

    Read characters from the specified port into the specified string. If the call specifies start and end, it enters the characters into the string at the half-open interval [start, end) (per the substring procedure). Return the number of characters read, or the EOF object at end of file.

    read-line

    [port]string

    Read a single line of input as a string. read-line differs from read-string without a character count by eliding the terminating newline character from the returned string. Returns the string, or the EOF object at end of file.

    write-string

    string [port start end]void

    Writes characters from the specified string into the specified port. If the call specifies start and end, it takes the charactes from the string at the half-open interval [start, end) (per the substring procedure). Return the number of characters read, or the EOF object at end of file.

    Up

    Soft ports

    make-input-port

    handlerinput-port

    Creates a new input port that queries the procedure handler for its content. An input port handler is a variable-arity procedure, called with one of the following symbols as its first argument:

    Flag Effect
    read-char Return a character
    peek-char Return a character. A subsequent call to read or peek will return this same character
    char-ready? Return #t if a read will not block, per the semantics of the standard Scheme procedure of this name
    close-port Port is closing

    make-output-port

    handleroutput-port

    Creates a new output port that queries the procedure handler for the disposition of its content. An output port handler is a variable-arity procedure, called with one of the following symbols as its first argument:

    Flag Effect
    write-char Second argument is a character to write
    force-output Write any pending cached data
    close-port Port is closing

    make-input-octet-source

    handlerraw-input-source

    Similar to make-input-port, but creates a raw input source rather than an input port. Its handler delivers octets, not characters.

    Flag Effect
    read-octet Return an octet
    data-ready? Return #t if a read will not block, per the semantics of the Pocket Scheme procedure of this name. Second argument is the number of octets expected
    close-port Octet source is closing

    make-output-octet-sink

    handlerraw-output-sink

    Similar to make-output-port, but creates a raw output sink rather than an output port. Its handler receives octets, not characters.

    Flag Effect
    write-octet Second argument is an octet to write
    force-output Write any pending cached data
    close-port Octet sink is closing
    Up

    Raw vectors

    The raw vector data type provides Pocket Scheme with an efficient medium for binary file I/O. Unlike standard Scheme vectors, raw vectors have homogeneous numeric elements, with a range limited by the fundamental raw machine datatype of the vector:

    Name Raw machine type
    u8 unsigned 8 bit exact integer
    s8 signed 8 bit exact integer
    u16 unsigned 16 bit exact integer
    s16 signed 16 bit exact integer
    u32 unsigned 32 bit exact integer
    s32 signed 32 bit exact integer
    u64 unsigned 64 bit exact integer
    s64 signed 64 bit exact integer
    f32 single-precision 32-bit inexact real
    f64 double-precision 64-bit inexact real

    Raw vectors are similar to the arrays of SIOD, the uniform vectors of SCM, or the homogeneous numeric vectors of Gambit and SRFI-4 (q.v. http://srfi.schemers.org/srfi-4/srfi-4.html).

    make-raw-vector

    k typeraw-vector

    Create a new raw vector with k elements of the specified type.

    raw-vector-ref

    v inumber

    Return the index-i element of raw vector v.

    raw-vector-set!

    v i dvoid

    Set the index-i element of raw vector v to value d.

    raw-vector?

    objectBoolean

    Predicate, returning #t if the argument is a raw vector.

    raw-vector-length

    vinteger

    Returns the number of elements in a raw vector.

    raw-vector-type

    vsymbol

    Returns the symbol naming the type of a raw vector. This will be one of the symbols in the table above.

    Up

    Strings

    string-breakup

    source separatorlist

    Scan the given string source, returning a list of its substrings as delimited by the substring separator.

    string-unbreakup

    string-list separatorstring

    Concatenate all strings in string-list, separating them by the string separator.

    For any string s and any separator r, the following relation holds: (string=? s (string-unbreakup (string-breakup s r) r)).

    Up

    Numerics

    zero?

    numberBoolean

    Per the Scheme standard.

    In addition to numbers, this predicate will accept a foreign as an argument, returning #t if the foreign has a bit-pattern of #x00000000.

    ash

    n countinteger

    Arithmetical shift left or right. n, the number to shift, must be a nonnegative integer, or a foreign. count gives the number of places to shift: positive to the left, negative to the right. The value returned is of the same type as the first argument, either a nonnegative integer or a foreign. The value of n must be less than (expt 2 32).

    bit-and

    n1 n2 [n3 ...]integer

    Bitwise AND. The procedure takes nonnegative integers or foreigns as parameters, returning a foreign value if any value is foreign, or a nonnegative integer otherwise. The value of n must be less than (expt 2 32).

    bit-or

    n1 n2 [n3 ...]integer

    Similar to bit-and, but performing bitwise OR.

    bit-xor

    n1 n2integer

    Similar to bit-and, but performing bitwise XOR, and limited to two parameters.

    bit-not

    ninteger

    Bitwise NOT, reversing the bits in its argument. The procedure takes a nonnegative integer or foreigns as its parameter, returning a value of the same type as the parameter given. The value of n must be less than (expt 2 32).

    Up

    Foreigns

    A foreign is a non-numeric 32-bit quantity, used when interfacing to external code libraries via the FFI in w32.dll.

    Note that the following numeric procedures also operate on foreigns: zero?, ash, bit-and, bit-or, bit-xor, bit-not.

    foreign?

    objectBoolean

    Returns #t if object is a foreign, #f otherwise.

    foreign->integer

    foreigninteger

    Converts the foreign quantity to an unsigned, nonnegative integer. To interpret a foreign as a signed integer, bias the value as follows: (- (foreign->integer x) (expt 2 32))

    integer->foreign

    integerforeign

    Converts an integer to a foreign quantity.

    foreign->string

    addressstring

    Given a foreign (non-Scheme) datum, returns a string that aliases the foreign data. The foreign datum must be a pointer to an array of 16-bit UCS-2 characters, terminated with a U+0000.

    All string-ref and string-set! operations work directly against the foreign character data.

    Use this procedure with caution. Scheme will not manage foreign memory. Passing an improper argument to this procedure can crash the interpreter or corrupt data.

    string->foreign

    stringforeign

    Converts a string to a foreign, naming the address of the string's data.

    Use this procedure with caution. Scheme will not manage foreign memory. This value may persist beyond the lifetime of the source string.

    foreign->raw-vector

    address dim kindraw-vector

    Given a foreign (non-Scheme) datum, returns a raw vector that aliases the foreign data. The foreign datum must be a pointer to an array of dim elements of the specified type, per the raw vector specification.

    All raw-vector-ref and raw-vector-set! operations work directly against the foreign data.

    Use this procedure with caution. Scheme will not manage foreign memory. Passing an improper argument to this procedure can crash the interpreter or corrupt data.

    raw-vector->foreign

    addressforeign

    Converts a raw vector to a foreign, naming the address of the raw vector's data.

    Use this procedure with caution. Scheme will not manage foreign memory. This value may persist beyond the lifetime of the source raw vector.

    Up

    List utilities

    make-list

    count elementlist

    Create a new list of count cells, each containing element.

    append2

    list1 list2list

    Simple two-element form of the Scheme standard append.

    append!

    list1 list2list

    Destructive form of the Pocket Scheme append2, changing list1.

    reverse!

    listlist

    Destructive form of the Scheme standard reverse.

    last

    listcons

    Returns the final pair of a list.

    butlast

    listcons

    Returns the penultimate pair of a list.

    Up

    Miscellaneous procedures

    version

    list

    Returns a list of four numbers describing the current version of Pocket Scheme: major version number, minor version number, update number, and build number.

    void-object?

    anyBoolean

    Returns #t if its argument is the void object, returned by procedures that return no useful value.

    void

    void

    Returns the void object.

    Up

    Extension libraries

    Pocket Scheme is extensible through binary extension libraries: DLLs containing additional commands and data types for the language.

    To load an extension library, use the load or require command, as you would on any other body of Scheme code.

  • REGEX, regular expressions
  • SS, TCP/IP socket streams
  • W32, Win32 API and FFI
  • Up

    REGEX, regular expressions

    The extension library regex locates character patterns within strings, described as regular expressions.

    regex regex-match regex?

    To access these functions, issue the command (load "regex.dll").

    regex

    pattern [flags]rx

    Create a new regular expression object from the regular expression described in the pattern. Pattern-strings use the POSIX regular expression syntax. The optional flags parameter is either one symbol or a list of symbols, as follows:

    Flag Meaning
    no-values Return only #t or #f to matches using this expression
    newline Use special newline treatment for matches against beginning or end of lines.
    ignore-case When matching character values, ignore case distinctions
    literal Match literal contents of pattern string, ignoring any special meanings

    regex-match

    regex string [flags]list

    Search a string of text for matches against the regular expression. The optional: flags parameter is either one symbol or a list of symbols, as follows:

    Flag Effect
    not-at-bol String does not include beginning of line
    nor-at-eol String does not include end of line

    If the string matches the regular expression, the procedure will return a list of pairs. The first pair will specify the indices of the entire matched sequence as the half-open interval (start, end]: in other words, the initial offset of the matched sequence, along with the offset of the remainder of the string not part of the sequence. If the regular expression contained subexpressions, subsequent pairs in the list will specify the indices of each matched subexpression.

    regex?

    anyBoolean

    Returns #t if its argument is a regular expression, #f otherwise.

    Up

    SS, TCP/IP socket streams

    The extension library ss provides a simple interface to connection-oriented network stream sockets.

    tcp:connect-client tcp:connection-input tcp:connection-output tcp:close-connection tcp:connection? tcp:listen-server tcp:accept-connection tcp:close-listener tcp:listener? tcp:timeout-seconds tcp:remote-address tcp:local-address tcp:remote-port tcp:local-port tcp:host-info tcp:service-info tcp:gethostname

    To access these functions, issue the command (load "ss.dll").

    tcp:connect-client

    host portconnection

    Return a connection to the named host on the named port.

    tcp:connection-input

    connraw-input-source

    Return a raw input source associated with an open connection. Octet reads from this source will receive data from the remote host.

    tcp:connection-output

    connraw-output-sink

    Return a raw output sink associated with an open connection. Octet writes to this sink will send data to the remote host.

    tcp:close-connection

    connvoid

    Close an open connection.

    tcp:connection?

    anyBoolean

    Return #t if the parameter is a connection object returned by tcp:connect-client or tcp:accept-connection.

    tcp:listen-server

    port [queue host]listener

    Return a listener that waits for clients to connect to the named port. Optionally specifies the number of clients to hold in queue, as well as the host address to use.

    tcp:accept-connection

    listenerconnection

    Return a connection to a pending client. If no clients are pending, this procedure will wait for one to arrive.

    tcp:close-listener

    listenervoid

    Close a waiting listener.

    tcp:listener?

    anyBoolean

    Return #t if the parameter is a listener object returned by tcp:listen-server.

    tcp:timeout-seconds

    object [seconds]integer or #f

    Returns the number of seconds for which operations on a connection or listener will wait before raising the exception exn:timeout. With two parameters, sets the timeout on a particular object.

    Calls on an object with no timeout will block until either the call receives enough data to continue or else the system raises another exception, e.g. exn:break.

    tcp:remote-address

    connectionstring

    Return the remote address of an open connection.

    tcp:local-address

    connectionstring

    Return the local address of an open connection.

    tcp:remote-port

    connectioninteger

    Return the remote port of an open connection.

    tcp:local-port

    connectioninteger

    Return the local port of an open connection.

    tcp:host-info

    hostlist

    Given a host name or address, returns a list of information about that host: name, aliases, addresses, address type.

    tcp:service-info

    servicelist

    Given a service name, returns a list of information about that service: name, aliases, port, protocol. Aliases will always be the empty list. (Since Windows CE lacks a /etc/services file, the set of known services is fixed within the extension.)

    tcp:gethostname

    string

    Return the local hostname.

    Up

    W32, Win32 API and FFI

    The extension library w32 provides a foreign function interface to Win32 system calls, as well as some general Windows utilities.

    w32:getopenfilename w32:getsavefilename w32:string->clipboard w32:clipboard->string w32:beep w32:foreign-procedure w32:declare-foreign-struct w32:register-class w32:create-window w32:dialog-box w32:dialog-box-indirect w32:create-dialog w32:create-dialog-indirect

    To access these functions, issue the command (load "w32.dll").

    w32:getopenfilename

    filters flags [initial-directory default-extension]string

    Present the standard dialog for getting a filename to open. Filters is a list of file descriptions and wildcard patterns. Flags is either one symbol or a list of symbols, as follows:
    Flag Effect
    file-must-exist The user must select the name of an existing file.
    prompt-create Prompt the user if the file does not exist.
    Initial-directory specifies the name of the directory in which to start, while default-extension supplies a default file extension.

    The following expression prompts for the name of a Scheme file in the topmost (default) directory:

    (w32:getopenfilename 
    	'("Scheme documents (*.scm)" "*.scm") 
    	'file-must-exist)

    Caveat: this procedure depends on system functionality. Unfortunately, some versions of Windows CE may not correctly support some flags.

    w32:getsavefilename

    filters flags [initial-directory default-extension]string

    Present the standard dialog for getting a filename to save. The parameters are the same as those to w32:getopenfilename, with the following flags:
    Flag Effect
    path-must-exist The user must select a name within an existing directory.
    file-must-exist The user must select the name of an existing file.
    prompt-create Prompt the user if the file does not exist.
    prompt-overwrite Prompt the user if the file already exists.

    Caveat: this procedure depends on system functionality. Unfortunately, some versions of Windows CE may not correctly support some flags.

    w32:string->clipboard

    svoid

    Take a string argument and copy it into the Windows clipboard, where other processes can access its data.

    w32:clipboard->string

    string

    Return the current contents of the system clipboard as a string.

    w32:beep

    [type]void

    Generates sound from the device speaker. The optional type parameter may be any one of the following symbols, specifying the particular sound to play: default question hand asterisk exclamation.

    w32:foreign-procedure

    dllname procname typelistproc

    Given a foreign (non-Scheme) procedure in a dynamic link library, load that procedure and return a Scheme-applicable procedure object. Dllname gives the path to the DLL, while procname specifies the name by which the DLL exports the procedure.

    Typelist is a list of symbols describing the calling sequence and parameters expected by the foreign procedure. The first element of the list must be w32api, specifying the calling sequence of exported system calls. The second element of the list specifies the return value of the procedure, one of the following symbols: void bool dword handle lpwstr lpcwstr lpvoid. Subsequent elements in the list specify the type of each parameter to the procedure.

    w32:declare-foreign-struct

    name tags layoutsyntax

    Takes the name of a foreign structure, the names of its fields, and the layout of the structure, generating a raw constructor for the structure, plus accessor and mutator procedures for each named field in the structure. For a structure 'S' with a field 'f', the macro will define a constructor make-S, an accessor S-f, a mutator S-f-set!, and the symbol S_sizeof.

    name is the name of the structure, e.g. RECT. tags is an ordered list of the fields in the structure. Each tag must correspond to its corresponding element in the layout vector. Specify #f to elide the accessor/mutator for this field, e.g. for the rgbReserved in a PAINTSTRUCT. The list may be empty, in which case the macro treats the entire structure as opaque, i.e. generates no accessors or mutators. layout is an ordered vector specifying the size in bytes/type of each field in the structure. An array of types is specified by a list of the size/type, followed by the count, e.g., (dword 4) or (wchar 16). Any array of char or wchar is assumed to be a 0-terminated C string. An embedded structure is specified by the appropriate types vector, though it is usually more convenient simply to embed the size of the embedded struct.

    w32:register-class

    name hinstance style resourcesBoolean

    Registers a window class for subsequent use with w32:create-window. name is a string naming the class of windows to register. hinstance is a foreign, the handle of the registering application. style is an integer specifying the class style bits. resources is a list of the icon handle and background brush (both foreign values) to use as defaults when painting windows of this class, or #f to use the system default.

    w32:create-window

    class title styles pos/size parent child-id hinstance proc [hints]Boolean

    Creates a window of the specified class, returning a handle to that window. class is a string value previously given to w32:register-class. title is a string captioning the window. styles is a list of integer values specifying the window style and extended window style bits, or #f for a default. pos/size is a list of integer values specifying the window starting x, y, dx, and dy coordinates and sizes, or #f for a default. parent is a handle to the parent to the parent or owning window, or 0 for top-level/desktop. child-id is the integer child ID, for child windows. hinstance is the instance handle of the creating application. proc is the window procedure to use, expecting four parameters: a window handle, a message code, the wparam, and the lparam. hints is a vector naming the messages handled by the window procedure.

    The proc returns an integer value, typically 0, for every handled case. All unhandled cases must return the value of an explicit call to the Win32 DefWindowProc API. Exception: a window created with a hint vector need not call DefWindowProc, as it will receive only messages named in the vector.

    w32:dialog-box

    hinstance resource parent procBoolean

    Loads a dialog from a specified resource, and runs it modally. hinstance is the instance handle of the application. resource is the resource to use, either a string or an integer; integer values must be coerced to foreign. parent is a handle to the owning window. proc is the dialog procedure to use, expecting four parameters: a window handle, a message code, the wparam, and the lparam.

    The dialog procedure resembles a window procedure, except that it returns a Boolean value instead of an integer, with all handled cases returning #t, and all unhandled cases returning #f. Also, a dialog procedure does not itself explicitly call either DefWindowProc or DefDialogProc.

    w32:dialog-box-indirect

    hinstance data parent procBoolean

    Creates a dialog from immediate data, and runs it modally.

    w32:create-dialog

    hinstance resource parent procforeign

    Loads a dialog from a specified resource, returning the window handle.

    w32:create-dialog-indirect

    hinstance data parent procforeign

    Creates a dialog from immediate data, returning the window handle.

    Up

    Last modified: 2 January 2006 for Pocket Scheme 1.2.1.

    Copyright 1998-2006, Ben Goetter. All rights reserved.