~ chicken-core (master) /manual/Module (chicken base)
Trap1[[tags: manual]]2[[toc:]]34== Module (chicken base)56Core procedures and macros, acting as basic extensions to the R7RS7standard and other essential features.89This module is used by default, unless a program is compiled with10the {{-explicit-use}} option.1112=== Numeric predicates1314These allow you to make a more precise differentiation between number15types and their properties, not provided by R7RS.1617==== fixnum?1819<procedure>(fixnum? X)</procedure>2021Returns {{#t}} if {{X}} is a fixnum, or {{#f}} otherwise.2223==== flonum?2425<procedure>(flonum? X)</procedure>2627Returns {{#t}} if {{X}} is a flonum, or {{#f}} otherwise.2829==== bignum?3031<procedure>(bignum? X)</procedure>3233Returns {{#t}} if {{X}} is a bignum (integer larger than fits in a34fixnum), or {{#f}} otherwise.3536==== exact-integer?3738<procedure>(exact-integer? X)</procedure>3940Returns {{#t}} if {{X}} is an exact integer (i.e., a fixnum or a41bignum), or {{#f}} otherwise.4243This procedure is compatible with the definition from the R7RS44{{(scheme base)}} library.4546==== cplxnum?4748<procedure>(cplxnum? X)</procedure>4950Returns {{#t}} if {{X}} is a true complex number (it has an imaginary51component), or {{#f}} otherwise.5253Please note that {{complex?}} will always return {{#t}} for any number54type supported by CHICKEN, so you can use this predicate if you want55to know the representational type of a number.5657==== ratnum?5859<procedure>(ratnum? X)</procedure>6061Returns {{#t}} if {{X}} is a true rational number (it is a fraction62with a denominator that's not 1), or {{#f}} otherwise.6364Please note that {{rational?}} will always return {{#t}} for any65number type supported by CHICKEN except complex numbers and non-finite66flonums, so you can use this predicate if you want to know the67representational type of a number.6869==== nan?7071<procedure>(nan? N)</procedure>7273Returns {{#t}} if {{N}} is not a number (a IEEE flonum NaN-value). If74{{N}} is a complex number, it's considered nan if it has a real or75imaginary component that's nan.7677This procedure is compatible with the definition from the R7RS78{{(scheme inexact)}} library.7980==== infinite?8182<procedure>(infinite? N)</procedure>8384Returns {{#t}} if {{N}} is negative or positive infinity, and {{#f}}85otherwise. If {{N}} is a complex number, it's considered infinite if86it has a real or imaginary component that's infinite.8788This procedure is compatible with the definition from the R7RS89{{(scheme inexact)}} library.9091==== finite?9293<procedure>(finite? N)</procedure>9495Returns {{#t}} if {{N}} represents a finite number and {{#f}}96otherwise. Positive and negative infinity as well as NaNs are not97considered finite. If {{N}} is a complex number, it's considered98finite if both the real and imaginary components are finite.99100This procedure is compatible with the definition from the R7RS101{{(scheme inexact)}} library.102103==== equal=?104105<procedure>(equal=? X y)</procedure>106107Similar to the standard procedure {{equal?}}, but compares numbers108using the {{=}} operator, so {{equal=?}} allows structural comparison109in combination with comparison of numerical data by value.110111112=== Arithmetic113114==== add1/sub1115116<procedure>(add1 N)</procedure>117<procedure>(sub1 N)</procedure>118119Adds/subtracts 1 from {{N}}.120121122==== exact-integer-nth-root123124<procedure>(exact-integer-nth-root K N)</procedure>125126Like {{exact-integer-sqrt}}, but with any base value. Calculates127{{\sqrt[N]{K}}}, the {{N}}th root of {{K}} and returns two values128{{s}} and {{r}} where {{s^N + r = K}} and {{K < (s+1)^N}}.129130131==== Division with quotient and remainder132133<procedure>(quotient&remainder X Y)</procedure>134<procedure>(quotient&modulo X Y)</procedure>135136Returns two values: the quotient and the remainder (or modulo) of137{{X}} divided by {{Y}}. Could be defined as {{(values (quotient X Y)138(remainder X Y))}}, but is much more efficient when dividing very139large numbers.140141==== signum142143<procedure>(signum N)</procedure>144145For real numbers, returns {{1}} if {{N}} is positive, {{-1}} if {{N}}146is negative or {{0}} if {{N}} is zero. {{signum}} is exactness147preserving.148149For complex numbers, returns a complex number of the same angle but150with magnitude 1.151152153=== Weak pairs154155''Weak pairs'' behave identically to regular pairs, with one156exception: the car value may be garbage collected. When that happens,157it gets replaced with a sentinel "broken-weak-pointer" value.158159They are indistinguishable from regular pairs: {{car}}, {{cdr}}, etc160all work on them, {{pair?}} returns true, etc. The {{WRITE}}161representation is identical to regular pairs, so they will be read162back as pairs. In other words, they have no read/write invariance.163164They're the same as regular pairs for all intents and purposes.165However, there's a {{weak-pair?}} predicate which ''can'' distinguish166between regular pairs and weak pairs.167168NOTE: Due to internal limitations, {{set-car!}} on a weak pair169currently may cause it to hold onto the value for one more GC cycle in170some situations.171172==== weak-cons173174<procedure>(weak-cons obj[1] obj[2])</procedure><br>175176Returns a newly allocated weak pair whose car is obj[1] and whose cdr177is obj[2]. The pair is indistinguishable from normal pairs, except as178noted above.179180 (weak-cons 'a '()) ===> (a)181 (weak-cons '(a) '(b c d)) ===> ((a) b c d)182 (weak-cons "a" '(b c)) ===> ("a" b c)183 (weak-cons 'a 3) ===> (a . 3)184 (weak-cons '(a b) 'c) ===> ((a b) . c)185186 (import (chicken gc))187188 (let* ((x '(a b))189 (y (weak-cons x 'c)))190 (gc #t)191 (car x)) ===> (a b)192193 (let ((x (weak-cons '(a b) 'c)))194 (gc #t)195 (car x)) ===> #!bwp196197As the final two examples show, when something ''else'' still holds on198to the value that's stored in the car of a weak pair, it will not be199reclaimed. But if the value is ''only'' referenced by one or more200weak pairs, it is reclaimed and the car of the weak pair is replaced201with the ''broken-weak-pointer'' value {{#!bwp}}.202203<procedure>(weak-pair? obj)</procedure><br>204205This predicate returns {{#t}} if and only if {{obj}} is a weak pair.206207 (weak-pair? (weak-cons 'a '())) ===> #t208 (weak-pair? (cons 'a '())) ===> #f209 (weak-pair? (vector 'a '())) ===> #f210211<procedure>(bwp-object? obj)</procedure>212213This predicate returns {{#t}} if {{obj}} is the broken-weak-pointer214value, otherwise {{#f}}.215216217=== Input/Output218219==== current-error-port220221<procedure>(current-error-port [PORT])</procedure>222223Returns default error output port. If {{PORT}} is given, then that224port is selected as the new current error output port.225226Note that the default error output port is not buffered. Use227[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]228if you need a different behaviour.229230==== print231232<procedure>(print [EXP1 ...])</procedure>233234Outputs the optional arguments {{EXP1 ...}} using {{display}} and235writes a newline character to the port that is the value of236{{(current-output-port)}}. Returns {{(void)}}.237238==== print*239240<procedure>(print* [EXP1 ...])</procedure>241242Similar to {{print}}, but does not output a terminating newline243character and performs a {{flush-output}} after writing its arguments.244245246=== Interrupts and error-handling247248==== enable-warnings249250<procedure>(enable-warnings [BOOL])</procedure>251252Enables or disables warnings, depending on wether {{BOOL}} is true or253false. If called with no arguments, this procedure returns {{#t}} if254warnings are currently enabled, or {{#f}} otherwise. Note that this is255not a parameter. The current state (whether warnings are enabled or256disabled) is global and not thread-local.257258259==== error260261<procedure>(error [LOCATION] [STRING] EXP ...)</procedure>262263Prints error message, writes all extra arguments to the value of264{{(current-error-port)}} and invokes the current265exception-handler. This conforms to266[[http://srfi.schemers.org/srfi-23/srfi-23.html|SRFI-23]]. If267{{LOCATION}} is given and a symbol, it specifies the ''location'' (the268name of the procedure) where the error occurred.269270271==== assert272273<macro>(assert EXP [OBJ ...])</macro>274275Evaluates {{EXP}}, if it returns #f, {{error}} is applied to {{OBJ ...}},276else the result of {{EXP}} is returned.277When compiling in unsafe mode, assertions of this kind are disabled.278279280==== get-call-chain281282<procedure>(get-call-chain [START [THREAD]])</procedure>283284Returns a list with the call history. Backtrace information is only285generated in code compiled without {{-no-trace}} and evaluated code.286If the optional argument {{START}} is given, the backtrace starts at287this offset, i.e. when {{START}} is 1, the next to last trace-entry is288printed, and so on. If the optional argument {{THREAD}} is given, then289the call-chain will only be constructed for calls performed by this290thread.291292293294==== print-call-chain295296<procedure>(print-call-chain [PORT [START [THREAD [HEADER]]]])</procedure>297298Prints a backtrace of the procedure call history to {{PORT}}, which299defaults to {{(current-output-port)}}. The output is prefixed by the300{{HEADER}}, which defaults to {{"\n\tCall history:\n"}}.301302303==== procedure-information304305<procedure>(procedure-information PROC)</procedure>306307Returns an s-expression with debug information for the procedure308{{PROC}}, or {{#f}}, if {{PROC}} has no associated debug information.309310311==== warning312313<procedure>(warning MESSAGE [EXP ...])</procedure>314315Displays a warning message (if warnings are enabled with {{enable-warnings}}),316from the {{MESSAGE}}, and optional {{EXP}} arguments, then continues execution.317{{MESSAGE}}, and {{EXP}}, may be {{any}} object.318319320=== Lists321322==== alist-ref323324<procedure>(alist-ref KEY ALIST [TEST [DEFAULT]])</procedure>325326Looks up {{KEY}} in {{ALIST}} using {{TEST}} as the comparison function (or {{eqv?}} if327no test was given) and returns the cdr of the found pair, or {{DEFAULT}} (which defaults to {{#f}}).328329330==== alist-update331332<procedure>(alist-update KEY VALUE ALIST [TEST])</procedure>333<procedure>(alist-update! KEY VALUE ALIST [TEST])</procedure>334335If the list {{ALIST}} contains a pair of the form {{(KEY . X)}}, then this procedure336replaces {{X}} with {{VALUE}} and returns {{ALIST}}. If {{ALIST}} contains no such item, then337{{alist-update}} returns {{((KEY . VALUE) . ALIST)}}. The optional argument338{{TEST}} specifies the comparison procedure to search a matching pair in {{ALIST}}339and defaults to {{eqv?}}. {{alist-update!}} is the destructive version of {{alist-update}}.340341342==== atom?343344<procedure>(atom? X)</procedure>345346Returns {{#t}} if {{X}} is not a pair.347348349==== butlast350351<procedure>(butlast LIST)</procedure>352353Returns a fresh list with all elements but the last of {{LIST}}.354355356==== chop357358<procedure>(chop LIST N)</procedure>359360Returns a new list of sublists, where each sublist contains {{N}}361elements of {{LIST}}. If {{LIST}} has a length that is not362a multiple of {{N}}, then the last sublist contains the remaining363elements.364365<enscript highlight=scheme>366(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))367(chop '(a b c d) 3) ==> ((a b c) (d))368</enscript>369370371==== compress372373<procedure>(compress BLIST LIST)</procedure>374375Returns a new list with elements taken from {{LIST}} with376corresponding true values in the list {{BLIST}}.377378<enscript highlight=scheme>379(define nums '(99 100 110 401 1234))380(compress (map odd? nums) nums) ==> (99 401)381</enscript>382383384==== flatten385386<procedure>(flatten LIST1 ...)</procedure>387388Returns {{LIST1 ...}} concatenated together, with nested lists389removed (flattened).390391392==== foldl393394<procedure>(foldl PROCEDURE INIT LIST)</procedure>395396Applies {{PROCEDURE}} to the elements from {{LIST}}, beginning from397the left:398399<enscript hightlight=scheme>400(foldl + 0 '(1 2 3)) ==> (+ (+ (+ 0 1) 2) 3)401</enscript>402403Note that the order of arguments taken by {{PROCEDURE}} is different404from the {{SRFI-1}} {{fold}} procedure, but matches the more natural405order used in Haskell and Objective Caml.406407408==== foldr409410<procedure>(foldr PROCEDURE INIT LIST)</procedure>411412Applies {{PROCEDURE}} to the elements from {{LIST}}, beginning from413the right:414415<enscript hightlight=scheme>416(foldr + 0 '(1 2 3)) ==> (+ 1 (+ 2 (+ 3 0)))417</enscript>418419420==== intersperse421422<procedure>(intersperse LIST X)</procedure>423424Returns a new list with {{X}} placed between each element.425426427==== join428429<procedure>(join LISTOFLISTS [LIST])</procedure>430431Concatenates the lists in {{LISTOFLISTS}} with {{LIST}} placed432between each sublist. {{LIST}} defaults to the empty list.433434<enscript highlight=scheme>435(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)436(join '((p q) () (r (s) t)) '(-)) ==> (p q - - r (s) t)437</enscript>438439{{join}} could be implemented as follows:440441<enscript highlight=scheme>442(define (join lstoflsts #!optional (lst '()))443 (apply append (intersperse lstoflists lst)) )444</enscript>445446447==== rassoc448449<procedure>(rassoc KEY LIST [TEST])</procedure>450451Similar to {{assoc}}, but compares {{KEY}} with the {{cdr}} of each pair in {{LIST}} using452{{TEST}} as the comparison procedures (which defaults to {{eqv?}}).453454455==== tail?456457<procedure>(tail? X LIST)</procedure>458459Returns true if {{X}} is one of the tails (cdr's) of {{LIST}}.460461462=== Vectors463464==== vector-resize465466<procedure>(vector-resize VECTOR N [INIT])</procedure>467468Creates and returns a new vector with the contents of {{VECTOR}} and469length {{N}}. If {{N}} is greater than the original length of470{{VECTOR}}, then all additional items are initialized to {{INIT}}. If471{{INIT}} is not specified, the contents are initialized to some472unspecified value.473474475==== subvector476477<procedure>(subvector VECTOR FROM [TO])</procedure>478479Returns a new vector with elements taken from {{VECTOR}} in the480given range. {{TO}} defaults to {{(vector-length VECTOR)}}.481482{{subvector}} was introduced in CHICKEN 4.7.3.483484485=== Combinators486487488==== constantly489490<procedure>(constantly X ...)</procedure>491492Returns a procedure that always returns the values {{X ...}} regardless of the number and value of its arguments.493494<enscript highlight=scheme>495(constantly X) <=> (lambda args X)496</enscript>497498499==== complement500501<procedure>(complement PROC)</procedure>502503Returns a procedure that returns the boolean inverse of {{PROC}}.504505<enscript highlight=scheme>506(complement PROC) <=> (lambda (x) (not (PROC x)))507</enscript>508509510==== compose511512<procedure>(compose PROC1 PROC2 ...)</procedure>513514Returns a procedure that represents the composition of the515argument-procedures {{PROC1 PROC2 ...}}.516517<enscript highlight=scheme>518(compose F G) <=> (lambda args519 (call-with-values520 (lambda () (apply G args))521 F))522</enscript>523524{{(compose)}} is equivalent to {{values}}.525526527==== conjoin528529<procedure>(conjoin PRED ...)</procedure>530531Returns a procedure that returns {{#t}} if its argument satisfies the532predicates {{PRED ...}}.533<enscript highlight=scheme>534((conjoin odd? positive?) 33) ==> #t535((conjoin odd? positive?) -33) ==> #f536</enscript>537538539==== disjoin540541<procedure>(disjoin PRED ...)</procedure>542543Returns a procedure that returns {{#t}} if its argument satisfies any544predicate {{PRED ...}}.545<enscript highlight=scheme>546((disjoin odd? positive?) 32) ==> #t547((disjoin odd? positive?) -32) ==> #f548</enscript>549550551==== each552553<procedure>(each PROC ...)</procedure>554555Returns a procedure that applies {{PROC ...}} to its arguments, and returns the result(s)556of the last procedure application. For example557558<enscript highlight=scheme>559(each pp eval)560</enscript>561562is equivalent to563564<enscript highlight=scheme>565(lambda args566 (apply pp args)567 (apply eval args) )568</enscript>569570{{(each PROC)}} is equivalent to {{PROC}} and {{(each)}} is equivalent to571{{void}}.572573574==== flip575576<procedure>(flip PROC)</procedure>577578Returns a two-argument procedure that calls {{PROC}} with its579arguments swapped:580<enscript highlight=scheme>581(flip PROC) <=> (lambda (x y) (PROC y x))582</enscript>583584585==== identity586587<procedure>(identity X)</procedure>588589Returns its sole argument {{X}}.590591592==== list-of?593594<procedure>(list-of? PRED)</procedure>595596Returns a procedure of one argument that returns {{#t}} when597applied to a list of elements that all satisfy the predicate procedure598{{PRED}}, or {{#f}} otherwise.599600<enscript highlight=scheme>601((list-of? even?) '(1 2 3)) ==> #f602((list-of? number?) '(1 2 3)) ==> #t603</enscript>604605606==== o607608<procedure>(o PROC ...)</procedure>609610A single value version of {{compose}} (slightly faster). {{(o)}} is equivalent611to {{identity}}.612613614=== User-defined named characters615616==== char-name617618<procedure>(char-name SYMBOL-OR-CHAR [CHAR-OR-FALSE])</procedure>619620This procedure can be used to inquire about character names or to621define new ones. With a single argument the behavior is as follows:622If {{SYMBOL-OR-CHAR}} is a symbol, then {{char-name}} returns623the character with this name, or {{#f}} if no character is defined624under this name. If {{SYMBOL-OR-CHAR}} is a character, then the625name of the character is returned as a symbol, or {{#f}} if the626character has no associated name.627628If the optional argument {{CHAR-OR-FALSE}} is provided and a character, then629{{SYMBOL-OR-CHAR}} should be a symbol that will be the new name of630the given character. If multiple names designate the same character,631then {{write}} will use the character name that was defined last.632If {{CHAR-OR-FALSE}} is {{#f}} instead, then {{SYMBOL-OR-CHAR}}633may designate a symbol naming a character or a character and any634defined character name for it will be removed.635636<enscript highlight=scheme>637(char-name 'space) ==> #\space638(char-name #\space) ==> space639(char-name 'bell) ==> #f640(char-name (integer->char 7)) ==> #f641(char-name 'bell (integer->char 7))642(char-name 'bell) ==> #\bell643(char->integer (char-name 'bell)) ==> 7644(char-name 'bell #f)645(char-name 'bell) ==> #f646</enscript>647648649=== The unspecified value650651==== void652653<procedure>(void ARGUMENT ...)</procedure>654655Ignores {{ARGUMENT ...}} and returns an unspecified value.656657658=== Continuations659660==== call/cc661662<procedure>(call/cc PROCEDURE)</procedure>663664An alias for {{call-with-current-continuation}}.665666This procedure is compatible with the definition from the R7RS667{{(scheme base)}} library.668669=== Symbols670671==== Symbol utilities672673===== symbol-append674675<procedure>(symbol-append SYMBOL1 ...)</procedure>676677Creates a new symbol from the concatenated names of the argument symbols678{{(SYMBOL1 ...)}}.679680==== Uninterned symbols ("gensyms")681682Symbols may be "interned" or "uninterned". Interned symbols are683registered in a global table, and when read back from a port are684identical to a symbol written before:685686<enscript highlight=scheme>687(define sym 'foo)688689(eq? sym (with-input-from-string690 (with-output-to-string691 (lambda () (write sym)))692 read))693694 => #t695</enscript>696697Uninterned symbols on the other hand are not globally registered and so698multiple symbols with the same name may coexist:699700<enscript highlight=scheme>701(define sym (gensym 'foo)) ; sym is a uninterned symbol like "foo42"702703(eq? sym (with-input-from-string ; the symbol read will be an interned symbol704 (with-output-to-string705 (lambda () (write sym)))706 read))707708 => #f709710(eq? (string->uninterned-symbol "foo") (string->uninterned-symbol "foo"))711712 => #f713</enscript>714715Use uninterned symbols if you need to generate unique values that716can be compared quickly, for example as keys into a hash-table717or association list. Note that uninterned symbols lose their718uniqueness property when written to a file and read back in, as719in the example above.720721===== gensym722723<procedure>(gensym [STRING-OR-SYMBOL])</procedure>724725Returns a newly created uninterned symbol. If an argument is provided,726the new symbol is prefixed with that argument.727728729===== string->uninterned-symbol730731<procedure>(string->uninterned-symbol STRING)</procedure>732733Returns a newly created, unique symbol with the name {{STRING}}.734735736=== Setters737738SRFI-17 is fully implemented. For more information see:739[[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].740741==== setter742743<procedure>(setter PROCEDURE)</procedure>744745Returns the setter-procedure of {{PROCEDURE}}, or signals an error if746{{PROCEDURE}} has no associated setter-procedure.747748Note that {{(set! (setter PROC) ...)}} for a procedure that has no749associated setter procedure yet is a very slow operation (the old750procedure is replaced by a modified copy, which involves a garbage751collection).752753754==== getter-with-setter755756<procedure>(getter-with-setter GETTER SETTER)</procedure>757758Returns a copy of the procedure {{GETTER}} with the associated setter759procedure {{SETTER}}. Contrary to the SRFI specification, the setter760of the returned procedure may be changed.761762763=== Binding forms for optional arguments764765==== optional766767<macro>(optional ARGS DEFAULT)</macro>768769Use this form for procedures that take a single optional argument. If770{{ARGS}} is the empty list {{DEFAULT}} is evaluated and771returned, otherwise the first element of the list {{ARGS}}. It is772an error if {{ARGS}} contains more than one value.773774<enscript highlight=scheme>775(define (incr x . i) (+ x (optional i 1)))776(incr 10) ==> 11777(incr 12 5) ==> 17778</enscript>779780781==== let-optionals782783<macro> (let-optionals ARGS ((VAR1 DEFAULT1) ...) BODY ...)</macro>784785Binding constructs for optional procedure arguments. {{ARGS}} is786normally a rest-parameter taken from a lambda-list. {{let-optionals}}787binds {{VAR1 ...}} to available arguments in parallel, or to788{{DEFAULT1 ...}} if not enough arguments were provided.789{{let-optionals*}} binds {{VAR1 ...}} sequentially, so every variable790sees the previous ones. it is an error if any excess arguments are791provided.792793<enscript highlight=scheme>794(let-optionals '(one two) ((a 1) (b 2) (c 3))795 (list a b c) ) ==> (one two 3)796</enscript>797798==== let-optionals*799800<macro> (let-optionals* ARGS ((VAR1 DEFAULT1) ... [RESTVAR]) BODY ...)</macro>801802Binding constructs for optional procedure arguments. {{ARGS}} is803normally a rest-parameter taken from a lambda-list. {{let-optionals}}804binds {{VAR1 ...}} to available arguments in parallel, or to805{{DEFAULT1 ...}} if not enough arguments were provided.806{{let-optionals*}} binds {{VAR1 ...}} sequentially, so every variable807sees the previous ones. If a single variable {{RESTVAR}} is given,808then it is bound to any remaining arguments, otherwise it is an error809if any excess arguments are provided.810811<enscript highlight=scheme>812(let-optionals* '(one two) ((a 1) (b 2) (c a))813 (list a b c) ) ==> (one two one)814</enscript>815816=== Other binding forms817818==== and-let*819820<macro>(and-let* (BINDING ...) EXP1 EXP2 ...)</macro>821822Bind sequentially and execute body. {{BINDING}} can823be a list of a variable and an expression, a list with a single824expression, or a single variable. If the value of an expression825bound to a variable is {{#f}}, the {{and-let*}} form826evaluates to {{#f}} (and the subsequent bindings and the body827are not executed). Otherwise the next binding is performed. If828all bindings/expressions evaluate to a true result, the body is829executed normally and the result of the last expression is the830result of the {{and-let*}} form. See also the documentation for831[[http://srfi.schemers.org/srfi-2/srfi-2.html|SRFI-2]].832833==== letrec*834835<macro>(letrec* ((VARIABLE EXPRESSION) ...) BODY ...)</macro>836837Implements R6RS/R7RS {{letrec*}}. {{letrec*}} is similar to {{letrec}}838but binds the variables sequentially and is to {{letrec}} what839{{let*}} is to {{let}}.840841This special form is compatible with the definition from the R7RS842{{(scheme base)}} library.843844==== rec845846<macro>(rec NAME EXPRESSION)</macro><br>847<macro>(rec (NAME VARIABLE ...) BODY ...)</macro>848849Allows simple definition of recursive definitions. {{(rec NAME EXPRESSION)}} is850equivalent to {{(letrec ((NAME EXPRESSION)) NAME)}} and {{(rec (NAME VARIABLE ...) BODY ...)}}851is the same as {{(letrec ((NAME (lambda (VARIABLE ...) BODY ...))) NAME)}}.852853==== cut854855<macro>(cut SLOT ...)</macro><br>856<macro>(cute SLOT ...)</macro>857858[[http://srfi.schemers.org/srfi-26/srfi-26.html|Syntactic sugar for specializing parameters]].859860==== define-values861862<macro>(define-values (NAME ...) VALUEEXP)</macro>863<macro>(define-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)</macro>864<macro>(define-values NAME VALUEEXP)</macro>865866Defines several variables at once, with the result values of expression867{{VALUEEXP}}, similar to {{set!-values}}.868869This special form is compatible with the definition from the R7RS870{{(scheme base)}} library.871872==== fluid-let873874<macro>(fluid-let ((VAR1 X1) ...) BODY ...)</macro>875876Binds the variables {{VAR1 ...}} dynamically to the values {{X1 ...}}877during execution of {{BODY ...}}. This implements878[[http://srfi.schemers.org/srfi-15/srfi-15.html|SRFI-15]].879880==== let-values881882<macro>(let-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>883884Binds multiple variables to the result values of {{VALUEEXP ...}}.885All variables are bound simultaneously. Like {{define-values}}, the886{{(NAME ...)}} expression can be any basic lambda list (dotted tail887notation is supported).888889This special form implements890[[http://srfi.schemers.org/srfi-11/srfi-11.html|SRFI-11]], and it is891also compatible with the definition from the R7RS {{(scheme base)}}892library.893894895==== let*-values896897<macro>(let*-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>898899Binds multiple variables to the result values of {{VALUEEXP ...}}.900The variables are bound sequentially. Like {{let-values}}, the901{{(NAME ...)}} expression can be any basic lambda list (dotted tail902notation is supported).903904This is also part of905[[http://srfi.schemers.org/srfi-11/srfi-11.html|SRFI-11]] and is also906compatible with the definition from the R7RS {{(scheme base)}}907library.908909<enscript highlight=scheme>910(let*-values (((a b) (values 2 3))911 ((p) (+ a b)) )912 p) ==> 5913</enscript>914915==== letrec-values916917<macro>(letrec-values (((NAME ...) VALUEEXP) ...) BODY ...)</macro>918919Binds the result values of {{VALUEEXP ...}} to multiple variables at920once. All variables are mutually recursive. Like {{let-values}}, the921{{(NAME ...)}} expression can be any basic lambda list (dotted tail922notation is supported).923924<enscript highlight=scheme>925(letrec-values (((odd even)926 (values927 (lambda (n) (if (zero? n) #f (even (sub1 n))))928 (lambda (n) (if (zero? n) #t (odd (sub1 n)))) ) ) )929 (odd 17) ) ==> #t930</enscript>931932933==== receive934935<macro>(receive (NAME ...) VALUEEXP BODY ...)</macro><br>936<macro>(receive (NAME1 ... NAMEn . NAMEn+1) VALUEEXP BODY ...)</macro><br>937<macro>(receive NAME VALUEEXP BODY ...)</macro><br>938<macro>(receive VALUEEXP)</macro>939940[[http://srfi.schemers.org/srfi-8/srfi-8.html|SRFI-8]].941Syntactic sugar for {{call-with-values}}. Binds variables942to the result values of {{VALUEEXP}} and evaluates {{BODY ...}},943similar {{define-values}} but lexically scoped.944945{{(receive VALUEEXP)}} is equivalent to {{(receive _ VALUEEXP _)}}.946This shortened form is not described by SRFI-8.947948==== set!-values949950<macro>(set!-values (NAME ...) VALUEEXP)</macro>951<macro>(set!-values (NAME1 ... NAMEn . NAMEn+1) VALUEEXP)</macro>952<macro>(set!-values NAME VALUEEXP)</macro>953954Assigns the result values of expression {{VALUEEXP}} to multiple955variables, similar to {{define-values}}.956957==== nth-value958959<macro>(nth-value N EXP)</macro>960961Returns the {{N}}th value (counting from zero) of the values returned962by expression {{EXP}}.963964965=== Substitution forms and macros966967==== define-constant968969<macro>(define-constant NAME CONST)</macro>970971Defines a variable with a constant value, evaluated at compile-time.972Any reference to such a constant should appear textually '''after'''973its definition. This construct is equivalent to {{define}} when974evaluated or interpreted. Constant definitions should only appear at975toplevel. Note that constants are local to the current compilation976unit and are not available outside of the source file in which they977are defined. Names of constants still exist in the Scheme namespace978and can be lexically shadowed. If the value is mutable, then the979compiler is careful to preserve its identity. {{CONST}} may be any980constant expression, and may also refer to constants defined via981{{define-constant}} previously, but it must be possible to982evaluate the expression at compile-time.983984==== define-inline985986<macro>(define-inline (NAME VAR ...) BODY ...)</macro><br>987<macro>(define-inline (NAME VAR ... . VAR) BODY ...)</macro><br>988<macro>(define-inline NAME EXP)</macro>989990Defines an inline procedure. Any occurrence of {{NAME}} will be replaced991by {{EXP}} or {{(lambda (VAR ... [. VAR]) BODY ...)}}. This is similar992to a macro, but variable names and scope are handled correctly.993994Inline substitutions take place '''after''' macro-expansion, and any995reference to {{NAME}} should appear textually '''after''' its996definition. Inline procedures are local to the current compilation unit997and are not available outside of the source file in which they are998defined. Names of inline procedures still exist in the Scheme namespace999and can be lexically shadowed. Inline definitions should only appear at1000the toplevel.10011002Note that the {{inline-limit}} compiler option does not affect inline1003procedure expansion, and self-referential inline procedures may cause1004the compiler to enter an infinite loop.10051006In the third form, {{EXP}} must be a lambda expression.10071008This construct is equivalent to {{define}} when evaluated or1009interpreted.101010111012=== Conditional forms10131014==== unless10151016<macro>(unless TEST EXP1 EXP2 ...)</macro>10171018Equivalent to:10191020<enscript highlight=scheme>1021(if (not TEST) (begin EXP1 EXP2 ...))1022</enscript>10231024==== when10251026<macro>(when TEST EXP1 EXP2 ...)</macro>10271028Equivalent to:10291030<enscript highlight=scheme>1031(if TEST (begin EXP1 EXP2 ...))1032</enscript>10331034=== Record structures10351036==== define-record10371038<macro>(define-record NAME SLOTNAME ...)</macro>10391040Defines a record type. This defines a number of procedures for1041creating, accessing, and modifying record members.10421043Call {{make-NAME}} to create an instance1044of the structure (with one initialization-argument for each slot, in1045the listed order).10461047{{(NAME? STRUCT)}} tests any object for being an instance of this1048structure.10491050Slots are accessed via {{(NAME-SLOTNAME STRUCT)}}1051and updated using {{(NAME-SLOTNAME-set!}} {{STRUCT}} {{VALUE)}}.10521053<enscript highlight=scheme>1054(define-record point x y)1055(define p1 (make-point 123 456))1056(point? p1) ==> #t1057(point-x p1) ==> 1231058(point-y-set! p1 99)1059(point-y p1) ==> 991060</enscript>10611062===== SRFI-17 setters10631064{{SLOTNAME}} may alternatively also be of the form10651066 (setter SLOTNAME)10671068In this case the slot can be read with {{(NAME-SLOTNAME STRUCT)}} as usual,1069and modified with {{(set! (NAME-SLOTNAME STRUCT) VALUE)}} (the slot-accessor1070has an associated SRFI-17 "setter" procedure) instead of1071the usual {{(NAME-SLOTNAME-set!}} {{STRUCT}} {{VALUE)}}.107210731074<enscript highlight=scheme>1075(define-record point (setter x) (setter y))1076(define p1 (make-point 123 456))1077(point? p1) ==> #t1078(point-x p1) ==> 1231079(set! (point-y p1) 99)1080(point-y p1) ==> 991081</enscript>10821083==== define-record-type10841085<macro>(define-record-type NAME (CONSTRUCTOR TAG ...) PREDICATE (FIELD ACCESSOR [MODIFIER]) ...)</macro>10861087SRFI-9 record types. For more information see the documentation for1088[[http://srfi.schemers.org/srfi-9/srfi-9.html|SRFI-9]].10891090As an extension the {{MODIFIER}} may have the form1091{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure1092for the given {{PROCEDURE}} that sets the field value.1093Usually {{PROCEDURE}} has the same name is {{ACCESSOR}} (but it1094doesn't have to).10951096This special form is also compatible with the definition from the R7RS1097{{(scheme base)}} library.10981099==== record-printer11001101<procedure>(record-printer NAME)</procedure><br>11021103Returns the procedure used to print records of the type {{NAME}} if1104one has been set with {{set-record-printer!}}, {{#f}} otherwise.11051106==== set-record-printer!11071108<procedure>(set-record-printer! NAME PROCEDURE)</procedure><br>1109<procedure>(set! (record-printer NAME) PROCEDURE)</procedure>11101111Defines a printing method for record of the type {{NAME}} by1112associating a procedure with the record type. When a record of this1113type is written using {{display, write}} or {{print}}, then1114the procedure is called with two arguments: the record to be printed1115and an output-port.11161117<enscript highlight=scheme>1118(define-record-type foo (make-foo x y z) foo?1119 (x foo-x)1120 (y foo-y)1121 (z foo-z))1122(define f (make-foo 1 2 3))1123(set-record-printer! foo1124 (lambda (x out)1125 (fprintf out "#,(foo ~S ~S ~S)"1126 (foo-x x) (foo-y x) (foo-z x))))1127(define-reader-ctor 'foo make-foo)1128(define s (with-output-to-string1129 (lambda () (write f))))1130s ==> "#,(foo 1 2 3)"1131(equal? f (with-input-from-string1132 s read))) ==> #t1133</enscript>11341135=== Other forms11361137==== load11381139<procedure>(load filename [evalproc])</procedure><br>11401141Filename should be a string naming an existing file containing Scheme1142source code. The load procedure reads expressions and definitions from1143the file and evaluates them sequentially. It is unspecified whether the1144results of the expressions are printed. The load procedure does not1145affect the values returned by current-input-port and1146current-output-port. Load returns an unspecified value.11471148CHICKEN offers a few extensions to the R7RS definition of {{load}}:11491150* The {{filename}} may also be an input port.1151* The expressions which are read one by one from the source file are passed to the procedure indicated by the extra optional {{evalproc}} argument, which defaults to {{eval}}.1152* On platforms that support it (currently BSD, Haiku, MacOS X, Linux, Solaris, and Windows), {{load}} can be used to load shared objects.11531154Example for loading compiled programs:11551156 % cat x.scm1157 (define (hello) (print "Hello!"))1158 % csc -s x.scm1159 % csi -q1160 #;1> (load "x.so")1161 ; loading x.so ...1162 #;2> (hello)1163 Hello!1164 #;3>11651166There are some limitations and caveats to the CHICKEN extensions you1167need to be aware of:11681169* The second argument to {{load}} is ignored when loading compiled code.1170* If source code is loaded from a port, then that port is closed after all expressions have been read.1171* A compiled file can only be loaded once. Subsequent attempts to load the same file have no effect.11721173==== include11741175<macro>(include STRING1 STRING2 ...)</macro>1176<macro>(include-ci STRING1 STRING2 ...)</macro>11771178Include toplevel-expressions from the given source files in the currently1179compiled/interpreted program. If the included file has the extension1180{{.scm}}, then it may be omitted. The file is searched for in the1181current directory and all directories specified by the {{-include-path}}1182option.11831184{{include-ci}} works as {{include}} but reads files in case-insensitive1185mode.11861187==== include-relative11881189<macro>(include-relative STRING)</macro>11901191Works like {{include}}, but the filename is searched for relative to the1192including file rather than the current directory.119311941195=== Making extra libraries and extensions available11961197==== require-extension11981199<macro>(require-extension ID ...)</macro>12001201This is equivalent to {{(require-library ID ...)}} but performs an implicit1202{{import}}, if necessary. Since version 4.4.0, {{ID}} may also be an import specification1203(using {{rename}}, {{only}}, {{except}} or {{prefix}}).12041205To make long matters short - just use {{require-extension}} and it will normally figure everything out for dynamically1206loadable extensions and core library units.12071208This implementation of {{require-extension}} is compliant with [[http://srfi.schemers.org/srfi-55/srfi-55.html|SRFI-55]]1209(see the [[http://srfi.schemers.org/srfi-55/srfi-55.html|SRFI-55]] document for more information).121012111212==== require-library12131214<macro>(require-library ID ...)</macro>12151216This form does all the necessary steps to make the libraries or extensions given1217in {{ID ...}} available. It loads syntactic extensions, if needed and generates1218code for loading/linking with core library modules or separately installed1219extensions.12201221During interpretation/evaluation {{require-library}} performs one of the1222following:12231224* If {{ID}} names a built-in feature, then nothing is done.1225* If {{ID}} names one of the syntactic extensions {{chicken-syntax chicken-ffi-syntax}}, then this extension will be loaded.1226* If {{ID}} names one of the core library units shipped with CHICKEN, then a {{(load-library 'ID)}} will be performed.1227* 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.1228* Otherwise, {{(require-library ID)}} is equivalent to {{(require 'ID)}}.12291230During compilation, one of the following happens instead:12311232* If {{ID}} names a built-in feature, then nothing is done.1233* 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.1234* 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.1235* 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.1236* Otherwise {{(require-library ID)}} is equivalent to {{(require 'ID)}}.12371238{{ID}} should be a pure extension name and should not contain any path prefixes (for example {{dir/lib...}} is illegal).12391240{{ID}} may also be a list that designates an extension-specifier. Currently the following extension specifiers are1241defined:12421243* {{(srfi NUMBER ...)}} is required for SRFI-55 compatibility and is fully implemented1244* {{(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>=?}}).12451246=== Process shutdown12471248==== emergency-exit12491250<procedure>(emergency-exit [CODE])</procedure>12511252Exits the current process without flushing any buffered output (using1253the C function {{_exit}}). Note that the {{exit-handler}} is not called1254when this procedure is invoked. The optional exit status code {{CODE}}1255defaults to {{0}}.125612571258==== exit12591260<procedure>(exit [CODE])</procedure>12611262Exit the running process and return exit-code, which defaults to 01263(Invokes {{exit-handler}}).12641265Note that pending {{dynamic-wind}} thunks are ''not'' invoked when exiting your program in this way.126612671268=== exit-handler12691270<parameter>(exit-handler)</parameter>12711272A procedure of a single optional argument. When {{exit}} is called,1273then this procedure will be invoked with the exit-code as argument. The1274default behavior is to terminate the program.12751276Note that this handler is ''not'' invoked when {{emergency-exit}} is1277used.127812791280=== implicit-exit-handler12811282<parameter>(implicit-exit-handler)</parameter>12831284A procedure of no arguments. When the last toplevel expression of the1285program has executed, then the value of this parameter is called. The1286default behaviour is to invoke all pending finalizers.128712881289==== on-exit12901291<procedure>(on-exit THUNK)</procedure>12921293Schedules the zero-argument procedures {{THUNK}} to be executed before1294the process exits, either explicitly via {{exit}} or implicitly after1295execution of the last top-level form. Note that finalizers for1296unreferenced finalized data are run before exit procedures.129712981299=== System interface130013011302==== sleep13031304<procedure>(sleep SECONDS)</procedure>13051306Puts the program to sleep for {{SECONDS}}. If the scheduler is loaded1307(for example when srfi-18 is in use) then only the calling thread is put1308to sleep and other threads may continue executing. Otherwise, the whole1309process is put to sleep.131013111312=== File Input/Output13131314==== flush-output13151316<procedure>(flush-output [PORT])</procedure>13171318Write buffered output to the given output-port. {{PORT}} defaults1319to the value of {{(current-output-port)}}.13201321=== Port predicates13221323==== port-closed?13241325<procedure>(port-closed? PORT)</procedure>13261327Is the given {{PORT}} closed (in all directions)?132813291330=== Built-in parameters13311332Certain behavior of the interpreter and compiled programs can be1333customized via the following built-in parameters:13341335==== case-sensitive13361337<parameter>(case-sensitive)</parameter>13381339If true, then {{read}} reads symbols and identifiers in1340case-sensitive mode and uppercase characters in symbols are printed1341escaped. Defaults to {{#t}}.134213431344==== keyword-style13451346<parameter>(keyword-style)</parameter>13471348Enables alternative keyword syntax, where {{STYLE}} may be either1349{{#:prefix}} (as in Common Lisp), which recognizes symbols beginning1350with a colon as keywords, or {{#:suffix}} (as in DSSSL), which recognizes1351symbols ending with a colon as keywords.1352Any other value disables the alternative syntaxes. In the interpreter1353the default is {{#:suffix}}.135413551356==== parentheses-synonyms13571358<parameter>(parentheses-synonyms)</parameter>13591360If true, then the list delimiter synonyms {{#\[}} {{#\]}} and {{#\{}} {{#\}}} are enabled. Defaults to {{#t}}.136113621363==== symbol-escape13641365<parameter>(symbol-escape)</parameter>13661367If true, then the symbol escape {{#\|}} {{#\|}} is allowed when reading1368and printing expressions. Defaults to {{#t}}.136913701371---1372Previous: [[Module srfi-4]]13731374Next: [[Module (chicken bitwise)]]