# Unit library

This unit contains basic Scheme definitions. This unit is used by default, unless the program is compiled with the `-explicit-use` option.

## Arithmetic

### add1

### sub1

    [procedure] (add1 N)
    [procedure] (sub1 N)

Adds/subtracts 1 from `N`.

### bitwise-and

### bitwise-ior

### bitwise-xor

### bitwise-not

### arithmetic-shift

    [procedure] (bitwise-and N1 ...)
    [procedure] (bitwise-ior N1 ...)
    [procedure] (bitwise-xor N1 ...)
    [procedure] (bitwise-not N)
    [procedure] (arithmetic-shift N1 N2)

Binary integer operations. `arithmetic-shift` shifts the argument `N1` by `N2` bits to the left. If `N2` is negative, than `N1` is shifted to the right. These operations only accept exact integers or inexact integers in word range (32 bit signed on 32-bit platforms, or 64 bit signed on 64-bit platforms).

### bit-set?

    [procedure] (bit-set? N INDEX)

Returns `#t` if the bit at the position `INDEX` in the integer `N` is set, or `#f` otherwise. The rightmost/least-significant bit is bit 0.

### fixnum?

    [procedure] (fixnum? X)

Returns `#t` if `X` is a fixnum, or `#f` otherwise.

### fx+

### fx-

### fx*

### fx/

### fxmod

### fxneg

### fxmin

### fxmax

### fx=

### fx>

### fx<

### fx>=

### fx<=

### fxand

### fxior

### fxxor

### fxnot

### fxshl

### fxshr

    [procedure] (fx+ N1 N2)
    [procedure] (fx- N1 N2)
    [procedure] (fx* N1 N2)
    [procedure] (fx/ N1 N2)
    [procedure] (fxmod N1 N2)
    [procedure] (fxneg N)
    [procedure] (fxmin N1 N2)
    [procedure] (fxmax N1 N2)
    [procedure] (fx= N1 N2)
    [procedure] (fx> N1 N2)
    [procedure] (fx< N1 N2)
    [procedure] (fx>= N1 N2)
    [procedure] (fx<= N1 N2)
    [procedure] (fxand N1 N2)
    [procedure] (fxior N1 N2)
    [procedure] (fxxor N1 N2)
    [procedure] (fxnot N)
    [procedure] (fxshl N1 N2)
    [procedure] (fxshr N1 N2)

Arithmetic fixnum operations. These procedures do not check their arguments, so non-fixnum parameters will result in incorrect results. `fxneg` negates its argument.

On division by zero, `fx/` and `fxmod` signal a condition of kind `(exn arithmetic)`.

`fxshl` and `fxshr` perform arithmetic shift left and right, respectively.

### flonum?

### fp+

### fp-

### fp*

### fp/

### fpneg

### fpmin

### fpmax

### fp=

### fp>

### fp<

### fp>=

### fp<=

    [procedure] (flonum? X)
    [procedure] (fp+ X Y)
    [procedure] (fp- X Y)
    [procedure] (fp* X Y)
    [procedure] (fp/ X Y)
    [procedure] (fpneg X)
    [procedure] (fpmin X Y)
    [procedure] (fpmax X Y)
    [procedure] (fp= X Y)
    [procedure] (fp> X Y)
    [procedure] (fp< X Y)
    [procedure] (fp>= X Y)
    [procedure] (fp<= X Y)

Arithmetic floating-point operations. In safe mode, these procedures throw a type error with non-float arguments (except `flonum?`, which returns `#f`). In unsafe mode, these procedures do not check their arguments. A non-flonum argument in unsafe mode can crash the system.

### signum

    [procedure] (signum N)

Returns `1` if `N` is positive, `-1` if `N` is negative or `0` if `N` is zero. `signum` is exactness preserving.

### finite?

    [procedure] (finite? N)

Returns `#f` if `N` is negative or positive infinity, and `#f` otherwise.

## File Input/Output

### current-output-port

    [procedure] (current-output-port [PORT])

Returns default output port. If `PORT` is given, then that port is selected as the new current output port.

Note that the default output port is not buffered. Use `set-buffering-mode!` if you need a different behaviour.

### current-error-port

    [procedure] (current-error-port [PORT])

Returns default error output port. If `PORT` is given, then that port is selected as the new current error output port.

Note that the default error output port is not buffered. Use `set-buffering-mode!` if you need a different behaviour.

### flush-output

    [procedure] (flush-output [PORT])

Write buffered output to the given output-port. `PORT` defaults to the value of `(current-output-port)`.

### port-name

    [procedure] (port-name PORT)

Fetch filename from `PORT`. This returns the filename that was used to open this file. Returns a special tag string, enclosed into parentheses for non-file ports.

### port-position

    [procedure] (port-position PORT)

Returns the current position of `PORT` as two values: row and column number. If the port does not support such an operation an error is signaled. This procedure is currently only available for input ports.

### set-port-name!

    [procedure] (set-port-name! PORT STRING)

Sets the name of `PORT` to `STRING`.

## Files

### delete-file

    [procedure] (delete-file STRING)

Deletes the file with the pathname `STRING`. If the file does not exist, an error is signaled.

### file-exists?

    [procedure] (file-exists? STRING)

Returns `STRING` if a file with the given pathname exists, or `#f` otherwise.

### rename-file

    [procedure] (rename-file OLD NEW)

Renames the file or directory with the pathname `OLD` to `NEW`. If the operation does not succeed, an error is signaled.

## String ports

### get-output-string

    [procedure] (get-output-string PORT)

Returns accumulated output of a port created with `(open-output-string)`.

### open-input-string

    [procedure] (open-input-string STRING)

Returns a port for reading from `STRING`.

### open-output-string

    [procedure] (open-output-string)

Returns a port for accumulating output in a string.

## Feature identifiers

CHICKEN maintains a global list of features naming functionality available int the current system. Additionally the `cond-expand` form accesses this feature list to infer what features are provided. Predefined features are `chicken`, and the SRFIs (Scheme Request For Implementation) provided by the base system: `srfi-23, srfi-30, srfi-39`. If the `eval` unit is used (the default), the features `srfi-0, srfi-2, srfi-6, srfi-8, srfi-9` and `srfi-10` are defined. When compiling code (during compile-time) the feature `compiling` is registered. When evaluating code in the interpreter (csi), the feature `csi` is registered.

### features

    [procedure] (features)

Returns a list of all registered features that will be accepted as valid feature-identifiers by `cond-expand`.

### feature?

    [procedure] (feature? ID ...)

Returns `#t` if all features with the given feature-identifiers `ID ...` are registered.

### register-feature!

    [procedure] (register-feature! FEATURE ...)

Register one or more features that will be accepted as valid feature-identifiers by `cond-expand`. `FEATURE ...` may be a keyword, string or symbol.

### unregister-feature!

    [procedure] (unregister-feature! FEATURE ...)

Unregisters the specified feature-identifiers. `FEATURE ...` may be a keyword, string or symbol.

## Keywords

Keywords are special symbols prefixed with `#:` that evaluate to themselves. Procedures can use keywords to accept optional named parameters in addition to normal required parameters. Assignment to and bindings of keyword symbols is not allowed. The parameter `keyword-style` and the compiler/interpreter option `-keyword-style` can be used to allow an additional keyword syntax, either compatible to Common LISP, or to DSSSL.

### get-keyword

    [procedure] (get-keyword KEYWORD ARGLIST [THUNK])

Returns the argument from `ARGLIST` specified under the keyword `KEYWORD`. If the keyword is not found, then the zero-argument procedure `THUNK` is invoked and the result value is returned. If `THUNK` is not given, `#f` is returned.

    (define (increase x . args)
      (+ x (get-keyword #:amount args (lambda () 1))) )
    (increase 123)                                      ==> 124
    (increase 123 #:amount 10)                          ==> 133

Note: the `KEYWORD` may actually be any kind of object.

### keyword?

    [procedure] (keyword? X)

Returns `#t` if `X` is a keyword symbol, or `#f` otherwise.

### keyword->string

    [procedure] (keyword->string KEYWORD)

Transforms `KEYWORD` into a string.

### string->keyword

    [procedure] (string->keyword STRING)

Returns a keyword with the name `STRING`.

## Exceptions

CHICKEN implements the (currently withdrawn) SRFI-12 exception system. For more information, see the SRFI-12 document.

### condition-case

    [syntax] (condition-case EXPRESSION CLAUSE ...)

Evaluates `EXPRESSION` and handles any exceptions that are covered by `CLAUSE ...`, where `CLAUSE` should be of the following form:

    CLAUSE = ([VARIABLE] (KIND ...) BODY ...)

If provided, `VARIABLE` will be bound to the signalled exception object. `BODY ...` is executed when the exception is a property- or composite condition with the kinds given `KIND ...` (unevaluated). If no clause applies, the exception is re-signalled in the same dynamic context as the `condition-case` form.

    (define (check thunk)
      (condition-case (thunk)
        [(exn file) (print "file error")]
        [(exn) (print "other error")]
        [var () (print "something else")] ) )

    (check (lambda () (open-input-file "")))   ; -> "file error"
    (check (lambda () some-unbound-variable))  ; -> "othererror"
    (check (lambda () (signal 99)))            ; -> "something else"

    (condition-case some-unbound-variable
      [(exn file) (print "ignored)] )      ; -> signals error

### breakpoint

    [procedure] (breakpoint [NAME])

Programmatically triggers a breakpoint (similar to the `,br` top-level csi command).

All error-conditions signalled by the system are of kind `exn`. The following composite conditions are additionally defined:

    (exn arity)
Signalled when a procedure is called with the wrong number of arguments.
    (exn type)
Signalled on type-mismatch errors, for example when an argument of the wrong type is passed to a builtin procedure.
    (exn arithmetic)
Signalled on arithmetic errors, like division by zero.
    (exn i/o)
Signalled on input/output errors.
    (exn i/o file)
Signalled on file-related errors.
    (exn i/o net)
Signalled on network errors.
    (exn bounds)
Signalled on errors caused by accessing non-existent elements of a collection.
    (exn runtime)
Signalled on low-level runtime-system error-situations.
    (exn runtime limit)
Signalled when an internal limit is exceeded (like running out of memory).
    (exn match)
Signalled on errors raised by failed matches (see the section on `match`).
    (exn syntax)
Signalled on syntax errors.
    (exn breakpoint)
Signalled when a breakpoint is reached.

Notes:

- All error-exceptions (of the kind `exn`) are non-continuable.
- Error-exceptions of the `exn` kind have additional `arguments` and `location` properties that contain the arguments passed to the exception-handler and the name of the procedure where the error occurred (if available).
- When the `posix` unit is available and used, then a user-interrupt (`signal/int`) signals an exception of the kind `user-interrupt`.
- the procedure `condition-property-accessor` accepts an optional third argument. If the condition does not have a value for the desired property and if the optional argument is given, no error is signalled and the accessor returns the third argument.
- In composite conditionss all properties are currently collected in a single property-list, so in the case that to conditions have the same named property, only one will be visible.

## Environment information and system interface

### argv

    [procedure] (argv)

Return a list of all supplied command-line arguments. The first item in the list is a string containing the name of the executing program. The other items are the arguments passed to the application. This list is freshly created on every invocation of `(argv)`. It depends on the host-shell whether arguments are expanded ('globbed') or not.

### exit

    [procedure] (exit [CODE])

Exit the running process and return exit-code, which defaults to 0 (Invokes `exit-handler`).

### build-platform

    [procedure] (build-platform)

Returns a symbol specifying the toolset which has been used for building the executing system, which is one of the following:

    cygwin
    msvc
    mingw32
    gnu
    metrowerks
    intel
    watcom
    unknown

### chicken-version

    [procedure] (chicken-version [FULL])

Returns a string containing the version number of the CHICKEN runtime system. If the optional argument `FULL` is given and true, then a full version string is returned.

### errno

    [procedure] (errno)

Returns the error code of the last system call.

### getenv

    [procedure] (getenv STRING)

Returns the value of the environment variable `STRING` or `#f` if that variable is not defined.

### machine-byte-order

    [procedure] (machine-byte-order)

Returns the symbol `little-endian` or `big-endian`, depending on the machine's byte-order.

### machine-type

    [procedure] (machine-type)

Returns a symbol specifying the processor on which this process is currently running, which is one of the following:

    alpha
    mips
    hppa
    ultrasparc
    sparc
    ppc
    ia64
    x86
    x86-64
    unknown

### on-exit

    [procedure] (on-exit THUNK)

Schedules the zero-argument procexdures `THUNK` to be executed before the process exits, either explicitly via `exit` or implicitly after exection of the last toplevel form. Note that finalizers for unreferenced finalized data are run before exit procedures.

### software-type

    [procedure] (software-type)

Returns a symbol specifying the operating system on which this process is currently running, which is one of the following:

    windows
    unix
    macos
    ecos
    unknown

### software-version

    [procedure] (software-version)

Returns a symbol specifying the operating system version on which this process is currently running, which is one of the following:

    linux
    freebsd
    netbsd
    openbsd
    macosx
    hpux
    solaris
    sunos
    unknown

### c-runtime

    [procedure] (c-runtime)

Returns a symbol that designates what kind of C runtime library has been linked with this version of the Chicken libraries. Possible return values are `static`, `dynamic` or `unknown`. On systems not compiled with the Microsoft C compiler, `c-runtime` always returns `unknown`.

### system

    [procedure] (system STRING)

Execute shell command. The functionality offered by this procedure depends on the capabilities of the host shell.

## Execution time

### cpu-time

    [procedure] (cpu-time)

Returns the used CPU time of the current process in milliseconds as two values: the time spent in user code, and the time spent in system code. On platforms where user and system time can not be differentiated, system time will be always be 0.

### current-milliseconds

    [procedure] (current-milliseconds)

Returns the number of milliseconds since process- or machine startup.

### current-seconds

    [procedure] (current-seconds)

Returns the number of seconds since midnight, Jan. 1, 1970.

### current-gc-milliseconds

    [procedure] (current-gc-milliseconds)

Returns the number of milliseconds spent in major garbage collections since the last call of `current-gc-milliseconds` and returns an exact integer.

## Interrupts and error-handling

### enable-warnings

    [procedure] (enable-warnings [BOOL])

Enables or disables warnings, depending on wether `BOOL` is true or false. If called with no arguments, this procedure returns `#t` if warnings are currently enabled, or `#f` otherwise. Note that this is not a parameter. The current state (wether warnings are enabled or disabled) is global and not thread-local.

### error

    [procedure] (error [LOCATION] [STRING] EXP ...)

Prints error message, writes all extra arguments to the value of `(current-error-port)` and invokes the current exception-handler. This conforms to SRFI-23. If `LOCATION` is given and a symbol, it specifies the location (the name of the procedure) where the error occurred.

### get-call-chain

    [procedure] (get-call-chain [START [THREAD]])

Returns a list with the call history. Backtrace information is only generated in code compiled without `-no-trace` and evaluated code. If the optional argument `START` is given, the backtrace starts at this offset, i.e. when `START` is 1, the next to last trace-entry is printed, and so on. If the optional argument `THREAD` is given, then the call-chain will only be constructed for calls performed by this thread.

### print-call-chain

    [procedure] (print-call-chain [PORT [START [THREAD]]])

Prints a backtrace of the procedure call history to `PORT`, which defaults to `(current-output-port)`.

### print-error-message

    [procedure] (print-error-message EXN [PORT [STRING]])

Prints an appropriate error message to `PORT` (which defaults to the value of `(current-output-port)` for the object `EXN`. `EXN` may be a condition, a string or any other object. If the optional argument `STRING` is given, it is printed before the error-message. `STRING` defaults to `"Error:"`.

### procedure-information

    [procedure] (procedure-information PROC)

Returns an s-expression with debug information for the procedure `PROC`, or `#f`, if `PROC` has no associated debug information.

### reset

    [procedure] (reset)

Reset program (Invokes `reset-handler`).

### warning

    [procedure] (warning STRING EXP ...)

Displays a warning message (if warnings are enabled with `enable-warnings`) and continues execution.

### singlestep

    [procedure] (singlestep THUNK)

Executes the code in the zero-procedure `THUNK` in single-stepping mode.

## Garbage collection

### gc

    [procedure] (gc [FLAG])

Invokes a garbage-collection and returns the number of free bytes in the heap. The flag specifies whether a minor (`#f`) or major (`#t`) GC is to be triggered. If no argument is given, `#t` is assumed. When the argument is `#t`, all pending finalizers are executed.

### memory-statistics

    [procedure] (memory-statistics)

Performs a major garbage collection and returns a three element vector containing the total heap size in bytes, the number of bytes currently used and the size of the nursery (the first heap generation). Note that the actual heap is actually twice the size given in the heap size, because CHICKEN uses a copying semi-space collector.

### set-finalizer!

    [procedure] (set-finalizer! X PROC)

Registers a procedure of one argument `PROC`, that will be called as soon as the non-immediate data object `X` is about to be garbage-collected (with that object as its argument). Note that the finalizer will not be called when interrupts are disabled. This procedure returns `X`.

### set-gc-report!

    [procedure] (set-gc-report! FLAG)

Print statistics after every GC, depending on `FLAG`. A value of `#t` shows statistics after every major GC. A true value different from `#t` shows statistics after every minor GC. `#f` switches statistics off.

## Other control structures

### andmap

    [procedure] (andmap PROC LIST1 ...)

Repeatedly calls `PROC` with arguments taken from `LIST1 ...`. If any invocation should return `#f`, the result of `andmap` is `#f`. If all invocations return a true result, then the result of `andmap` is `#t`.

### ormap

    [procedure] (ormap PROC LIST1 ...)

Repeatedly calls `PROC` with arguments taken from `LIST1 ...`. If any invocation should return a value different from `#f`, then this value is returned as the result of `ormap`. If all invocations return #f, then the result of `ormap` is `#f`.

### promise?

    [procedure] (promise? X)

Returns `#t` if `X` is a promise returned by `delay`, or `#f` otherwise.

## String utilities

### reverse-list->string

    [procedure] (reverse-list->string LIST)

Returns a string with the characters in `LIST` in reverse order. This is equivalent to `(list->string (reverse LIST))`, but much more efficient.

## Generating uninterned symbols

### gensym

    [procedure] (gensym [STRING-OR-SYMBOL])

Returns a newly created uninterned symbol. If an argument is provided, the new symbol is prefixed with that argument.

### string->uninterned-symbol

    [procedure] (string->uninterned-symbol STRING)

Returns a newly created, unique symbol with the name `STRING`.

## Standard Input/Output

### port?

    [procedure] (port? X)

Returns `#t` if `X` is a port object or `#f` otherwise.

### print

    [procedure] (print EXP1 EXP2 ...)

Outputs the arguments `EXP1 EXP2 ...` using `display` and writes a newline character to the port that is the value of `(current-output-port)`. Returns its first argument.

### print*

    [procedure] (print* EXP1 ...)

Similar to `print`, but does not output a terminating newline character and performs a `flush-outout` after writing its arguments.

## User-defined named characters

### char-name

    [procedure] (char-name SYMBOL-OR-CHAR [CHAR])

This procedure can be used to inquire about character names or to define new ones. With a single argument the behavior is as follows: If `SYMBOL-OR-CHAR` is a symbol, then `char-name` returns the character with this name, or `#f` if no character is defined under this name. If `SYMBOL-OR-CHAR` is a character, then the name of the character is returned as a symbol, or `#f` if the character has no associated name.

If the optional argument `CHAR` is provided, then `SYMBOL-OR-CHAR` should be a symbol that will be the new name of the given character. If multiple names designate the same character, then the `write` will use the character name that was defined last.

    (char-name 'space)                  ==> #\space
    (char-name #\space)                 ==> space
    (char-name 'bell)                   ==> #f
    (char-name (integer->char 7))       ==> #f
    (char-name 'bell (integer->char 7))
    (char-name 'bell)                   ==> #\bell
    (char->integer (char-name 'bell))   ==> 7

## Vectors

### vector-copy!

    [procedure] (vector-copy! VECTOR1 VECTOR2 [COUNT])

Copies contents of `VECTOR1` into `VECTOR2`. If the argument `COUNT` is given, it specifies the maximal number of elements to be copied. If not given, the minimum of the lengths of the argument vectors is copied.

Exceptions: `(exn bounds)`

### vector-resize

    [procedure] (vector-resize VECTOR N [INIT])

Creates and returns a new vector with the contents of `VECTOR` and length `N`. If `N` is greater than the original length of `VECTOR`, then all additional items are initialized to `INIT`. If `INIT` is not specified, the contents are initialized to some unspecified value.

## The unspecified value

### void

    [procedure] (void)

Returns an unspecified value.

## Continuations

### call/cc

    [procedure] (call/cc PROCEDURE)

An alias for `call-with-current-continuation`.

### continuation-capture

    [procedure] (continuation-capture PROCEDURE)

Creates a continuation object representing the current continuation and tail-calls `PROCEDURE` with this continuation as the single argument.

More information about this continuation API can be found in the paper http://repository.readscheme.org/ftp/papers/sw2001/feeley.pdf A Better API for first class Continuations by Marc Feeley.

### continuation?

    [procedure] (continuation? X)

Returns `#t` if `X` is a continuation object, or `#f` otherwise.

### continuation-graft

    [procedure] (continuation-graft CONT THUNK)

Calls the procedure `THUNK` with no arguments and the implicit continuation `CONT`.

### continuation-return

    [procedure] (continuation-return CONT VALUE ...)

Returns the value(s) to the continuation `CONT`. `continuation-return` could be implemented like this:

    (define (continuation-return k . vals)
      (continuation-graft
        k
        (lambda () (apply values vals)) ) )

## Setters

SRFI-17 is fully implemented. For more information see: SRFI-17.

### setter

    [procedure] (setter PROCEDURE)

Returns the setter-procedure of `PROCEDURE`, or signals an error if `PROCEDURE` has no associated setter-procedure.

Note that `(set! (setter PROC) ...)` for a procedure that has no associated setter procedure yet is a very slow operation (the old procedure is replaced by a modified copy, which involves a garbage collection).

### getter-with-setter

    [procedure] (getter-with-setter GETTER SETTER)

Returns a copy of the procedure `GETTER` with the associated setter procedure `SETTER`. Contrary to the SRFI specification, the setter of the returned procedure may be changed.

## Reader extensions

### define-reader-ctor

    [procedure] (define-reader-ctor SYMBOL PROC)

Define new read-time constructor for `#,` read syntax. For further information, see the documentation for SRFI-10.

### set-read-syntax!

    [procedure] (set-read-syntax! CHAR-OR-SYMBOL PROC)

When the reader is encounting the non-whitespace character `CHAR` while reading an expression from a given port, then the procedure `PROC` will be called with that port as its argument. The procedure should return a value that will be returned to the reader:

    ; A simple RGB color syntax:

    (set-read-syntax! #\%
      (lambda (port)
        (apply vector
          (map (cut string->number <> 16)

(string-chop (read-string 6 port) 2) ) ) ) )

    (with-input-from-string "(1 2 %f0f0f0 3)" read)
    ; ==> (1 2 #(240 240 240) 3)

If `CHAR-OR-SYMBOL` is a symbol, then a so-called read-mark handler is defined. In that case the handler procedure will be called when a character-sequence of the form

    #!SYMBOL

is encountered.

You can undo special handling of read-syntax by passing `#f` as the second argument (if the syntax was previously defined via `set-read-syntax!`).

Note that all of CHICKEN's special non-standard read-syntax is handled directly by the reader to disable built-in read-syntax, define a handler that triggers an error (for example).

### set-sharp-read-syntax!

    [procedure] (set-sharp-read-syntax! CHAR-OR-SYMBOL PROC)

Similar to `set-read-syntax!`, but allows defining new `#<CHAR> ...` reader syntax. If the first argument is a symbol, then this procedure is equivalent to `set-read-syntax!`.

### set-parameterized-read-syntax!

    [procedure] (set-parameterized-read-syntax! CHAR-OR-SYMBOL PROC)

Similar to `set-sharp-read-syntax!`, but intended for defining reader syntax of the form `#<NUMBER><CHAR> ...`. The handler procedure `PROC` will be called with two arguments: the input port and the number preceding the dispatching character. If the first argument is a symbol, then this procedure is equivalent to `set-read-syntax!`.

### copy-read-table

    [procedure] (copy-read-table READ-TABLE)

Returns a copy of the given read-table. You can access the currently active read-table with `(current-read-table)`.

Previous: Parameters

Next: Unit eval