chickadee » chicken » base

TOC »

Module (chicken base)

Core procedures and macros, acting as basic extensions to the R5RS standard and other essential features.

This module is used by default, unless a program is compiled with the -explicit-use option.

Numeric predicates

These allow you to make a more precise differentiation between number types and their properties, not provided by R5RS.

fixnum?

fixnum? Xprocedure

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

flonum?

flonum? Xprocedure

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

bignum?

bignum? Xprocedure

Returns #t if X is a bignum (integer larger than fits in a fixnum), or #f otherwise.

exact-integer?

exact-integer? Xprocedure

Returns #t if X is an exact integer (i.e., a fixnum or a bignum), or #f otherwise.

This procedure is compatible with the definition from the R7RS (scheme base) library.

cplxnum?

cplxnum? Xprocedure

Returns #t if X is a true complex number (it has an imaginary component), or #f otherwise.

Please note that complex? will always return #t for any number type supported by CHICKEN, so you can use this predicate if you want to know the representational type of a number.

ratnum?

ratnum? Xprocedure

Returns #t if X is a true rational number (it is a fraction with a denominator that's not 1), or #f otherwise.

Please note that rational? will always return #t for any number type supported by CHICKEN except complex numbers and non-finite flonums, so you can use this predicate if you want to know the representational type of a number.

nan?

nan? Nprocedure

Returns #t if N is not a number (a IEEE flonum NaN-value). If N is a complex number, it's considered nan if it has a real or imaginary component that's nan.

This procedure is compatible with the definition from the R7RS (scheme inexact) library.

infinite?

infinite? Nprocedure

Returns #t if N is negative or positive infinity, and #f otherwise. If N is a complex number, it's considered infinite if it has a real or imaginary component that's infinite.

This procedure is compatible with the definition from the R7RS (scheme inexact) library.

finite?

finite? Nprocedure

Returns #t if N represents a finite number and #f otherwise. Positive and negative infinity as well as NaNs are not considered finite. If N is a complex number, it's considered finite if both the real and imaginary components are finite.

This procedure is compatible with the definition from the R7RS (scheme inexact) library.

equal=?

equal=? X yprocedure

Similar to the standard procedure equal?, but compares numbers using the = operator, so equal=? allows structural comparison in combination with comparison of numerical data by value.

Arithmetic

add1/sub1

add1 Nprocedure
sub1 Nprocedure

Adds/subtracts 1 from N.

exact-integer-sqrt

exact-integer-sqrt Kprocedure

Returns two values s and r, where s^2 + r = K and K < (s+1)^2. In other words, s is the closest square root we can find that's equal to or smaller than K, and r is the rest if K isn't a neat square of two numbers.

This procedure is compatible with the definition from the R7RS (scheme base) library.

exact-integer-nth-root

exact-integer-nth-root K Nprocedure

Like exact-integer-sqrt, but with any base value. Calculates \sqrt[N]{K}, the Nth root of K and returns two values s and r where s^N + r = K and K < (s+1)^N.

Division with quotient and remainder

quotient&remainder X Yprocedure
quotient&modulo X Yprocedure

Returns two values: the quotient and the remainder (or modulo) of X divided by Y. Could be defined as (values (quotient X Y) (remainder X Y)), but is much more efficient when dividing very large numbers.

signum

signum Nprocedure

For real numbers, returns 1 if N is positive, -1 if N is negative or 0 if N is zero. signum is exactness preserving.

For complex numbers, returns a complex number of the same angle but with magnitude 1.

Lazy evaluation

delay-force

(delay-force <expression>)syntax

The expression (delay-force expression) is conceptually similar to (delay (force expression)), with the difference that forcing the result of delay-force will in effect result in a tail call to (force expression), while forcing the result of (delay (force expression)) might not.

Thus iterative lazy algorithms that might result in a long series of chains of delay and force can be rewritten using delay-force to prevent consuming unbounded space during evaluation.

This special form is compatible with the definition from the R7RS (scheme lazy) library.

See the description of force under Control features in the "scheme" module documentation for a more complete description of delayed evaluation.

For more information regarding the unbounded build-up of space, see the SRFI-45 rationale.

make-promise

make-promise objprocedure

The make-promise procedure returns a promise which, when forced, will return obj . It is similar to delay, but does not delay its argument: it is a procedure rather than syntax. If obj is already a promise, it is returned.

This procedure is compatible with the definition from the R7RS (scheme lazy) library.

promise?

promise? Xprocedure

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

This procedure is compatible with the definition from the R7RS (scheme lazy) library.

Input/Output

current-error-port

current-error-port #!optional PORTprocedure

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.

print

(print [EXP1 ...])procedure

Outputs the optional arguments EXP1 ... using display and writes a newline character to the port that is the value of (current-output-port). Returns (void).

print*

(print* [EXP1 ...])procedure

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

Interrupts and error-handling

enable-warnings

enable-warnings #!optional BOOLprocedure

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 (whether warnings are enabled or disabled) is global and not thread-local.

error

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

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.

assert

(assert EXP [OBJ ...])syntax

Evaluates EXP, if it returns #f error is applied to OBJ ..., else the result of EXP is returned. When compiling in unsafe mode, assertions of this kind are disabled.

get-call-chain

get-call-chain #!optional START THREADprocedure

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

print-call-chain #!optional PORT START THREAD HEADERprocedure

Prints a backtrace of the procedure call history to PORT, which defaults to (current-output-port). The output is prefixed by the HEADER, which defaults to "\n\tCall history:\n".

procedure-information

procedure-information PROCprocedure

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

warning

(warning MESSAGE [EXP ...])procedure

Displays a warning message (if warnings are enabled with enable-warnings), from the MESSAGE, and optional EXP arguments, then continues execution. MESSAGE, and EXP, may be any object.

Lists

alist-ref

alist-ref KEY ALIST #!optional TEST DEFAULTprocedure

Looks up KEY in ALIST using TEST as the comparison function (or eqv? if no test was given) and returns the cdr of the found pair, or DEFAULT (which defaults to #f).

alist-update

alist-update KEY VALUE ALIST #!optional TESTprocedure
alist-update! KEY VALUE ALIST #!optional TESTprocedure

If the list ALIST contains a pair of the form (KEY . X), then this procedure replaces X with VALUE and returns ALIST. If ALIST contains no such item, then alist-update returns ((KEY . VALUE) . ALIST). The optional argument TEST specifies the comparison procedure to search a matching pair in ALIST and defaults to eqv?. alist-update! is the destructive version of alist-update.

atom?

atom? Xprocedure

Returns #t if X is not a pair.

butlast

butlast LISTprocedure

Returns a fresh list with all elements but the last of LIST.

chop

chop LIST Nprocedure

Returns a new list of sublists, where each sublist contains N elements of LIST. If LIST has a length that is not a multiple of N, then the last sublist contains the remaining elements.

(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))
(chop '(a b c d) 3)     ==> ((a b c) (d))

compress

compress BLIST LISTprocedure

Returns a new list with elements taken from LIST with corresponding true values in the list BLIST.

(define nums '(99 100 110 401 1234))
(compress (map odd? nums) nums)      ==> (99 401)

flatten

flatten LIST1 ...procedure

Returns LIST1 ... concatenated together, with nested lists removed (flattened).

foldl

foldl PROCEDURE INIT LISTprocedure

Applies PROCEDURE to the elements from LIST, beginning from the left:

(foldl + 0 '(1 2 3))    ==>    (+ (+ (+ 0 1) 2) 3)

Note that the order of arguments taken by PROCEDURE is different from the SRFI-1 fold procedure, but matches the more natural order used in Haskell and Objective Caml.

foldr

foldr PROCEDURE INIT LISTprocedure

Applies PROCEDURE to the elements from LIST, beginning from the right:

(foldr + 0 '(1 2 3))    ==>    (+ 1 (+ 2 (+ 3 0)))

intersperse

intersperse LIST Xprocedure

Returns a new list with X placed between each element.

join

join LISTOFLISTS #!optional LISTprocedure

Concatenates the lists in LISTOFLISTS with LIST placed between each sublist. LIST defaults to the empty list.

(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)
(join '((p q) () (r (s) t)) '(-))  ==> (p q - - r (s) t)

join could be implemented as follows:

(define (join lstoflsts #!optional (lst '()))
  (apply append (intersperse lstoflists lst)) )

rassoc

rassoc KEY LIST #!optional TESTprocedure

Similar to assoc, but compares KEY with the cdr of each pair in LIST using TEST as the comparison procedures (which defaults to eqv?).

tail?

tail? X LISTprocedure

Returns true if X is one of the tails (cdr's) of LIST.

Vectors

vector-copy!

vector-copy! VECTOR1 VECTOR2 #!optional COUNTprocedure

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

vector-resize VECTOR N #!optional INITprocedure

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.

subvector

subvector VECTOR FROM #!optional TOprocedure

Returns a new vector with elements taken from VECTOR in the given range. TO defaults to (vector-length VECTOR).

subvector was introduced in CHICKEN 4.7.3.

Combinators

constantly

constantly X ...procedure

Returns a procedure that always returns the values X ... regardless of the number and value of its arguments.

(constantly X) <=> (lambda args X)

complement

complement PROCprocedure

Returns a procedure that returns the boolean inverse of PROC.

(complement PROC) <=> (lambda (x) (not (PROC x)))

compose

compose PROC1 PROC2 ...procedure

Returns a procedure that represents the composition of the argument-procedures PROC1 PROC2 ....

(compose F G) <=> (lambda args
                      (call-with-values
                         (lambda () (apply G args))
                         F))

(compose) is equivalent to values.

conjoin

conjoin PRED ...procedure

Returns a procedure that returns #t if its argument satisfies the predicates PRED ....

((conjoin odd? positive?) 33)   ==>  #t
((conjoin odd? positive?) -33)  ==>  #f

disjoin

disjoin PRED ...procedure

Returns a procedure that returns #t if its argument satisfies any predicate PRED ....

((disjoin odd? positive?) 32)    ==>  #t
((disjoin odd? positive?) -32)   ==>  #f

each

each PROC ...procedure

Returns a procedure that applies PROC ... to its arguments, and returns the result(s) of the last procedure application. For example

(each pp eval)

is equivalent to

(lambda args 
  (apply pp args)
  (apply eval args) )

(each PROC) is equivalent to PROC and (each) is equivalent to void.

flip

flip PROCprocedure

Returns a two-argument procedure that calls PROC with its arguments swapped:

(flip PROC) <=> (lambda (x y) (PROC y x))

identity

identity Xprocedure

Returns its sole argument X.

list-of?

list-of? PREDprocedure

Returns a procedure of one argument that returns #t when applied to a list of elements that all satisfy the predicate procedure PRED, or #f otherwise.

((list-of? even?) '(1 2 3))   ==> #f
((list-of? number?) '(1 2 3)) ==> #t

o

o PROC ...procedure

A single value version of compose (slightly faster). (o) is equivalent to identity.

User-defined named characters

char-name

char-name SYMBOL-OR-CHAR #!optional CHARprocedure

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

The unspecified value

void

void ARGUMENT ...procedure

Ignores ARGUMENT ... and returns an unspecified value.

Continuations

call/cc

call/cc PROCEDUREprocedure

An alias for call-with-current-continuation.

This procedure is compatible with the definition from the R7RS (scheme base) library.

Symbols

Symbol utilities

symbol-append
symbol-append SYMBOL1 ...procedure

Creates a new symbol from the concatenated names of the argument symbols (SYMBOL1 ...).

Uninterned symbols ("gensyms")

Symbols may be "interned" or "uninterned". Interned symbols are registered in a global table, and when read back from a port are identical to a symbol written before:

(define sym 'foo)

(eq? sym (with-input-from-string
            (with-output-to-string 
              (lambda () (write sym)))
	    read))

  => #t

Uninterned symbols on the other hand are not globally registered and so multiple symbols with the same name may coexist:

(define sym (gensym 'foo))   ; sym is a uninterned symbol like "foo42"

(eq? sym (with-input-from-string    ; the symbol read will be an interned symbol
            (with-output-to-string 
              (lambda () (write sym)))
	    read))

  => #f

(eq? (string->uninterned-symbol "foo") (string->uninterned-symbol "foo"))

  => #f

Use uninterned symbols if you need to generate unique values that can be compared quickly, for example as keys into a hash-table or association list. Note that uninterned symbols lose their uniqueness property when written to a file and read back in, as in the example above.

gensym
gensym #!optional STRING-OR-SYMBOLprocedure

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

string->uninterned-symbol
string->uninterned-symbol STRINGprocedure

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

Setters

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

setter

setter PROCEDUREprocedure

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

getter-with-setter GETTER SETTERprocedure

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.

Binding forms for optional arguments

optional

(optional ARGS DEFAULT)syntax

Use this form for procedures that take a single optional argument. If ARGS is the empty list DEFAULT is evaluated and returned, otherwise the first element of the list ARGS. It is an error if ARGS contains more than one value.

(define (incr x . i) (+ x (optional i 1)))
(incr 10)                                   ==> 11
(incr 12 5)                                 ==> 17

case-lambda

(case-lambda (LAMBDA-LIST1 EXP1 ...) ...)syntax

Expands into a lambda that invokes the body following the first matching lambda-list.

(define plus
  (case-lambda 
    (() 0)
    ((x) x)
    ((x y) (+ x y))
    ((x y z) (+ (+ x y) z))
    (args (apply + args))))

(plus)                      ==> 0
(plus 1)                    ==> 1
(plus 1 2 3)                ==> 6

For more information see the documentation for SRFI-16

This special form is also compatible with the definition from the R7RS (scheme case-lambda) library.

let-optionals

(let-optionals ARGS ((VAR1 DEFAULT1) ...) BODY ...)syntax

Binding constructs for optional procedure arguments. ARGS is normally a rest-parameter taken from a lambda-list. let-optionals binds VAR1 ... to available arguments in parallel, or to DEFAULT1 ... if not enough arguments were provided. let-optionals* binds VAR1 ... sequentially, so every variable sees the previous ones. it is an error if any excess arguments are provided.

(let-optionals '(one two) ((a 1) (b 2) (c 3))
  (list a b c) )                               ==> (one two 3)

let-optionals*

(let-optionals* ARGS ((VAR1 DEFAULT1) ... [RESTVAR]) BODY ...)syntax

Binding constructs for optional procedure arguments. ARGS is normally a rest-parameter taken from a lambda-list. let-optionals binds VAR1 ... to available arguments in parallel, or to DEFAULT1 ... if not enough arguments were provided. let-optionals* binds VAR1 ... sequentially, so every variable sees the previous ones. If a single variable RESTVAR is given, then it is bound to any remaining arguments, otherwise it is an error if any excess arguments are provided.

(let-optionals* '(one two) ((a 1) (b 2) (c a))
  (list a b c) )                               ==> (one two one)

Other binding forms

and-let*

(and-let* (BINDING ...) EXP1 EXP2 ...)syntax

Bind sequentially and execute body. BINDING can be a list of a variable and an expression, a list with a single expression, or a single variable. If the value of an expression bound to a variable is #f, the and-let* form evaluates to #f (and the subsequent bindings and the body are not executed). Otherwise the next binding is performed. If all bindings/expressions evaluate to a true result, the body is executed normally and the result of the last expression is the result of the and-let* form. See also the documentation for SRFI-2.

letrec*

(letrec* ((VARIABLE EXPRESSION) ...) BODY ...)syntax

Implements R6RS/R7RS letrec*. letrec* is similar to letrec but binds the variables sequentially and is to letrec what let* is to let.

This special form is compatible with the definition from the R7RS (scheme base) library.

rec

(rec NAME EXPRESSION)syntax
(rec (NAME VARIABLE ...) BODY ...)syntax

Allows simple definition of recursive definitions. (rec NAME EXPRESSION) is equivalent to (letrec ((NAME EXPRESSION)) NAME) and (rec (NAME VARIABLE ...) BODY ...) is the same as (letrec ((NAME (lambda (VARIABLE ...) BODY ...))) NAME).

cut

(cut SLOT ...)syntax
(cute SLOT ...)syntax

Syntactic sugar for specializing parameters.

define-values

(define-values (NAME ...) VALUEEXP)syntax
(define-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)syntax
(define-values NAME VALUEEXP)syntax

Defines several variables at once, with the result values of expression VALUEEXP, similar to set!-values.

This special form is compatible with the definition from the R7RS (scheme base) library.

fluid-let

(fluid-let ((VAR1 X1) ...) BODY ...)syntax

Binds the variables VAR1 ... dynamically to the values X1 ... during execution of BODY .... This implements SRFI-15.

let-values

(let-values (((NAME ...) VALUEEXP) ...) BODY ...)syntax

Binds multiple variables to the result values of VALUEEXP .... All variables are bound simultaneously. Like define-values, the (NAME ...) expression can be any basic lambda list (dotted tail notation is supported).

This special form implements SRFI-11, and it is also compatible with the definition from the R7RS (scheme base) library.

let*-values

(let*-values (((NAME ...) VALUEEXP) ...) BODY ...)syntax

Binds multiple variables to the result values of VALUEEXP .... The variables are bound sequentially. Like let-values, the (NAME ...) expression can be any basic lambda list (dotted tail notation is supported).

This is also part of SRFI-11 and is also compatible with the definition from the R7RS (scheme base) library.

(let*-values (((a b) (values 2 3))
              ((p) (+ a b)) )
  p)                               ==> 5

letrec-values

(letrec-values (((NAME ...) VALUEEXP) ...) BODY ...)syntax

Binds the result values of VALUEEXP ... to multiple variables at once. All variables are mutually recursive. Like let-values, the (NAME ...) expression can be any basic lambda list (dotted tail notation is supported).

(letrec-values (((odd even)
                   (values 
                     (lambda (n) (if (zero? n) #f (even (sub1 n))))
                     (lambda (n) (if (zero? n) #t (odd (sub1 n)))) ) ) )
  (odd 17) )                           ==> #t

receive

(receive (NAME ...) VALUEEXP BODY ...)syntax
(receive (NAME1 ... NAMEn . NAMEn+1) VALUEEXP BODY ...)syntax
(receive NAME VALUEEXP BODY ...)syntax
(receive VALUEEXP)syntax

SRFI-8. Syntactic sugar for call-with-values. Binds variables to the result values of VALUEEXP and evaluates BODY ..., similar define-values but lexically scoped.

(receive VALUEEXP) is equivalent to (receive _ VALUEEXP _). This shortened form is not described by SRFI-8.

set!-values

(set!-values (NAME ...) VALUEEXP)syntax
(set!-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)syntax
(set!-values NAME VALUEEXP)syntax

Assigns the result values of expression VALUEEXP to multiple variables, similar to define-values.

nth-value

(nth-value N EXP)syntax

Returns the Nth value (counting from zero) of the values returned by expression EXP.

Parameters

Parameters are CHICKEN's form of dynamic variables, except that they are procedures rather than actual variables. A parameter is a procedure of zero or one arguments. To retrieve the value of a parameter call the parameter-procedure with zero arguments. To change the setting of the parameter, call the parameter-procedure with the new value as argument:

(define foo (make-parameter 123))
(foo)                             ==> 123
(foo 99)
(foo)                             ==> 99

Parameters are fully thread-local, each thread of execution owns a local copy of a parameters' value.

CHICKEN implements SRFI-39, which is also standardized by R7RS.

parameterize

(parameterize ((PARAMETER1 X1) ...) BODY ...)syntax

Binds the parameters PARAMETER1 ... dynamically to the values X1 ... during execution of BODY .... (see also: make-parameter in Parameters). Note that PARAMETER may be any expression that evaluates to a parameter procedure.

This special form is compatible with the definition from the R7RS (scheme base) library.

make-parameter

make-parameter VALUE #!optional GUARDprocedure

Returns a procedure that accepts zero or one argument. Invoking the procedure with zero arguments returns VALUE. Invoking the procedure with one argument changes its value to the value of that argument and returns the new value (subsequent invocations with zero parameters return the new value). GUARD should be a procedure of a single argument. Any new values of the parameter (even the initial value) are passed to this procedure. The guard procedure should check the value and/or convert it to an appropriate form.

This special form is compatible with the definition from the R7RS (scheme base) library.

Substitution forms and macros

define-constant

(define-constant NAME CONST)syntax

Defines a variable with a constant value, evaluated at compile-time. Any reference to such a constant should appear textually after its definition. This construct is equivalent to define when evaluated or interpreted. Constant definitions should only appear at toplevel. Note that constants are local to the current compilation unit and are not available outside of the source file in which they are defined. Names of constants still exist in the Scheme namespace and can be lexically shadowed. If the value is mutable, then the compiler is careful to preserve its identity. CONST may be any constant expression, and may also refer to constants defined via define-constant previously, but it must be possible to evaluate the expression at compile-time.

define-inline

(define-inline (NAME VAR ...) BODY ...)syntax
(define-inline (NAME VAR ... . VAR) BODY ...)syntax
(define-inline NAME EXP)syntax

Defines an inline procedure. Any occurrence of NAME will be replaced by EXP or (lambda (VAR ... [. VAR]) BODY ...). This is similar to a macro, but variable names and scope are handled correctly.

Inline substitutions take place after macro-expansion, and any reference to NAME should appear textually after its definition. Inline procedures are local to the current compilation unit and are not available outside of the source file in which they are defined. Names of inline procedures still exist in the Scheme namespace and can be lexically shadowed. Inline definitions should only appear at the toplevel.

Note that the inline-limit compiler option does not affect inline procedure expansion, and self-referential inline procedures may cause the compiler to enter an infinite loop.

In the third form, EXP must be a lambda expression.

This construct is equivalent to define when evaluated or interpreted.

Conditional forms

unless

(unless TEST EXP1 EXP2 ...)syntax

Equivalent to:

(if (not TEST) (begin EXP1 EXP2 ...))

when

(when TEST EXP1 EXP2 ...)syntax

Equivalent to:

(if TEST (begin EXP1 EXP2 ...))

Record structures

define-record

(define-record NAME SLOTNAME ...)syntax

Defines a record type. This defines a number of procedures for creating, accessing, and modifying record members.

Call make-NAME to create an instance of the structure (with one initialization-argument for each slot, in the listed order).

(NAME? STRUCT) tests any object for being an instance of this structure.

Slots are accessed via (NAME-SLOTNAME STRUCT) and updated using (NAME-SLOTNAME-set! STRUCT VALUE).

(define-record point x y)
(define p1 (make-point 123 456))
(point? p1)                      ==> #t
(point-x p1)                     ==> 123
(point-y-set! p1 99)
(point-y p1)                     ==> 99
SRFI-17 setters

SLOTNAME may alternatively also be of the form

 (setter SLOTNAME)

In this case the slot can be read with (NAME-SLOTNAME STRUCT) as usual, and modified with (set! (NAME-SLOTNAME STRUCT) VALUE) (the slot-accessor has an associated SRFI-17 "setter" procedure) instead of the usual (NAME-SLOTNAME-set! STRUCT VALUE).

(define-record point (setter x) (setter y))
(define p1 (make-point 123 456))
(point? p1)                      ==> #t
(point-x p1)                     ==> 123
(set! (point-y p1) 99)
(point-y p1)                     ==> 99

define-record-type

(define-record-type NAME (CONSTRUCTOR TAG ...) PREDICATE (FIELD ACCESSOR [MODIFIER]) ...)syntax

SRFI-9 record types. For more information see the documentation for SRFI-9.

As an extension the MODIFIER may have the form (setter PROCEDURE), which will define a SRFI-17 setter-procedure for the given PROCEDURE that sets the field value. Usually PROCEDURE has the same name is ACCESSOR (but it doesn't have to).

This special form is also compatible with the definition from the R7RS (scheme base) library.

record-printer

record-printer NAMEprocedure

Returns the procedure used to print records of the type NAME if one has been set with set-record-printer!, #f otherwise.

set-record-printer!

set-record-printer! NAME PROCEDUREprocedure
set! (record-printer NAME) PROCEDUREprocedure

Defines a printing method for record of the type NAME by associating a procedure with the record type. When a record of this type is written using display, write or print, then the procedure is called with two arguments: the record to be printed and an output-port.

(define-record-type foo (make-foo x y z) foo?
  (x foo-x)
  (y foo-y)
  (z foo-z))
(define f (make-foo 1 2 3))
(set-record-printer! foo
  (lambda (x out)
    (fprintf out "#,(foo ~S ~S ~S)"
             (foo-x x) (foo-y x) (foo-z x))))
(define-reader-ctor 'foo make-foo)
(define s (with-output-to-string
              (lambda () (write f))))
s                                   ==> "#,(foo 1 2 3)"
(equal? f (with-input-from-string
              s read)))             ==> #t

Other forms

include

(include STRING)syntax

Include toplevel-expressions from the given source file in the currently compiled/interpreted program. If the included file has the extension .scm, then it may be omitted. The file is searched for in the current directory and all directories specified by the -include-path option.

include-relative

(include-relative STRING)syntax

Works like include, but the filename is searched for relative to the including file rather than the current directory.

Making extra libraries and extensions available

require-extension

(require-extension ID ...)syntax

This is equivalent to (require-library ID ...) but performs an implicit import, if necessary. Since version 4.4.0, ID may also be an import specification (using rename, only, except or prefix).

To make long matters short - just use require-extension and it will normally figure everything out for dynamically loadable extensions and core library units.

This implementation of require-extension is compliant with SRFI-55 (see the SRFI-55 document for more information).

require-library

(require-library ID ...)syntax

This form does all the necessary steps to make the libraries or extensions given in ID ... available. It loads syntactic extensions, if needed and generates code for loading/linking with core library modules or separately installed extensions.

During interpretation/evaluation require-library performs one of the following:

  • If ID names a built-in feature chicken srfi-0 srfi-2 srfi-6 srfi-8 srfi-9 srfi-10 srfi-17 srfi-23 srfi-30 srfi-39 srfi-55, then nothing is done.
  • If ID names one of the syntactic extensions chicken-syntax chicken-ffi-syntax, then this extension will be loaded.
  • If ID names one of the core library units shipped with CHICKEN, then a (load-library 'ID) will be performed.
  • If ID names an installed extension with the syntax or require-at-runtime attribute, then the extensions is loaded at compile-time, probably doing a run-time (require ...) for any run-time requirements.
  • Otherwise, (require-library ID) is equivalent to (require 'ID).

During compilation, one of the following happens instead:

  • If ID names a built-in feature chicken srfi-0 srfi-2 srfi-6 srfi-8 srfi-9 srfi-10 srfi-17 srfi-23 srfi-30 srfi-39 srfi-55, then nothing is done.
  • If ID names one of the syntactic extensions chicken-syntax chicken-ffi-syntax, then this extension will be loaded at compile-time, making the syntactic extensions available in compiled code.
  • If ID names one of the core library units shipped with CHICKEN, or if the option -uses ID has been passed to the compiler, then a (declare (uses ID)) is generated.
  • If ID names an installed extension with the syntax or require-at-runtime attribute, then the extension is loaded at compile-time, and code is emitted to (require ...) any needed run-time requirements.
  • Otherwise (require-library ID) is equivalent to (require 'ID).

ID should be a pure extension name and should not contain any path prefixes (for example dir/lib... is illegal).

ID may also be a list that designates an extension-specifier. Currently the following extension specifiers are defined:

  • (srfi NUMBER ...) is required for SRFI-55 compatibility and is fully implemented
  • (version ID NUMBER) is equivalent to ID, but checks at compile-time whether the extension named ID is installed and whether its version is equal or higher than NUMBER. NUMBER may be a string or a number, the comparison is done lexicographically (using string>=?).

Process shutdown

emergency-exit

emergency-exit #!optional CODEprocedure

Exits the current process without flushing any buffered output (using the C function _exit). Note that the exit-handler is not called when this procedure is invoked. The optional exit status code CODE defaults to 0.

exit

exit #!optional CODEprocedure

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

Note that pending dynamic-wind thunks are not invoked when exiting your program in this way.

exit-handler

exit-handlerparameter

A procedure of a single optional argument. When exit is called, then this procedure will be invoked with the exit-code as argument. The default behavior is to terminate the program.

Note that this handler is not invoked when emergency-exit is used.

implicit-exit-handler

implicit-exit-handlerparameter

A procedure of no arguments. When the last toplevel expression of the program has executed, then the value of this parameter is called. The default behaviour is to invoke all pending finalizers.

on-exit

on-exit THUNKprocedure

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

System interface

sleep

sleep SECONDSprocedure

Puts the program to sleep for SECONDS. If the scheduler is loaded (for example when srfi-18 is in use) then only the calling thread is put to sleep and other threads may continue executing. Otherwise, the whole process is put to sleep.

Ports

String ports

get-output-string
get-output-string PORTprocedure

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

open-input-string
open-input-string STRINGprocedure

Returns a port for reading from STRING.

open-output-string
open-output-stringprocedure

Returns a port for accumulating output in a string.

File Input/Output

flush-output

flush-output #!optional PORTprocedure

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

Port predicates

input-port-open?

input-port-open? PORTprocedure

Is the given PORT open for input?

output-port-open? PORTprocedure

Is the given PORT open for output?

port-closed?

port-closed? PORTprocedure

Is the given PORT closed (in all directions)?

port?

port? Xprocedure

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

Built-in parameters

Certain behavior of the interpreter and compiled programs can be customized via the following built-in parameters:

case-sensitive

case-sensitiveparameter

If true, then read reads symbols and identifiers in case-sensitive mode and uppercase characters in symbols are printed escaped. Defaults to #t.

keyword-style

keyword-styleparameter

Enables alternative keyword syntax, where STYLE may be either #:prefix (as in Common Lisp), which recognizes symbols beginning with a colon as keywords, or #:suffix (as in DSSSL), which recognizes symbols ending with a colon as keywords. Any other value disables the alternative syntaxes. In the interpreter the default is #:suffix.

parentheses-synonyms

parentheses-synonymsparameter

If true, then the list delimiter synonyms #\[ #\] and #\{ #\} are enabled. Defaults to #t.

symbol-escape

symbol-escapeparameter

If true, then the symbol escape #\| #\| is enabled. Defaults to #t.


Previous: Module srfi-4

Next: Module (chicken bitwise)

Contents »