This is guile.info, produced by makeinfo version 4.13 from guile.texi. This reference manual documents Guile, GNU's Ubiquitous Intelligent Language for Extensions. This is edition 1.1 corresponding to Guile 1.8.8. Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the no Invariant Sections, with the Front-Cover Texts being "A GNU Manual," and with the Back-Cover Text "You are free to copy and modify this GNU Manual.". A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION The Algorithmic Language Scheme START-INFO-DIR-ENTRY * Guile Reference: (guile). The Guile reference manual. END-INFO-DIR-ENTRY  File: guile.info, Node: SRFI-1 Set Operations, Prev: SRFI-1 Association Lists, Up: SRFI-1 6.4.3.10 Set Operations on Lists ................................ Lists can be used to represent sets of objects. The procedures in this section operate on such lists as sets. Note that lists are not an efficient way to implement large sets. The procedures here typically take time MxN when operating on M and N element lists. Other data structures like trees, bitsets (*note Bit Vectors::) or hash tables (*note Hash Tables::) are faster. All these procedures take an equality predicate as the first argument. This predicate is used for testing the objects in the list sets for sameness. This predicate must be consistent with `eq?' (*note Equality::) in the sense that if two list elements are `eq?' then they must also be equal under the predicate. This simply means a given object must be equal to itself. -- Scheme Procedure: lset<= = list1 list2 ... Return `#t' if each list is a subset of the one following it. Ie. LIST1 a subset of LIST2, LIST2 a subset of LIST3, etc, for as many lists as given. If only one list or no lists are given then the return is `#t'. A list X is a subset of Y if each element of X is equal to some element in Y. Elements are compared using the given = procedure, called as `(= xelem yelem)'. (lset<= eq?) => #t (lset<= eqv? '(1 2 3) '(1)) => #f (lset<= eqv? '(1 3 2) '(4 3 1 2)) => #t -- Scheme Procedure: lset= = list1 list2 ... Return `#t' if all argument lists are set-equal. LIST1 is compared to LIST2, LIST2 to LIST3, etc, for as many lists as given. If only one list or no lists are given then the return is `#t'. Two lists X and Y are set-equal if each element of X is equal to some element of Y and conversely each element of Y is equal to some element of X. The order of the elements in the lists doesn't matter. Element equality is determined with the given = procedure, called as `(= xelem yelem)', but exactly which calls are made is unspecified. (lset= eq?) => #t (lset= eqv? '(1 2 3) '(3 2 1)) => #t (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) => #t -- Scheme Procedure: lset-adjoin = list elem1 ... Add to LIST any of the given ELEMs not already in the list. ELEMs are `cons'ed onto the start of LIST (so the return shares a common tail with LIST), but the order they're added is unspecified. The given = procedure is used for comparing elements, called as `(= listelem elem)', ie. the second argument is one of the given ELEM parameters. (lset-adjoin eqv? '(1 2 3) 4 1 5) => (5 4 1 2 3) -- Scheme Procedure: lset-union = list1 list2 ... -- Scheme Procedure: lset-union! = list1 list2 ... Return the union of the argument list sets. The result is built by taking the union of LIST1 and LIST2, then the union of that with LIST3, etc, for as many lists as given. For one list argument that list itself is the result, for no list arguments the result is the empty list. The union of two lists X and Y is formed as follows. If X is empty then the result is Y. Otherwise start with X as the result and consider each Y element (from first to last). A Y element not equal to something already in the result is `cons'ed onto the result. The given = procedure is used for comparing elements, called as `(= relem yelem)'. The first argument is from the result accumulated so far, and the second is from the list being union-ed in. But exactly which calls are made is otherwise unspecified. Notice that duplicate elements in LIST1 (or the first non-empty list) are preserved, but that repeated elements in subsequent lists are only added once. (lset-union eqv?) => () (lset-union eqv? '(1 2 3)) => (1 2 3) (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) => (5 4 1 2 1 3) `lset-union' doesn't change the given lists but the result may share a tail with the first non-empty list. `lset-union!' can modify all of the given lists to form the result. -- Scheme Procedure: lset-intersection = list1 list2 ... -- Scheme Procedure: lset-intersection! = list1 list2 ... Return the intersection of LIST1 with the other argument lists, meaning those elements of LIST1 which are also in all of LIST2 etc. For one list argument, just that list is returned. The test for an element of LIST1 to be in the return is simply that it's equal to some element in each of LIST2 etc. Notice this means an element appearing twice in LIST1 but only once in each of LIST2 etc will go into the return twice. The return has its elements in the same order as they were in LIST1. The given = procedure is used for comparing elements, called as `(= elem1 elemN)'. The first argument is from LIST1 and the second is from one of the subsequent lists. But exactly which calls are made and in what order is unspecified. (lset-intersection eqv? '(x y)) => (x y) (lset-intersection eqv? '(1 2 3) '(4 3 2)) => (2 3) (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) => (2 2) The return from `lset-intersection' may share a tail with LIST1. `lset-intersection!' may modify LIST1 to form its result. -- Scheme Procedure: lset-difference = list1 list2 ... -- Scheme Procedure: lset-difference! = list1 list2 ... Return LIST1 with any elements in LIST2, LIST3 etc removed (ie. subtracted). For one list argument, just that list is returned. The given = procedure is used for comparing elements, called as `(= elem1 elemN)'. The first argument is from LIST1 and the second from one of the subsequent lists. But exactly which calls are made and in what order is unspecified. (lset-difference eqv? '(x y)) => (x y) (lset-difference eqv? '(1 2 3) '(3 1)) => (2) (lset-difference eqv? '(1 2 3) '(3) '(2)) => (1) The return from `lset-difference' may share a tail with LIST1. `lset-difference!' may modify LIST1 to form its result. -- Scheme Procedure: lset-diff+intersection = list1 list2 ... -- Scheme Procedure: lset-diff+intersection! = list1 list2 ... Return two values (*note Multiple Values::), the difference and intersection of the argument lists as per `lset-difference' and `lset-intersection' above. For two list arguments this partitions LIST1 into those elements of LIST1 which are in LIST2 and not in LIST2. (But for more than two arguments there can be elements of LIST1 which are neither part of the difference nor the intersection.) One of the return values from `lset-diff+intersection' may share a tail with LIST1. `lset-diff+intersection!' may modify LIST1 to form its results. -- Scheme Procedure: lset-xor = list1 list2 ... -- Scheme Procedure: lset-xor! = list1 list2 ... Return an XOR of the argument lists. For two lists this means those elements which are in exactly one of the lists. For more than two lists it means those elements which appear in an odd number of the lists. To be precise, the XOR of two lists X and Y is formed by taking those elements of X not equal to any element of Y, plus those elements of Y not equal to any element of X. Equality is determined with the given = procedure, called as `(= e1 e2)'. One argument is from X and the other from Y, but which way around is unspecified. Exactly which calls are made is also unspecified, as is the order of the elements in the result. (lset-xor eqv? '(x y)) => (x y) (lset-xor eqv? '(1 2 3) '(4 3 2)) => (4 1) The return from `lset-xor' may share a tail with one of the list arguments. `lset-xor!' may modify LIST1 to form its result.  File: guile.info, Node: SRFI-2, Next: SRFI-4, Prev: SRFI-1, Up: SRFI Support 6.4.4 SRFI-2 - and-let* ----------------------- The following syntax can be obtained with (use-modules (srfi srfi-2)) -- library syntax: and-let* (clause ...) body ... A combination of `and' and `let*'. Each CLAUSE is evaluated in turn, and if `#f' is obtained then evaluation stops and `#f' is returned. If all are non-`#f' then BODY is evaluated and the last form gives the return value, or if BODY is empty then the result is `#t'. Each CLAUSE should be one of the following, `(symbol expr)' Evaluate EXPR, check for `#f', and bind it to SYMBOL. Like `let*', that binding is available to subsequent clauses. `(expr)' Evaluate EXPR and check for `#f'. `symbol' Get the value bound to SYMBOL and check for `#f'. Notice that `(expr)' has an "extra" pair of parentheses, for instance `((eq? x y))'. One way to remember this is to imagine the `symbol' in `(symbol expr)' is omitted. `and-let*' is good for calculations where a `#f' value means termination, but where a non-`#f' value is going to be needed in subsequent expressions. The following illustrates this, it returns text between brackets `[...]' in a string, or `#f' if there are no such brackets (ie. either `string-index' gives `#f'). (define (extract-brackets str) (and-let* ((start (string-index str #\[)) (end (string-index str #\] start))) (substring str (1+ start) end))) The following shows plain variables and expressions tested too. `diagnostic-levels' is taken to be an alist associating a diagnostic type with a level. `str' is printed only if the type is known and its level is high enough. (define (show-diagnostic type str) (and-let* (want-diagnostics (level (assq-ref diagnostic-levels type)) ((>= level current-diagnostic-level))) (display str))) The advantage of `and-let*' is that an extended sequence of expressions and tests doesn't require lots of nesting as would arise from separate `and' and `let*', or from `cond' with `=>'.  File: guile.info, Node: SRFI-4, Next: SRFI-6, Prev: SRFI-2, Up: SRFI Support 6.4.5 SRFI-4 - Homogeneous numeric vector datatypes --------------------------------------------------- The SRFI-4 procedures and data types are always available, *Note Uniform Numeric Vectors::.  File: guile.info, Node: SRFI-6, Next: SRFI-8, Prev: SRFI-4, Up: SRFI Support 6.4.6 SRFI-6 - Basic String Ports --------------------------------- SRFI-6 defines the procedures `open-input-string', `open-output-string' and `get-output-string'. These procedures are included in the Guile core, so using this module does not make any difference at the moment. But it is possible that support for SRFI-6 will be factored out of the core library in the future, so using this module does not hurt, after all.  File: guile.info, Node: SRFI-8, Next: SRFI-9, Prev: SRFI-6, Up: SRFI Support 6.4.7 SRFI-8 - receive ---------------------- `receive' is a syntax for making the handling of multiple-value procedures easier. It is documented in *Note Multiple Values::.  File: guile.info, Node: SRFI-9, Next: SRFI-10, Prev: SRFI-8, Up: SRFI Support 6.4.8 SRFI-9 - define-record-type --------------------------------- This SRFI is a syntax for defining new record types and creating predicate, constructor, and field getter and setter functions. In Guile this is simply an alternate interface to the core record functionality (*note Records::). It can be used with, (use-modules (srfi srfi-9)) -- library syntax: define-record-type type (constructor fieldname ...) predicate (fieldname accessor [modifier]) ... Create a new record type, and make various `define's for using it. This syntax can only occur at the top-level, not nested within some other form. TYPE is bound to the record type, which is as per the return from the core `make-record-type'. TYPE also provides the name for the record, as per `record-type-name'. CONSTRUCTOR is bound to a function to be called as `(CONSTRUCTOR fieldval ...)' to create a new record of this type. The arguments are initial values for the fields, one argument for each field, in the order they appear in the `define-record-type' form. The FIELDNAMEs provide the names for the record fields, as per the core `record-type-fields' etc, and are referred to in the subsequent accessor/modifier forms. PREDICTATE is bound to a function to be called as `(PREDICATE obj)'. It returns `#t' or `#f' according to whether OBJ is a record of this type. Each ACCESSOR is bound to a function to be called `(ACCESSOR record)' to retrieve the respective field from a RECORD. Similarly each MODIFIER is bound to a function to be called `(MODIFIER record val)' to set the respective field in a RECORD. An example will illustrate typical usage, (define-record-type employee-type (make-employee name age salary) employee? (name get-employee-name) (age get-employee-age set-employee-age) (salary get-employee-salary set-employee-salary)) This creates a new employee data type, with name, age and salary fields. Accessor functions are created for each field, but no modifier function for the name (the intention in this example being that it's established only when an employee object is created). These can all then be used as for example, employee-type => # (define fred (make-employee "Fred" 45 20000.00)) (employee? fred) => #t (get-employee-age fred) => 45 (set-employee-salary fred 25000.00) ;; pay rise The functions created by `define-record-type' are ordinary top-level `define's. They can be redefined or `set!' as desired, exported from a module, etc.  File: guile.info, Node: SRFI-10, Next: SRFI-11, Prev: SRFI-9, Up: SRFI Support 6.4.9 SRFI-10 - Hash-Comma Reader Extension ------------------------------------------- This SRFI implements a reader extension `#,()' called hash-comma. It allows the reader to give new kinds of objects, for use both in data and as constants or literals in source code. This feature is available with (use-modules (srfi srfi-10)) The new read syntax is of the form #,(TAG ARG...) where TAG is a symbol and the ARGs are objects taken as parameters. TAGs are registered with the following procedure. -- Scheme Procedure: define-reader-ctor tag proc Register PROC as the constructor for a hash-comma read syntax starting with symbol TAG, ie. #,(TAG arg...). PROC is called with the given arguments `(PROC arg...)' and the object it returns is the result of the read. For example, a syntax giving a list of N copies of an object. (define-reader-ctor 'repeat (lambda (obj reps) (make-list reps obj))) (display '#,(repeat 99 3)) -| (99 99 99) Notice the quote ' when the #,( ) is used. The `repeat' handler returns a list and the program must quote to use it literally, the same as any other list. Ie. (display '#,(repeat 99 3)) => (display '(99 99 99)) When a handler returns an object which is self-evaluating, like a number or a string, then there's no need for quoting, just as there's no need when giving those directly as literals. For example an addition, (define-reader-ctor 'sum (lambda (x y) (+ x y))) (display #,(sum 123 456)) -| 579 A typical use for #,() is to get a read syntax for objects which don't otherwise have one. For example, the following allows a hash table to be given literally, with tags and values, ready for fast lookup. (define-reader-ctor 'hash (lambda elems (let ((table (make-hash-table))) (for-each (lambda (elem) (apply hash-set! table elem)) elems) table))) (define (animal->family animal) (hash-ref '#,(hash ("tiger" "cat") ("lion" "cat") ("wolf" "dog")) animal)) (animal->family "lion") => "cat" Or for example the following is a syntax for a compiled regular expression (*note Regular Expressions::). (use-modules (ice-9 regex)) (define-reader-ctor 'regexp make-regexp) (define (extract-angs str) (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str))) (and match (match:substring match 1)))) (extract-angs "foo quux") => "BAR" #,() is somewhat similar to `define-macro' (*note Macros::) in that handler code is run to produce a result, but #,() operates at the read stage, so it can appear in data for `read' (*note Scheme Read::), not just in code to be executed. Because #,() is handled at read-time it has no direct access to variables etc. A symbol in the arguments is just a symbol, not a variable reference. The arguments are essentially constants, though the handler procedure can use them in any complicated way it might want. Once `(srfi srfi-10)' has loaded, #,() is available globally, there's no need to use `(srfi srfi-10)' in later modules. Similarly the tags registered are global and can be used anywhere once registered. There's no attempt to record what previous #,() forms have been seen, if two identical forms occur then two calls are made to the handler procedure. The handler might like to maintain a cache or similar to avoid making copies of large objects, depending on expected usage. In code the best uses of #,() are generally when there's a lot of objects of a particular kind as literals or constants. If there's just a few then some local variables and initializers are fine, but that becomes tedious and error prone when there's a lot, and the anonymous and compact syntax of #,() is much better.  File: guile.info, Node: SRFI-11, Next: SRFI-13, Prev: SRFI-10, Up: SRFI Support 6.4.10 SRFI-11 - let-values --------------------------- This module implements the binding forms for multiple values `let-values' and `let*-values'. These forms are similar to `let' and `let*' (*note Local Bindings::), but they support binding of the values returned by multiple-valued expressions. Write `(use-modules (srfi srfi-11))' to make the bindings available. (let-values (((x y) (values 1 2)) ((z f) (values 3 4))) (+ x y z f)) => 10 `let-values' performs all bindings simultaneously, which means that no expression in the binding clauses may refer to variables bound in the same clause list. `let*-values', on the other hand, performs the bindings sequentially, just like `let*' does for single-valued expressions.  File: guile.info, Node: SRFI-13, Next: SRFI-14, Prev: SRFI-11, Up: SRFI Support 6.4.11 SRFI-13 - String Library ------------------------------- The SRFI-13 procedures are always available, *Note Strings::.  File: guile.info, Node: SRFI-14, Next: SRFI-16, Prev: SRFI-13, Up: SRFI Support 6.4.12 SRFI-14 - Character-set Library -------------------------------------- The SRFI-14 data type and procedures are always available, *Note Character Sets::.  File: guile.info, Node: SRFI-16, Next: SRFI-17, Prev: SRFI-14, Up: SRFI Support 6.4.13 SRFI-16 - case-lambda ---------------------------- The syntactic form `case-lambda' creates procedures, just like `lambda', but has syntactic extensions for writing procedures of varying arity easier. The syntax of the `case-lambda' form is defined in the following EBNF grammar. --> (case-lambda ) --> ( *) --> (*) | (* . ) | The value returned by a `case-lambda' form is a procedure which matches the number of actual arguments against the formals in the various clauses, in order. "Formals" means a formal argument list just like with `lambda' (*note Lambda::). The first matching clause is selected, the corresponding values from the actual parameter list are bound to the variable names in the clauses and the body of the clause is evaluated. If no clause matches, an error is signalled. The following (silly) definition creates a procedure FOO which acts differently, depending on the number of actual arguments. If one argument is given, the constant `#t' is returned, two arguments are added and if more arguments are passed, their product is calculated. (define foo (case-lambda ((x) #t) ((x y) (+ x y)) (z (apply * z)))) (foo 'bar) => #t (foo 2 4) => 6 (foo 3 3 3) => 27 (foo) => 1 The last expression evaluates to 1 because the last clause is matched, Z is bound to the empty list and the following multiplication, applied to zero arguments, yields 1.  File: guile.info, Node: SRFI-17, Next: SRFI-19, Prev: SRFI-16, Up: SRFI Support 6.4.14 SRFI-17 - Generalized set! --------------------------------- This SRFI implements a generalized `set!', allowing some "referencing" functions to be used as the target location of a `set!'. This feature is available from (use-modules (srfi srfi-17)) For example `vector-ref' is extended so that (set! (vector-ref vec idx) new-value) is equivalent to (vector-set! vec idx new-value) The idea is that a `vector-ref' expression identifies a location, which may be either fetched or stored. The same form is used for the location in both cases, encouraging visual clarity. This is similar to the idea of an "lvalue" in C. The mechanism for this kind of `set!' is in the Guile core (*note Procedures with Setters::). This module adds definitions of the following functions as procedures with setters, allowing them to be targets of a `set!', car, cdr, caar, cadr, cdar, cddr, caaar, caadr, cadar, caddr, cdaar, cdadr, cddar, cdddr, caaaar, caaadr, caadar, caaddr, cadaar, cadadr, caddar, cadddr, cdaaar, cdaadr, cdadar, cdaddr, cddaar, cddadr, cdddar, cddddr string-ref, vector-ref The SRFI specifies `setter' (*note Procedures with Setters::) as a procedure with setter, allowing the setter for a procedure to be changed, eg. `(set! (setter foo) my-new-setter-handler)'. Currently Guile does not implement this, a setter can only be specified on creation (`getter-with-setter' below). -- Function: getter-with-setter The same as the Guile core `make-procedure-with-setter' (*note Procedures with Setters::).  File: guile.info, Node: SRFI-19, Next: SRFI-26, Prev: SRFI-17, Up: SRFI Support 6.4.15 SRFI-19 - Time/Date Library ---------------------------------- This is an implementation of the SRFI-19 time/date library. The functions and variables described here are provided by (use-modules (srfi srfi-19)) *Caution*: The current code in this module incorrectly extends the Gregorian calendar leap year rule back prior to the introduction of those reforms in 1582 (or the appropriate year in various countries). The Julian calendar was used prior to 1582, and there were 10 days skipped for the reform, but the code doesn't implement that. This will be fixed some time. Until then calculations for 1583 onwards are correct, but prior to that any day/month/year and day of the week calculations are wrong. * Menu: * SRFI-19 Introduction:: * SRFI-19 Time:: * SRFI-19 Date:: * SRFI-19 Time/Date conversions:: * SRFI-19 Date to string:: * SRFI-19 String to date::  File: guile.info, Node: SRFI-19 Introduction, Next: SRFI-19 Time, Up: SRFI-19 6.4.15.1 SRFI-19 Introduction ............................. This module implements time and date representations and calculations, in various time systems, including universal time (UTC) and atomic time (TAI). For those not familiar with these time systems, TAI is based on a fixed length second derived from oscillations of certain atoms. UTC differs from TAI by an integral number of seconds, which is increased or decreased at announced times to keep UTC aligned to a mean solar day (the orbit and rotation of the earth are not quite constant). So far, only increases in the TAI <-> UTC difference have been needed. Such an increase is a "leap second", an extra second of TAI introduced at the end of a UTC day. When working entirely within UTC this is never seen, every day simply has 86400 seconds. But when converting from TAI to a UTC date, an extra 23:59:60 is present, where normally a day would end at 23:59:59. Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI seconds. In the current implementation, the system clock is assumed to be UTC, and a table of leap seconds in the code converts to TAI. See comments in `srfi-19.scm' for how to update this table. Also, for those not familiar with the terminology, a "Julian Day" is a real number which is a count of days and fraction of a day, in UTC, starting from -4713-01-01T12:00:00Z, ie. midday Monday 1 Jan 4713 B.C. A "Modified Julian Day" is the same, but starting from 1858-11-17T00:00:00Z, ie. midnight 17 November 1858 UTC. That time is julian day 2400000.5.  File: guile.info, Node: SRFI-19 Time, Next: SRFI-19 Date, Prev: SRFI-19 Introduction, Up: SRFI-19 6.4.15.2 SRFI-19 Time ..................... A "time" object has type, seconds and nanoseconds fields representing a point in time starting from some epoch. This is an arbitrary point in time, not just a time of day. Although times are represented in nanoseconds, the actual resolution may be lower. The following variables hold the possible time types. For instance `(current-time time-process)' would give the current CPU process time. -- Variable: time-utc Universal Coordinated Time (UTC). -- Variable: time-tai International Atomic Time (TAI). -- Variable: time-monotonic Monotonic time, meaning a monotonically increasing time starting from an unspecified epoch. Note that in the current implementation `time-monotonic' is the same as `time-tai', and unfortunately is therefore affected by adjustments to the system clock. Perhaps this will change in the future. -- Variable: time-duration A duration, meaning simply a difference between two times. -- Variable: time-process CPU time spent in the current process, starting from when the process began. -- Variable: time-thread CPU time spent in the current thread. Not currently implemented. -- Function: time? obj Return `#t' if OBJ is a time object, or `#f' if not. -- Function: make-time type nanoseconds seconds Create a time object with the given TYPE, SECONDS and NANOSECONDS. -- Function: time-type time -- Function: time-nanosecond time -- Function: time-second time -- Function: set-time-type! time type -- Function: set-time-nanosecond! time nsec -- Function: set-time-second! time sec Get or set the type, seconds or nanoseconds fields of a time object. `set-time-type!' merely changes the field, it doesn't convert the time value. For conversions, see *note SRFI-19 Time/Date conversions::. -- Function: copy-time time Return a new time object, which is a copy of the given TIME. -- Function: current-time [type] Return the current time of the given TYPE. The default TYPE is `time-utc'. Note that the name `current-time' conflicts with the Guile core `current-time' function (*note Time::). Applications wanting to use both will need to use a different name for one of them. -- Function: time-resolution [type] Return the resolution, in nanoseconds, of the given time TYPE. The default TYPE is `time-utc'. -- Function: time<=? t1 t2 -- Function: time=? t1 t2 -- Function: time>? t1 t2 Return `#t' or `#f' according to the respective relation between time objects T1 and T2. T1 and T2 must be the same time type. -- Function: time-difference t1 t2 -- Function: time-difference! t1 t2 Return a time object of type `time-duration' representing the period between T1 and T2. T1 and T2 must be the same time type. `time-difference' returns a new time object, `time-difference!' may modify T1 to form its return. -- Function: add-duration time duration -- Function: add-duration! time duration -- Function: subtract-duration time duration -- Function: subtract-duration! time duration Return a time object which is TIME with the given DURATION added or subtracted. DURATION must be a time object of type `time-duration'. `add-duration' and `subtract-duration' return a new time object. `add-duration!' and `subtract-duration!' may modify the given TIME to form their return.  File: guile.info, Node: SRFI-19 Date, Next: SRFI-19 Time/Date conversions, Prev: SRFI-19 Time, Up: SRFI-19 6.4.15.3 SRFI-19 Date ..................... A "date" object represents a date in the Gregorian calendar and a time of day on that date in some timezone. The fields are year, month, day, hour, minute, second, nanoseconds and timezone. A date object is immutable, its fields can be read but they cannot be modified once the object is created. -- Function: date? obj Return `#t' if OBJ is a date object, or `#f' if not. -- Function: make-date nsecs seconds minutes hours date month year zone-offset Create a new date object. -- Function: date-nanosecond date Nanoseconds, 0 to 999999999. -- Function: date-second date Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working entirely within UTC, it's only when converting to or from TAI. -- Function: date-minute date Minutes, 0 to 59. -- Function: date-hour date Hour, 0 to 23. -- Function: date-day date Day of the month, 1 to 31 (or less, according to the month). -- Function: date-month date Month, 1 to 12. -- Function: date-year date Year, eg. 2003. Dates B.C. are negative, eg. -46 is 46 B.C. There is no year 0, year -1 is followed by year 1. -- Function: date-zone-offset date Time zone, an integer number of seconds east of Greenwich. -- Function: date-year-day date Day of the year, starting from 1 for 1st January. -- Function: date-week-day date Day of the week, starting from 0 for Sunday. -- Function: date-week-number date dstartw Week of the year, ignoring a first partial week. DSTARTW is the day of the week which is taken to start a week, 0 for Sunday, 1 for Monday, etc. -- Function: current-date [tz-offset] Return a date object representing the current date/time, in UTC offset by TZ-OFFSET. TZ-OFFSET is seconds east of Greenwich and defaults to the local timezone. -- Function: current-julian-day Return the current Julian Day. -- Function: current-modified-julian-day Return the current Modified Julian Day.  File: guile.info, Node: SRFI-19 Time/Date conversions, Next: SRFI-19 Date to string, Prev: SRFI-19 Date, Up: SRFI-19 6.4.15.4 SRFI-19 Time/Date conversions ...................................... -- Function: date->julian-day date -- Function: date->modified-julian-day date -- Function: date->time-monotonic date -- Function: date->time-tai date -- Function: date->time-utc date -- Function: julian-day->date jdn [tz-offset] -- Function: julian-day->time-monotonic jdn -- Function: julian-day->time-tai jdn -- Function: julian-day->time-utc jdn -- Function: modified-julian-day->date jdn [tz-offset] -- Function: modified-julian-day->time-monotonic jdn -- Function: modified-julian-day->time-tai jdn -- Function: modified-julian-day->time-utc jdn -- Function: time-monotonic->date time [tz-offset] -- Function: time-monotonic->time-tai time -- Function: time-monotonic->time-tai! time -- Function: time-monotonic->time-utc time -- Function: time-monotonic->time-utc! time -- Function: time-tai->date time [tz-offset] -- Function: time-tai->julian-day time -- Function: time-tai->modified-julian-day time -- Function: time-tai->time-monotonic time -- Function: time-tai->time-monotonic! time -- Function: time-tai->time-utc time -- Function: time-tai->time-utc! time -- Function: time-utc->date time [tz-offset] -- Function: time-utc->julian-day time -- Function: time-utc->modified-julian-day time -- Function: time-utc->time-monotonic time -- Function: time-utc->time-monotonic! time -- Function: time-utc->time-tai time -- Function: time-utc->time-tai! time Convert between dates, times and days of the respective types. For instance `time-tai->time-utc' accepts a TIME object of type `time-tai' and returns an object of type `time-utc'. The `!' variants may modify their TIME argument to form their return. The plain functions create a new object. For conversions to dates, TZ-OFFSET is seconds east of Greenwich. The default is the local timezone, at the given time, as provided by the system, using `localtime' (*note Time::). On 32-bit systems, `localtime' is limited to a 32-bit `time_t', so a default TZ-OFFSET is only available for times between Dec 1901 and Jan 2038. For prior dates an application might like to use the value in 1902, though some locations have zone changes prior to that. For future dates an application might like to assume today's rules extend indefinitely. But for correct daylight savings transitions it will be necessary to take an offset for the same day and time but a year in range and which has the same starting weekday and same leap/non-leap (to support rules like last Sunday in October).  File: guile.info, Node: SRFI-19 Date to string, Next: SRFI-19 String to date, Prev: SRFI-19 Time/Date conversions, Up: SRFI-19 6.4.15.5 SRFI-19 Date to string ............................... -- Function: date->string date [format] Convert a date to a string under the control of a format. FORMAT should be a string containing `~' escapes, which will be expanded as per the following conversion table. The default FORMAT is `~c', a locale-dependent date and time. Many of these conversion characters are the same as POSIX `strftime' (*note Time::), but there are some extras and some variations. ~~ literal ~ ~a locale abbreviated weekday, eg. `Sun' ~A locale full weekday, eg. `Sunday' ~b locale abbreviated month, eg. `Jan' ~B locale full month, eg. `January' ~c locale date and time, eg. `Fri Jul 14 20:28:42-0400 2000' ~d day of month, zero padded, `01' to `31' ~e day of month, blank padded, ` 1' to `31' ~f seconds and fractional seconds, with locale decimal point, eg. `5.2' ~h same as ~b ~H hour, 24-hour clock, zero padded, `00' to `23' ~I hour, 12-hour clock, zero padded, `01' to `12' ~j day of year, zero padded, `001' to `366' ~k hour, 24-hour clock, blank padded, ` 0' to `23' ~l hour, 12-hour clock, blank padded, ` 1' to `12' ~m month, zero padded, `01' to `12' ~M minute, zero padded, `00' to `59' ~n newline ~N nanosecond, zero padded, `000000000' to `999999999' ~p locale AM or PM ~r time, 12 hour clock, `~I:~M:~S ~p' ~s number of full seconds since "the epoch" in UTC ~S second, zero padded `00' to `60' (usual limit is 59, 60 is a leap second) ~t horizontal tab character ~T time, 24 hour clock, `~H:~M:~S' ~U week of year, Sunday first day of week, `00' to `52' ~V week of year, Monday first day of week, `01' to `53' ~w day of week, 0 for Sunday, `0' to `6' ~W week of year, Monday first day of week, `00' to `52' ~y year, two digits, `00' to `99' ~Y year, full, eg. `2003' ~z time zone, RFC-822 style ~Z time zone symbol (not currently implemented) ~1 ISO-8601 date, `~Y-~m-~d' ~2 ISO-8601 time+zone, `~k:~M:~S~z' ~3 ISO-8601 time, `~k:~M:~S' ~4 ISO-8601 date/time+zone, `~Y-~m-~dT~k:~M:~S~z' ~5 ISO-8601 date/time, `~Y-~m-~dT~k:~M:~S' Conversions `~D', `~x' and `~X' are not currently described here, since the specification and reference implementation differ. Currently Guile doesn't implement any localizations for the above, all outputs are in English, and the `~c' conversion is POSIX `ctime' style `~a ~b ~d ~H:~M:~S~z ~Y'. This may change in the future.  File: guile.info, Node: SRFI-19 String to date, Prev: SRFI-19 Date to string, Up: SRFI-19 6.4.15.6 SRFI-19 String to date ............................... -- Function: string->date input template Convert an INPUT string to a date under the control of a TEMPLATE string. Return a newly created date object. Literal characters in TEMPLATE must match characters in INPUT and `~' escapes must match the input forms described in the table below. "Skip to" means characters up to one of the given type are ignored, or "no skip" for no skipping. "Read" is what's then read, and "Set" is the field affected in the date object. For example `~Y' skips input characters until a digit is reached, at which point it expects a year and stores that to the year field of the date. Skip to Read Set ~~ no skip literal ~ nothing ~a char-alphabetic? locale abbreviated weekday nothing name ~A char-alphabetic? locale full weekday name nothing ~b char-alphabetic? locale abbreviated month date-month name ~B char-alphabetic? locale full month name date-month ~d char-numeric? day of month date-day ~e no skip day of month, blank padded date-day ~h same as `~b' ~H char-numeric? hour date-hour ~k no skip hour, blank padded date-hour ~m char-numeric? month date-month ~M char-numeric? minute date-minute ~S char-numeric? second date-second ~y no skip 2-digit year date-year within 50 years ~Y char-numeric? year date-year ~z no skip time zone date-zone-offset Notice that the weekday matching forms don't affect the date object returned, instead the weekday will be derived from the day, month and year. Currently Guile doesn't implement any localizations for the above, month and weekday names are always expected in English. This may change in the future.  File: guile.info, Node: SRFI-26, Next: SRFI-31, Prev: SRFI-19, Up: SRFI Support 6.4.16 SRFI-26 - specializing parameters ---------------------------------------- This SRFI provides a syntax for conveniently specializing selected parameters of a function. It can be used with, (use-modules (srfi srfi-26)) -- library syntax: cut slot ... -- library syntax: cute slot ... Return a new procedure which will make a call (SLOT ...) but with selected parameters specialized to given expressions. An example will illustrate the idea. The following is a specialization of `write', sending output to `my-output-port', (cut write <> my-output-port) => (lambda (obj) (write obj my-output-port)) The special symbol `<>' indicates a slot to be filled by an argument to the new procedure. `my-output-port' on the other hand is an expression to be evaluated and passed, ie. it specializes the behaviour of `write'. <> A slot to be filled by an argument from the created procedure. Arguments are assigned to `<>' slots in the order they appear in the `cut' form, there's no way to re-arrange arguments. The first argument to `cut' is usually a procedure (or expression giving a procedure), but `<>' is allowed there too. For example, (cut <> 1 2 3) => (lambda (proc) (proc 1 2 3)) <...> A slot to be filled by all remaining arguments from the new procedure. This can only occur at the end of a `cut' form. For example, a procedure taking a variable number of arguments like `max' but in addition enforcing a lower bound, (define my-lower-bound 123) (cut max my-lower-bound <...>) => (lambda arglist (apply max my-lower-bound arglist)) For `cut' the specializing expressions are evaluated each time the new procedure is called. For `cute' they're evaluated just once, when the new procedure is created. The name `cute' stands for "`cut' with evaluated arguments". In all cases the evaluations take place in an unspecified order. The following illustrates the difference between `cut' and `cute', (cut format <> "the time is ~s" (current-time)) => (lambda (port) (format port "the time is ~s" (current-time))) (cute format <> "the time is ~s" (current-time)) => (let ((val (current-time))) (lambda (port) (format port "the time is ~s" val)) (There's no provision for a mixture of `cut' and `cute' where some expressions would be evaluated every time but others evaluated only once.) `cut' is really just a shorthand for the sort of `lambda' forms shown in the above examples. But notice `cut' avoids the need to name unspecialized parameters, and is more compact. Use in functional programming style or just with `map', `for-each' or similar is typical. (map (cut * 2 <>) '(1 2 3 4)) (for-each (cut write <> my-port) my-list)  File: guile.info, Node: SRFI-31, Next: SRFI-34, Prev: SRFI-26, Up: SRFI Support 6.4.17 SRFI-31 - A special form `rec' for recursive evaluation -------------------------------------------------------------- SRFI-31 defines a special form that can be used to create self-referential expressions more conveniently. The syntax is as follows: --> (rec ) --> (rec (+) ) The first syntax can be used to create self-referential expressions, for example: guile> (define tmp (rec ones (cons 1 (delay ones)))) The second syntax can be used to create anonymous recursive functions: guile> (define tmp (rec (display-n item n) (if (positive? n) (begin (display n) (display-n (- n 1)))))) guile> (tmp 42 3) 424242 guile>  File: guile.info, Node: SRFI-34, Next: SRFI-35, Prev: SRFI-31, Up: SRFI Support 6.4.18 SRFI-34 - Exception handling for programs ------------------------------------------------ Guile provides an implementation of SRFI-34's exception handling mechanisms (http://srfi.schemers.org/srfi-34/srfi-34.html) as an alternative to its own built-in mechanisms (*note Exceptions::). It can be made available as follows: (use-modules (srfi srfi-34))  File: guile.info, Node: SRFI-35, Next: SRFI-37, Prev: SRFI-34, Up: SRFI Support 6.4.19 SRFI-35 - Conditions --------------------------- SRFI-35 (http://srfi.schemers.org/srfi-35/srfi-35.html) implements "conditions", a data structure akin to records designed to convey information about exceptional conditions between parts of a program. It is normally used in conjunction with SRFI-34's `raise': (raise (condition (&message (message "An error occurred")))) Users can define "condition types" containing arbitrary information. Condition types may inherit from one another. This allows the part of the program that handles (or "catches") conditions to get accurate information about the exceptional condition that arose. SRFI-35 conditions are made available using: (use-modules (srfi srfi-35)) The procedures available to manipulate condition types are the following: -- Scheme Procedure: make-condition-type id parent field-names Return a new condition type named ID, inheriting from PARENT, and with the fields whose names are listed in FIELD-NAMES. FIELD-NAMES must be a list of symbols and must not contain names already used by PARENT or one of its supertypes. -- Scheme Procedure: condition-type? obj Return true if OBJ is a condition type. Conditions can be created and accessed with the following procedures: -- Scheme Procedure: make-condition type . field+value Return a new condition of type TYPE with fields initialized as specified by FIELD+VALUE, a sequence of field names (symbols) and values as in the following example: (let ((&ct (make-condition-type 'foo &condition '(a b c)))) (make-condition &ct 'a 1 'b 2 'c 3)) Note that all fields of TYPE and its supertypes must be specified. -- Scheme Procedure: make-compound-condition . conditions Return a new compound condition composed of CONDITIONS. The returned condition has the type of each condition of CONDITIONS (per `condition-has-type?'). -- Scheme Procedure: condition-has-type? c type Return true if condition C has type TYPE. -- Scheme Procedure: condition-ref c field-name Return the value of the field named FIELD-NAME from condition C. If C is a compound condition and several underlying condition types contain a field named FIELD-NAME, then the value of the first such field is returned, using the order in which conditions were passed to MAKE-COMPOUND-CONDITION. -- Scheme Procedure: extract-condition c type Return a condition of condition type TYPE with the field values specified by C. If C is a compound condition, extract the field values from the subcondition belonging to TYPE that appeared first in the call to `make-compound-condition' that created the the condition. Convenience macros are also available to create condition types and conditions. -- library syntax: define-condition-type type supertype predicate field-spec... Define a new condition type named TYPE that inherits from SUPERTYPE. In addition, bind PREDICATE to a type predicate that returns true when passed a condition of type TYPE or any of its subtypes. FIELD-SPEC must have the form `(field accessor)' where FIELD is the name of field of TYPE and ACCESSOR is the name of a procedure to access field FIELD in conditions of type TYPE. The example below defines condition type `&foo', inheriting from `&condition' with fields `a', `b' and `c': (define-condition-type &foo &condition foo-condition? (a foo-a) (b foo-b) (c foo-c)) -- library syntax: condition type-field-bindings... Return a new condition, or compound condition, initialized according to TYPE-FIELD-BINDINGS. Each TYPE-FIELD-BINDING must have the form `(type field-specs...)', where TYPE is the name of a variable bound to condition type; each FIELD-SPEC must have the form `(field-name value)' where FIELD-NAME is a symbol denoting the field being initialized to VALUE. As for `make-condition', all fields must be specified. The following example returns a simple condition: (condition (&message (message "An error occurred"))) The one below returns a compound condition: (condition (&message (message "An error occurred")) (&serious)) Finally, SRFI-35 defines a several standard condition types. -- Variable: &condition This condition type is the root of all condition types. It has no fields. -- Variable: &message A condition type that carries a message describing the nature of the condition to humans. -- Scheme Procedure: message-condition? c Return true if C is of type `&message' or one of its subtypes. -- Scheme Procedure: condition-message c Return the message associated with message condition C. -- Variable: &serious This type describes conditions serious enough that they cannot safely be ignored. It has no fields. -- Scheme Procedure: serious-condition? c Return true if C is of type `&serious' or one of its subtypes. -- Variable: &error This condition describes errors, typically caused by something that has gone wrong in the interaction of the program with the external world or the user. -- Scheme Procedure: error? c Return true if C is of type `&error' or one of its subtypes.  File: guile.info, Node: SRFI-37, Next: SRFI-39, Prev: SRFI-35, Up: SRFI Support 6.4.20 SRFI-37 - args-fold -------------------------- This is a processor for GNU `getopt_long'-style program arguments. It provides an alternative, less declarative interface than `getopt-long' in `(ice-9 getopt-long)' (*note The (ice-9 getopt-long) Module: getopt-long.). Unlike `getopt-long', it supports repeated options and any number of short and long names per option. Access it with: (use-modules (srfi srfi-37)) SRFI-37 principally provides an `option' type and the `args-fold' function. To use the library, create a set of options with `option' and use it as a specification for invoking `args-fold'. Here is an example of a simple argument processor for the typical `--version' and `--help' options, which returns a backwards list of files given on the command line: (args-fold (cdr (program-arguments)) (let ((display-and-exit-proc (lambda (msg) (lambda (opt name arg loads) (display msg) (quit))))) (list (option '(#\v "version") #f #f (display-and-exit-proc "Foo version 42.0\n")) (option '(#\h "help") #f #f (display-and-exit-proc "Usage: foo scheme-file ...")))) (lambda (opt name arg loads) (error "Unrecognized option `~A'" name)) (lambda (op loads) (cons op loads)) '()) -- Scheme Procedure: option names required-arg? optional-arg? processor Return an object that specifies a single kind of program option. NAMES is a list of command-line option names, and should consist of characters for traditional `getopt' short options and strings for `getopt_long'-style long options. REQUIRED-ARG? and OPTIONAL-ARG? are mutually exclusive; one or both must be `#f'. If REQUIRED-ARG?, the option must be followed by an argument on the command line, such as `--opt=value' for long options, or an error will be signalled. If OPTIONAL-ARG?, an argument will be taken if available. PROCESSOR is a procedure that takes at least 3 arguments, called when `args-fold' encounters the option: the containing option object, the name used on the command line, and the argument given for the option (or `#f' if none). The rest of the arguments are `args-fold' "seeds", and the PROCESSOR should return seeds as well. -- Scheme Procedure: option-names opt -- Scheme Procedure: option-required-arg? opt -- Scheme Procedure: option-optional-arg? opt -- Scheme Procedure: option-processor opt Return the specified field of OPT, an option object, as described above for `option'. -- Scheme Procedure: args-fold args options unrecognized-option-proc operand-proc seeds ... Process ARGS, a list of program arguments such as that returned by `(cdr (program-arguments))', in order against OPTIONS, a list of option objects as described above. All functions called take the "seeds", or the last multiple-values as multiple arguments, starting with SEEDS, and must return the new seeds. Return the final seeds. Call `unrecognized-option-proc', which is like an option object's processor, for any options not found in OPTIONS. Call `operand-proc' with any items on the command line that are not named options. This includes arguments after `--'. It is called with the argument in question, as well as the seeds.  File: guile.info, Node: SRFI-39, Next: SRFI-55, Prev: SRFI-37, Up: SRFI Support 6.4.21 SRFI-39 - Parameters --------------------------- This SRFI provides parameter objects, which implement dynamically bound locations for values. The functions below are available from (use-modules (srfi srfi-39)) A parameter object is a procedure. Called with no arguments it returns its value, called with one argument it sets the value. (define my-param (make-parameter 123)) (my-param) => 123 (my-param 456) (my-param) => 456 The `parameterize' special form establishes new locations for parameters, those new locations having effect within the dynamic scope of the `parameterize' body. Leaving restores the previous locations, or re-entering through a saved continuation will again use the new locations. (parameterize ((my-param 789)) (my-param) => 789 ) (my-param) => 456 Parameters are like dynamically bound variables in other Lisp dialets. They allow an application to establish parameter settings (as the name suggests) just for the execution of a particular bit of code, restoring when done. Examples of such parameters might be case-sensitivity for a search, or a prompt for user input. Global variables are not as good as parameter objects for this sort of thing. Changes to them are visible to all threads, but in Guile parameter object locations are per-thread, thereby truely limiting the effect of `parameterize' to just its dynamic execution. Passing arguments to functions is thread-safe, but that soon becomes tedious when there's more than a few or when they need to pass down through several layers of calls before reaching the point they should affect. And introducing a new setting to existing code is often easier with a parameter object than adding arguments. -- Function: make-parameter init [converter] Return a new parameter object, with initial value INIT. A parameter object is a procedure. When called `(param)' it returns its value, or a call `(param val)' sets its value. For example, (define my-param (make-parameter 123)) (my-param) => 123 (my-param 456) (my-param) => 456 If a CONVERTER is given, then a call `(CONVERTER val)' is made for each value set, its return is the value stored. Such a call is made for the INIT initial value too. A CONVERTER allows values to be validated, or put into a canonical form. For example, (define my-param (make-parameter 123 (lambda (val) (if (not (number? val)) (error "must be a number")) (inexact->exact val)))) (my-param 0.75) (my-param) => 3/4 -- library syntax: parameterize ((param value) ...) body ... Establish a new dynamic scope with the given PARAMs bound to new locations and set to the given VALUEs. BODY is evaluated in that environment, the result is the return from the last form in BODY. Each PARAM is an expression which is evaluated to get the parameter object. Often this will just be the name of a variable holding the object, but it can be anything that evaluates to a parameter. The PARAM expressions and VALUE expressions are all evaluated before establishing the new dynamic bindings, and they're evaluated in an unspecified order. For example, (define prompt (make-parameter "Type something: ")) (define (get-input) (display (prompt)) ...) (parameterize ((prompt "Type a number: ")) (get-input) ...) -- Parameter object: current-input-port [new-port] -- Parameter object: current-output-port [new-port] -- Parameter object: current-error-port [new-port] This SRFI extends the core `current-input-port' and `current-output-port', making them parameter objects. The Guile-specific `current-error-port' is extended too, for consistency. (*note Default Ports::.) This is an upwardly compatible extension, a plain call like `(current-input-port)' still returns the current input port, and `set-current-input-port' can still be used. But the port can now also be set with `(current-input-port my-port)' and bound dynamically with `parameterize'. -- Function: with-parameters* param-list value-list thunk Establish a new dynamic scope, as per `parameterize' above, taking parameters from PARAM-LIST and corresponding values from VALUES-LIST. A call `(THUNK)' is made in the new scope and the result from that THUNK is the return from `with-parameters*'. This function is a Guile-specific addition to the SRFI, it's similar to the core `with-fluids*' (*note Fluids and Dynamic States::). Parameter objects are implemented using fluids (*note Fluids and Dynamic States::), so each dynamic state has it's own parameter locations. That includes the separate locations when outside any `parameterize' form. When a parameter is created it gets a separate initial location in each dynamic state, all initialized to the given INIT value. As alluded to above, because each thread usually has a separate dynamic state, each thread has it's own locations behind parameter objects, and changes in one thread are not visible to any other. When a new dynamic state or thread is created, the values of parameters in the originating context are copied, into new locations. SRFI-39 doesn't specify the interaction between parameter objects and threads, so the threading behaviour described here should be regarded as Guile-specific.  File: guile.info, Node: SRFI-55, Next: SRFI-60, Prev: SRFI-39, Up: SRFI Support 6.4.22 SRFI-55 - Requiring Features ----------------------------------- SRFI-55 provides `require-extension' which is a portable mechanism to load selected SRFI modules. This is implemented in the Guile core, there's no module needed to get SRFI-55 itself. -- library syntax: require-extension clause... Require each of the given CLAUSE features, throwing an error if any are unavailable. A CLAUSE is of the form `(IDENTIFIER arg...)'. The only IDENTIFIER currently supported is `srfi' and the arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6, (require-extension (srfi 1 6)) `require-extension' can only be used at the top-level. A Guile-specific program can simply `use-modules' to load SRFIs not already in the core, `require-extension' is for programs designed to be portable to other Scheme implementations.  File: guile.info, Node: SRFI-60, Next: SRFI-61, Prev: SRFI-55, Up: SRFI Support 6.4.23 SRFI-60 - Integers as Bits --------------------------------- This SRFI provides various functions for treating integers as bits and for bitwise manipulations. These functions can be obtained with, (use-modules (srfi srfi-60)) Integers are treated as infinite precision twos-complement, the same as in the core logical functions (*note Bitwise Operations::). And likewise bit indexes start from 0 for the least significant bit. The following functions in this SRFI are already in the Guile core, `logand', `logior', `logxor', `lognot', `logtest', `logcount', `integer-length', `logbit?', `ash' -- Function: bitwise-and n1 ... -- Function: bitwise-ior n1 ... -- Function: bitwise-xor n1 ... -- Function: bitwise-not n -- Function: any-bits-set? j k -- Function: bit-set? index n -- Function: arithmetic-shift n count -- Function: bit-field n start end -- Function: bit-count n Aliases for `logand', `logior', `logxor', `lognot', `logtest', `logbit?', `ash', `bit-extract' and `logcount' respectively. Note that the name `bit-count' conflicts with `bit-count' in the core (*note Bit Vectors::). -- Function: bitwise-if mask n1 n0 -- Function: bitwise-merge mask n1 n0 Return an integer with bits selected from N1 and N0 according to MASK. Those bits where MASK has 1s are taken from N1, and those where MASK has 0s are taken from N0. (bitwise-if 3 #b0101 #b1010) => 9 -- Function: log2-binary-factors n -- Function: first-set-bit n Return a count of how many factors of 2 are present in N. This is also the bit index of the lowest 1 bit in N. If N is 0, the return is -1. (log2-binary-factors 6) => 1 (log2-binary-factors -8) => 3 -- Function: copy-bit index n newbit Return N with the bit at INDEX set according to NEWBIT. NEWBIT should be `#t' to set the bit to 1, or `#f' to set it to 0. Bits other than at INDEX are unchanged in the return. (copy-bit 1 #b0101 #t) => 7 -- Function: copy-bit-field n newbits start end Return N with the bits from START (inclusive) to END (exclusive) changed to the value NEWBITS. The least significant bit in NEWBITS goes to START, the next to START+1, etc. Anything in NEWBITS past the END given is ignored. (copy-bit-field #b10000 #b11 1 3) => #b10110 -- Function: rotate-bit-field n count start end Return N with the bit field from START (inclusive) to END (exclusive) rotated upwards by COUNT bits. COUNT can be positive or negative, and it can be more than the field width (it'll be reduced modulo the width). (rotate-bit-field #b0110 2 1 4) => #b1010 -- Function: reverse-bit-field n start end Return N with the bits from START (inclusive) to END (exclusive) reversed. (reverse-bit-field #b101001 2 4) => #b100101 -- Function: integer->list n [len] Return bits from N in the form of a list of `#t' for 1 and `#f' for 0. The least significant LEN bits are returned, and the first list element is the most significant of those bits. If LEN is not given, the default is `(integer-length N)' (*note Bitwise Operations::). (integer->list 6) => (#t #t #f) (integer->list 1 4) => (#f #f #f #t) -- Function: list->integer lst -- Function: booleans->integer bool... Return an integer formed bitwise from the given LST list of booleans, or for `booleans->integer' from the BOOL arguments. Each boolean is `#t' for a 1 and `#f' for a 0. The first element becomes the most significant bit in the return. (list->integer '(#t #f #t #f)) => 10  File: guile.info, Node: SRFI-61, Next: SRFI-69, Prev: SRFI-60, Up: SRFI Support 6.4.24 SRFI-61 - A more general `cond' clause --------------------------------------------- This SRFI extends RnRS `cond' to support test expressions that return multiple values, as well as arbitrary definitions of test success. SRFI 61 is implemented in the Guile core; there's no module needed to get SRFI-61 itself. Extended `cond' is documented in *note Simple Conditional Evaluation: if cond case.  File: guile.info, Node: SRFI-69, Next: SRFI-88, Prev: SRFI-61, Up: SRFI Support 6.4.25 SRFI-69 - Basic hash tables ---------------------------------- This is a portable wrapper around Guile's built-in hash table and weak table support. *Note Hash Tables::, for information on that built-in support. Above that, this hash-table interface provides association of equality and hash functions with tables at creation time, so variants of each function are not required, as well as a procedure that takes care of most uses for Guile hash table handles, which this SRFI does not provide as such. Access it with: (use-modules (srfi srfi-69)) * Menu: * SRFI-69 Creating hash tables:: * SRFI-69 Accessing table items:: * SRFI-69 Table properties:: * SRFI-69 Hash table algorithms::  File: guile.info, Node: SRFI-69 Creating hash tables, Next: SRFI-69 Accessing table items, Up: SRFI-69 6.4.25.1 Creating hash tables ............................. -- Scheme Procedure: make-hash-table [equal-proc hash-proc #:weak weakness start-size] Create and answer a new hash table with EQUAL-PROC as the equality function and HASH-PROC as the hashing function. By default, EQUAL-PROC is `equal?'. It can be any two-argument procedure, and should answer whether two keys are the same for this table's purposes. My default HASH-PROC assumes that `equal-proc' is no coarser than `equal?' unless it is literally `string-ci=?'. If provided, HASH-PROC should be a two-argument procedure that takes a key and the current table size, and answers a reasonably good hash integer between 0 (inclusive) and the size (exclusive). WEAKNESS should be `#f' or a symbol indicating how "weak" the hash table is: `#f' An ordinary non-weak hash table. This is the default. `key' When the key has no more non-weak references at GC, remove that entry. `value' When the value has no more non-weak references at GC, remove that entry. `key-or-value' When either has no more non-weak references at GC, remove the association. As a legacy of the time when Guile couldn't grow hash tables, START-SIZE is an optional integer argument that specifies the approximate starting size for the hash table, which will be rounded to an algorithmically-sounder number. By "coarser" than `equal?', we mean that for all X and Y values where `(EQUAL-PROC X Y)', `(equal? X Y)' as well. If that does not hold for your EQUAL-PROC, you must provide a HASH-PROC. In the case of weak tables, remember that "references" above always refers to `eq?'-wise references. Just because you have a reference to some string `"foo"' doesn't mean that an association with key `"foo"' in a weak-key table _won't_ be collected; it only counts as a reference if the two `"foo"'s are `eq?', regardless of EQUAL-PROC. As such, it is usually only sensible to use `eq?' and `hashq' as the equivalence and hash functions for a weak table. *Note Weak References::, for more information on Guile's built-in weak table support. -- Scheme Procedure: alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size] As with `make-hash-table', but initialize it with the associations in ALIST. Where keys are repeated in ALIST, the leftmost association takes precedence.  File: guile.info, Node: SRFI-69 Accessing table items, Next: SRFI-69 Table properties, Prev: SRFI-69 Creating hash tables, Up: SRFI-69 6.4.25.2 Accessing table items .............................. -- Scheme Procedure: hash-table-ref table key [default-thunk] -- Scheme Procedure: hash-table-ref/default table key default Answer the value associated with KEY in TABLE. If KEY is not present, answer the result of invoking the thunk DEFAULT-THUNK, which signals an error instead by default. `hash-table-ref/default' is a variant that requires a third argument, DEFAULT, and answers DEFAULT itself instead of invoking it. -- Scheme Procedure: hash-table-set! table key new-value Set KEY to NEW-VALUE in TABLE. -- Scheme Procedure: hash-table-delete! table key Remove the association of KEY in TABLE, if present. If absent, do nothing. -- Scheme Procedure: hash-table-exists? table key Answer whether KEY has an association in TABLE. -- Scheme Procedure: hash-table-update! table key modifier [default-thunk] -- Scheme Procedure: hash-table-update!/default table key modifier default Replace KEY's associated value in TABLE by invoking MODIFIER with one argument, the old value. If KEY is not present, and DEFAULT-THUNK is provided, invoke it with no arguments to get the "old value" to be passed to MODIFIER as above. If DEFAULT-THUNK is not provided in such a case, signal an error. `hash-table-update!/default' is a variant that requires the fourth argument, which is used directly as the "old value" rather than as a thunk to be invoked to retrieve the "old value".  File: guile.info, Node: SRFI-69 Table properties, Next: SRFI-69 Hash table algorithms, Prev: SRFI-69 Accessing table items, Up: SRFI-69 6.4.25.3 Table properties ......................... -- Scheme Procedure: hash-table-size table Answer the number of associations in TABLE. This is guaranteed to run in constant time for non-weak tables. -- Scheme Procedure: hash-table-keys table Answer an unordered list of the keys in TABLE. -- Scheme Procedure: hash-table-values table Answer an unordered list of the values in TABLE. -- Scheme Procedure: hash-table-walk table proc Invoke PROC once for each association in TABLE, passing the key and value as arguments. -- Scheme Procedure: hash-table-fold table proc init Invoke `(PROC KEY VALUE PREVIOUS)' for each KEY and VALUE in TABLE, where PREVIOUS is the result of the previous invocation, using INIT as the first PREVIOUS value. Answer the final PROC result. -- Scheme Procedure: hash-table->alist table Answer an alist where each association in TABLE is an association in the result.  File: guile.info, Node: SRFI-69 Hash table algorithms, Prev: SRFI-69 Table properties, Up: SRFI-69 6.4.25.4 Hash table algorithms .............................. Each hash table carries an "equivalence function" and a "hash function", used to implement key lookups. Beginning users should follow the rules for consistency of the default HASH-PROC specified above. Advanced users can use these to implement their own equivalence and hash functions for specialized lookup semantics. -- Scheme Procedure: hash-table-equivalence-function hash-table -- Scheme Procedure: hash-table-hash-function hash-table Answer the equivalence and hash function of HASH-TABLE, respectively. -- Scheme Procedure: hash obj [size] -- Scheme Procedure: string-hash obj [size] -- Scheme Procedure: string-ci-hash obj [size] -- Scheme Procedure: hash-by-identity obj [size] Answer a hash value appropriate for equality predicate `equal?', `string=?', `string-ci=?', and `eq?', respectively. `hash' is a backwards-compatible replacement for Guile's built-in `hash'.  File: guile.info, Node: SRFI-88, Prev: SRFI-69, Up: SRFI Support 6.4.26 SRFI-88 Keyword Objects ------------------------------ SRFI-88 (http://srfi.schemers.org/srfi-88/srfi-88.html) provides "keyword objects", which are equivalent to Guile's keywords (*note Keywords::). SRFI-88 keywords can be entered using the "postfix keyword syntax", which consists of an identifier followed by `:' (*note `postfix' keyword syntax: Reader options.). SRFI-88 can be made available with: (use-modules (srfi srfi-88)) Doing so installs the right reader option for keyword syntax, using `(read-set! keywords 'postfix)'. It also provides the procedures described below. -- Scheme Procedure: keyword? obj Return `#t' if OBJ is a keyword. This is the same procedure as the same-named built-in procedure (*note `keyword?': Keyword Procedures.). (keyword? foo:) => #t (keyword? 'foo:) => #t (keyword? "foo") => #f -- Scheme Procedure: keyword->string kw Return the name of KW as a string, i.e., without the trailing colon. The returned string may not be modified, e.g., with `string-set!'. (keyword->string foo:) => "foo" -- Scheme Procedure: string->keyword str Return the keyword object whose name is STR. (keyword->string (string->keyword "a b c")) => "a b c"  File: guile.info, Node: Readline Support, Next: Value History, Prev: SRFI Support, Up: Guile Modules 6.5 Readline Support ==================== Guile comes with an interface module to the readline library (*note Top: (readline)Top.). This makes interactive use much more convenient, because of the command-line editing features of readline. Using `(ice-9 readline)', you can navigate through the current input line with the cursor keys, retrieve older command lines from the input history and even search through the history entries. * Menu: * Loading Readline Support:: How to load readline support into Guile. * Readline Options:: How to modify readline's behaviour. * Readline Functions:: Programming with readline.  File: guile.info, Node: Loading Readline Support, Next: Readline Options, Up: Readline Support 6.5.1 Loading Readline Support ------------------------------ The module is not loaded by default and so has to be loaded and activated explicitly. This is done with two simple lines of code: (use-modules (ice-9 readline)) (activate-readline) The first line will load the necessary code, and the second will activate readline's features for the REPL. If you plan to use this module often, you should save these to lines to your `.guile' personal startup file. You will notice that the REPL's behaviour changes a bit when you have loaded the readline module. For example, when you press Enter before typing in the closing parentheses of a list, you will see the "continuation" prompt, three dots: `...' This gives you a nice visual feedback when trying to match parentheses. To make this even easier, "bouncing parentheses" are implemented. That means that when you type in a closing parentheses, the cursor will jump to the corresponding opening parenthesis for a short time, making it trivial to make them match. Once the readline module is activated, all lines entered interactively will be stored in a history and can be recalled later using the cursor-up and -down keys. Readline also understands the Emacs keys for navigating through the command line and history. When you quit your Guile session by evaluating `(quit)' or pressing Ctrl-D, the history will be saved to the file `.guile_history' and read in when you start Guile for the next time. Thus you can start a new Guile session and still have the (probably long-winded) definition expressions available. You can specify a different history file by setting the environment variable `GUILE_HISTORY'. And you can make Guile specific customizations to your `.inputrc' by testing for application `Guile' (*note Conditional Init Constructs: (readline)Conditional Init Constructs.). For instance to define a key inserting a matched pair of parentheses, $if Guile "\C-o": "()\C-b" $endif  File: guile.info, Node: Readline Options, Next: Readline Functions, Prev: Loading Readline Support, Up: Readline Support 6.5.2 Readline Options ---------------------- The readline interface module can be configured in several ways to better suit the user's needs. Configuration is done via the readline module's options interface, in a similar way to the evaluator and debugging options (*note Runtime Options::). Here is the list of readline options generated by typing `(readline-options 'full)' in Guile. You can also see the default values. bounce-parens 500 Time (ms) to show matching opening parenthesis (0 = off). history-length 200 History length. history-file yes Use history file. The history length specifies how many input lines will be remembered. If the history contains that many lines and additional lines are entered, the oldest lines will be lost. You can switch on/off the usage of the history file using the following call. (readline-disable 'history) The readline options interface can only be used _after_ loading the readline module, because it is defined in that module.  File: guile.info, Node: Readline Functions, Prev: Readline Options, Up: Readline Support 6.5.3 Readline Functions ------------------------ The following functions are provided by (use-modules (ice-9 readline)) There are two ways to use readline from Scheme code, either make calls to `readline' directly to get line by line input, or use the readline port below with all the usual reading functions. -- Function: readline [prompt] Read a line of input from the user and return it as a string (without a newline at the end). PROMPT is the prompt to show, or the default is the string set in `set-readline-prompt!' below. (readline "Type something: ") => "hello" -- Function: set-readline-input-port! port -- Function: set-readline-output-port! port Set the input and output port the readline function should read from and write to. PORT must be a file port (*note File Ports::), and should usually be a terminal. The default is the `current-input-port' and `current-output-port' (*note Default Ports::) when `(ice-9 readline)' loads, which in an interactive user session means the Unix "standard input" and "standard output". 6.5.3.1 Readline Port ..................... -- Function: readline-port Return a buffered input port (*note Buffered Input::) which calls the `readline' function above to get input. This port can be used with all the usual reading functions (`read', `read-char', etc), and the user gets the interactive editing features of readline. There's only a single readline port created. `readline-port' creates it when first called, and on subsequent calls just returns what it previously made. -- Function: activate-readline If the `current-input-port' is a terminal (*note `isatty?': Terminals and Ptys.) then enable readline for all reading from `current-input-port' (*note Default Ports::) and enable readline features in the interactive REPL (*note The REPL::). (activate-readline) (read-char) `activate-readline' enables readline on `current-input-port' simply by a `set-current-input-port' to the `readline-port' above. An application can do that directly if the extra REPL features that `activate-readline' adds are not wanted. -- Function: set-readline-prompt! prompt1 [prompt2] Set the prompt string to print when reading input. This is used when reading through `readline-port', and is also the default prompt for the `readline' function above. PROMPT1 is the initial prompt shown. If a user might enter an expression across multiple lines, then PROMPT2 is a different prompt to show further input required. In the Guile REPL for instance this is an ellipsis (`...'). See `set-buffered-input-continuation?!' (*note Buffered Input::) for an application to indicate the boundaries of logical expressions (assuming of course an application has such a notion). 6.5.3.2 Completion .................. -- Function: with-readline-completion-function completer thunk Call `(THUNK)' with COMPLETER as the readline tab completion function to be used in any readline calls within that THUNK. COMPLETER can be `#f' for no completion. COMPLETER will be called as `(COMPLETER text state)', as described in (*note How Completing Works: (readline)How Completing Works.). TEXT is a partial word to be completed, and each COMPLETER call should return a possible completion string or `#f' when no more. STATE is `#f' for the first call asking about a new TEXT then `#t' while getting further completions of that TEXT. Here's an example COMPLETER for user login names from the password file (*note User Information::), much like readline's own `rl_username_completion_function', (define (username-completer-function text state) (if (not state) (setpwent)) ;; new, go to start of database (let more ((pw (getpwent))) (if pw (if (string-prefix? text (passwd:name pw)) (passwd:name pw) ;; this name matches, return it (more (getpwent))) ;; doesn't match, look at next (begin ;; end of database, close it and return #f (endpwent) #f)))) -- Function: apropos-completion-function text state A completion function offering completions for Guile functions and variables (all `define's). This is the default completion function. -- Function: filename-completion-function text state A completion function offering filename completions. This is readline's `rl_filename_completion_function' (*note Completion Functions: (readline)Completion Functions.). -- Function: make-completion-function string-list Return a completion function which offers completions from the possibilities in STRING-LIST. Matching is case-sensitive.  File: guile.info, Node: Value History, Next: Pretty Printing, Prev: Readline Support, Up: Guile Modules 6.6 Value History ================= Another module which makes command line usage more convenient is `(ice-9 history)'. This module will change the REPL so that each value which is evaluated and printed will be remembered under a name constructed from the dollar character (`$') and the number of the evaluated expression. Consider an example session. guile> (use-modules (ice-9 history)) guile> 1 $1 = 1 guile> (+ $1 $1) $2 = 2 guile> (* $2 $2) $3 = 4 After loading the value history module `(ice-9 history)', one (trivial) expression is evaluated. The result is stored into the variable `$1'. This fact is indicated by the output `$1 = ', which is also caused by `(ice-9 history)'. In the next line, this variable is used two times, to produce the value `$2', which in turn is used in the calculation for `$3'.  File: guile.info, Node: Pretty Printing, Next: Formatted Output, Prev: Value History, Up: Guile Modules 6.7 Pretty Printing =================== The module `(ice-9 pretty-print)' provides the procedure `pretty-print', which provides nicely formatted output of Scheme objects. This is especially useful for deeply nested or complex data structures, such as lists and vectors. The module is loaded by simply saying. (use-modules (ice-9 pretty-print)) This makes the procedure `pretty-print' available. As an example how `pretty-print' will format the output, see the following: (pretty-print '(define (foo) (lambda (x) (cond ((zero? x) #t) ((negative? x) -x) (else (if (= x 1) 2 (* x x x))))))) -| (define (foo) (lambda (x) (cond ((zero? x) #t) ((negative? x) -x) (else (if (= x 1) 2 (* x x x)))))) -- Scheme Procedure: pretty-print obj [port] [keyword-options] Print the textual representation of the Scheme object OBJ to PORT. PORT defaults to the current output port, if not given. The further KEYWORD-OPTIONS are keywords and parameters as follows, #:display? FLAG If FLAG is true then print using `display'. The default is `#f' which means use `write' style. (*note Writing::) #:per-line-prefix STRING Print the given STRING as a prefix on each line. The default is no prefix. #:width COLUMNS Print within the given COLUMNS. The default is 79.  File: guile.info, Node: Formatted Output, Next: File Tree Walk, Prev: Pretty Printing, Up: Guile Modules 6.8 Formatted Output ==================== The `format' function is a powerful way to print numbers, strings and other objects together with literal text under the control of a format string. This function is available from (use-modules (ice-9 format)) A format string is generally more compact and easier than using just the standard procedures like `display', `write' and `newline'. Parameters in the output string allow various output styles, and parameters can be taken from the arguments for runtime flexibility. `format' is similar to the Common Lisp procedure of the same name, but it's not identical and doesn't have quite all the features found in Common Lisp. C programmers will note the similarity between `format' and `printf', though escape sequences are marked with ~ instead of %, and are more powerful. -- Scheme Procedure: format dest fmt [args...] Write output specified by the FMT string to DEST. DEST can be an output port, `#t' for `current-output-port' (*note Default Ports::), a number for `current-error-port', or `#f' to return the output as a string. FMT can contain literal text to be output, and ~ escapes. Each escape has the form ~ [param [, param...] [:] [@] code code is a character determining the escape sequence. The : and @ characters are optional modifiers, one or both of which change the way various codes operate. Optional parameters are accepted by some codes too. Parameters have the following forms, [+/-]number An integer, with optional + or -. ' (apostrophe) The following character in the format string, for instance 'z for z. v The next function argument as the parameter. v stands for "variable", a parameter can be calculated at runtime and included in the arguments. Upper case V can be used too. # The number of arguments remaining. (See ~* below for some usages.) Parameters are separated by commas (,). A parameter can be left empty to keep its default value when supplying later parameters. The following escapes are available. The code letters are not case-sensitive, upper and lower case are the same. ~a ~s Object output. Parameters: MINWIDTH, PADINC, MINPAD, PADCHAR. ~a outputs an argument like `display', ~s outputs an argument like `write' (*note Writing::). (format #t "~a" "foo") -| foo (format #t "~s" "foo") -| "foo" ~:a and ~:s put objects that don't have an external representation in quotes like a string. (format #t "~:a" car) -| "#" If the output is less than MINWIDTH characters (default 0), it's padded on the right with PADCHAR (default space). ~@a and ~@s put the padding on the left instead. (format #f "~5a" 'abc) => "abc " (format #f "~5,,,'-@a" 'abc) => "--abc" MINPAD is a minimum for the padding then plus a multiple of PADINC. Ie. the padding is MINPAD + N * PADINC, where N is the smallest integer making the total object plus padding greater than or equal to MINWIDTH. The default MINPAD is 0 and the default PADINC is 1 (imposing no minimum or multiple). (format #f "~5,1,4a" 'abc) => "abc " ~c Character. Parameter: CHARNUM. Output a character. The default is to simply output, as per `write-char' (*note Writing::). ~@c prints in `write' style. ~:c prints control characters (ASCII 0 to 31) in ^X form. (format #t "~c" #\z) -| z (format #t "~@c" #\z) -| #\z (format #t "~:c" #\newline) -| ^J If the CHARNUM parameter is given then an argument is not taken but instead the character is `(integer->char CHARNUM)' (*note Characters::). This can be used for instance to output characters given by their ASCII code. (format #t "~65c") -| A ~d ~x ~o ~b Integer. Parameters: MINWIDTH, PADCHAR, COMMACHAR, COMMAWIDTH. Output an integer argument as a decimal, hexadecimal, octal or binary integer (respectively). (format #t "~d" 123) -| 123 ~@d etc shows a + sign is shown on positive numbers. (format #t "~@b" 12) -| +1100 If the output is less than the MINWIDTH parameter (default no minimum), it's padded on the left with the PADCHAR parameter (default space). (format #t "~5,'*d" 12) -| ***12 (format #t "~5,'0d" 12) -| 00012 (format #t "~3d" 1234) -| 1234 ~:d adds commas (or the COMMACHAR parameter) every three digits (or the COMMAWIDTH parameter many). (format #t "~:d" 1234567) -| 1,234,567 (format #t "~10,'*,'/,2:d" 12345) -| ***1/23/45 Hexadecimal ~x output is in lower case, but the ~( and ~) case conversion directives described below can be used to get upper case. (format #t "~x" 65261) -| feed (format #t "~:@(~x~)" 65261) -| FEED ~r Integer in words, roman numerals, or a specified radix. Parameters: RADIX, MINWIDTH, PADCHAR, COMMACHAR, COMMAWIDTH. With no parameters output is in words as a cardinal like "ten", or ~:r prints an ordinal like "tenth". (format #t "~r" 9) -| nine ;; cardinal (format #t "~r" -9) -| minus nine ;; cardinal (format #t "~:r" 9) -| ninth ;; ordinal And also with no parameters, ~@r gives roman numerals and ~:@r gives old roman numerals. In old roman numerals there's no "subtraction", so 9 is VIIII instead of IX. In both cases only positive numbers can be output. (format #t "~@r" 89) -| LXXXIX ;; roman (format #t "~:@r" 89) -| LXXXVIIII ;; old roman When a parameter is given it means numeric output in the specified RADIX. The modifiers and parameters following the radix are the same as described for ~d etc above. (format #f "~3r" 27) => "1000" ;; base 3 (format #f "~3,5r" 26) => " 222" ;; base 3 width 5 ~f Fixed-point float. Parameters: WIDTH, DECIMALS, SCALE, OVERFLOWCHAR, PADCHAR. Output a number or number string in fixed-point format, ie. with a decimal point. (format #t "~f" 5) -| 5.0 (format #t "~f" "123") -| 123.0 (format #t "~f" "1e-1") -| 0.1 ~@f prints a + sign on positive numbers (including zero). (format #t "~@f" 0) -| +0.0 If the output is less than WIDTH characters it's padded on the left with PADCHAR (space by default). If the output equals or exceeds WIDTH then there's no padding. The default for WIDTH is no padding. (format #f "~6f" -1.5) => " -1.5" (format #f "~6,,,,'*f" 23) => "**23.0" (format #f "~6f" 1234567.0) => "1234567.0" DECIMALS is how many digits to print after the decimal point, with the value rounded or padded with zeros as necessary. (The default is to output as many decimals as required.) (format #t "~1,2f" 3.125) -| 3.13 (format #t "~1,2f" 1.5) -| 1.50 SCALE is a power of 10 applied to the value, moving the decimal point that many places. A positive SCALE increases the value shown, a negative decreases it. (format #t "~,,2f" 1234) -| 123400.0 (format #t "~,,-2f" 1234) -| 12.34 If OVERFLOWCHAR and WIDTH are both given and if the output would exceed WIDTH, then that many OVERFLOWCHARs are printed instead of the value. (format #t "~5,,,'xf" 12345) -| 12345 (format #t "~4,,,'xf" 12345) -| xxxx ~e Exponential float. Parameters: WIDTH, MANTDIGITS, EXPDIGITS, INTDIGITS, OVERFLOWCHAR, PADCHAR, EXPCHAR. Output a number or number string in exponential notation. (format #t "~e" 5000.25) -| 5.00025E+3 (format #t "~e" "123.4") -| 1.234E+2 (format #t "~e" "1e4") -| 1.0E+4 ~@e prints a + sign on positive numbers (including zero). (This is for the mantissa, a + or - sign is always shown on the exponent.) (format #t "~@e" 5000.0) -| +5.0E+3 If the output is less than WIDTH characters it's padded on the left with PADCHAR (space by default). The default for WIDTH is to output with no padding. (format #f "~10e" 1234.0) => " 1.234E+3" (format #f "~10,,,,,'*e" 0.5) => "****5.0E-1" MANTDIGITS is the number of digits shown in the mantissa after the decimal point. The value is rounded or trailing zeros are added as necessary. The default MANTDIGITS is to show as much as needed by the value. (format #f "~,3e" 11111.0) => "1.111E+4" (format #f "~,8e" 123.0) => "1.23000000E+2" EXPDIGITS is the minimum number of digits shown for the exponent, with leading zeros added if necessary. The default for EXPDIGITS is to show only as many digits as required. At least 1 digit is always shown. (format #f "~,,1e" 1.0e99) => "1.0E+99" (format #f "~,,6e" 1.0e99) => "1.0E+000099" INTDIGITS (default 1) is the number of digits to show before the decimal point in the mantissa. INTDIGITS can be zero, in which case the integer part is a single 0, or it can be negative, in which case leading zeros are shown after the decimal point. (format #t "~,,,3e" 12345.0) -| 123.45E+2 (format #t "~,,,0e" 12345.0) -| 0.12345E+5 (format #t "~,,,-3e" 12345.0) -| 0.00012345E+8 If OVERFLOWCHAR is given then WIDTH is a hard limit. If the output would exceed WIDTH then instead that many OVERFLOWCHARs are printed. (format #f "~6,,,,'xe" 100.0) => "1.0E+2" (format #f "~3,,,,'xe" 100.0) => "xxx" EXPCHAR is the exponent marker character (default E). (format #t "~,,,,,,'ee" 100.0) -| 1.0e+2 ~g General float. Parameters: WIDTH, MANTDIGITS, EXPDIGITS, INTDIGITS, OVERFLOWCHAR, PADCHAR, EXPCHAR. Output a number or number string in either exponential format the same as ~e, or fixed-point format like ~f but aligned where the mantissa would have been and followed by padding where the exponent would have been. Fixed-point is used when the absolute value is 0.1 or more and it takes no more space than the mantissa in exponential format, ie. basically up to MANTDIGITS digits. (format #f "~12,4,2g" 999.0) => " 999.0 " (format #f "~12,4,2g" "100000") => " 1.0000E+05" The parameters are interpreted as per ~e above. When fixed-point is used, the DECIMALS parameter to ~f is established from MANTDIGITS, so as to give a total MANTDIGITS+1 figures. ~$ Monetary style fixed-point float. Parameters: DECIMALS, INTDIGITS, WIDTH, PADCHAR. Output a number or number string in fixed-point format, ie. with a decimal point. DECIMALS is the number of decimal places to show, default 2. (format #t "~$" 5) -| 5.00 (format #t "~4$" "2.25") -| 2.2500 (format #t "~4$" "1e-2") -| 0.0100 ~@$ prints a + sign on positive numbers (including zero). (format #t "~@$" 0) -| +0.00 INTDIGITS is a minimum number of digits to show in the integer part of the value (default 1). (format #t "~,3$" 9.5) -| 009.50 (format #t "~,0$" 0.125) -| .13 If the output is less than WIDTH characters (default 0), it's padded on the left with PADCHAR (default space). ~:$ puts the padding after the sign. (format #f "~,,8$" -1.5) => " -1.50" (format #f "~,,8:$" -1.5) => "- 1.50" (format #f "~,,8,'.:@$" 3) => "+...3.00" Note that floating point for dollar amounts is generally not a good idea, because a cent 0.01 cannot be represented exactly in the binary floating point Guile uses, which leads to slowly accumulating rounding errors. Keeping values as cents (or fractions of a cent) in integers then printing with the scale option in ~f may be a better approach. ~i Complex fixed-point float. Parameters: WIDTH, DECIMALS, SCALE, OVERFLOWCHAR, PADCHAR. Output the argument as a complex number, with both real and imaginary part shown (even if one or both are zero). The parameters and modifiers are the same as for fixed-point ~f described above. The real and imaginary parts are both output with the same given parameters and modifiers, except that for the imaginary part the @ modifier is always enabled, so as to print a + sign between the real and imaginary parts. (format #t "~i" 1) -| 1.0+0.0i ~p Plural. No parameters. Output nothing if the argument is 1, or `s' for any other value. (format #t "enter name~p" 1) -| enter name (format #t "enter name~p" 2) -| enter names ~@p prints `y' for 1 or `ies' otherwise. (format #t "pupp~@p" 1) -| puppy (format #t "pupp~@p" 2) -| puppies ~:p re-uses the preceding argument instead of taking a new one, which can be convenient when printing some sort of count. (format #t "~d cat~:p" 9) -| 9 cats (format #t "~d pupp~:@p" 5) -| 5 puppies ~p is designed for English plurals and there's no attempt to support other languages. ~[ conditionals (below) may be able to help. When using `gettext' to translate messages `ngettext' is probably best though (*note Internationalization::). ~y Pretty print. No parameters. Output an argument with `pretty-print' (*note Pretty Printing::). ~? ~k Sub-format. No parameters. Take a format string argument and a second argument which is a list of arguments for that string, and output the result. (format #t "~?" "~d ~d" '(1 2)) -| 1 2 ~@? takes arguments for the sub-format directly rather than in a list. (format #t "~@? ~s" "~d ~d" 1 2 "foo") -| 1 2 "foo" ~? and ~k are the same, ~k is provided for T-Scheme compatibility. ~* Argument jumping. Parameter: N. Move forward N arguments (default 1) in the argument list. ~:* moves backwards. (N cannot be negative.) (format #f "~d ~2*~d" 1 2 3 4) => "1 4" (format #f "~d ~:*~d" 6) => "6 6" ~@* moves to argument number N. The first argument is number 0 (and that's the default for N). (format #f "~d~d again ~@*~d~d" 1 2) => "12 again 12" (format #f "~d~d~d ~1@*~d~d" 1 2 3) => "123 23" A # move to the end followed by a : modifier move back can be used for an absolute position relative to the end of the argument list, a reverse of what the @ modifier does. (format #t "~#*~2:*~a" 'a 'b 'c 'd) -| c At the end of the format string the current argument postion doesn't matter, any further arguments are ignored. ~t Advance to a column position. Parameters: COLNUM, COLINC, PADCHAR. Output PADCHAR (space by default) to move to the given COLNUM column. The start of the line is column 0, the default for COLNUM is 1. (format #f "~tX") => " X" (format #f "~3tX") => " X" If the current column is already past COLNUM, then the move is to there plus a multiple of COLINC, ie. column COLNUM + N * COLINC for the smallest N which makes that value greater than or equal to the current column. The default COLINC is 1 (which means no further move). (format #f "abcd~2,5,'.tx") => "abcd...x" ~@t takes COLNUM as an offset from the current column. COLNUM many pad characters are output, then further padding to make the current column a multiple of COLINC, if it isn't already so. (format #f "a~3,5'*@tx") => "a****x" ~t is implemented using `port-column' (*note Reading::), so it works even there has been other output before `format'. ~~ Tilde character. Parameter: N. Output a tilde character ~, or N many if a parameter is given. Normally ~ introduces an escape sequence, ~~ is the way to output a literal tilde. ~% Newline. Parameter: N. Output a newline character, or N many if a parameter is given. A newline (or a few newlines) can of course be output just by including them in the format string. ~& Start a new line. Parameter: N. Output a newline if not already at the start of a line. With a parameter, output that many newlines, but with the first only if not already at the start of a line. So for instance 3 would be a newline if not already at the start of a line, and 2 further newlines. ~_ Space character. Parameter: N. Output a space character, or N many if a parameter is given. With a variable parameter this is one way to insert runtime calculated padding (~t or the various field widths can do similar things). (format #f "~v_foo" 4) => " foo" ~/ Tab character. Parameter: N. Output a tab character, or N many if a parameter is given. ~| Formfeed character. Parameter: N. Output a formfeed character, or N many if a parameter is given. ~! Force output. No parameters. At the end of output, call `force-output' to flush any buffers on the destination (*note Writing::). ~! can occur anywhere in the format string, but the force is done at the end of output. When output is to a string (destination `#f'), ~! does nothing. ~newline (ie. newline character) Continuation line. No parameters. Skip this newline and any following whitespace in the format string, ie. don't send it to the output. This can be used to break up a long format string for readability, but not print the extra whitespace. (format #f "abc~ ~d def~ ~d" 1 2) => "abc1 def2" ~:newline skips the newline but leaves any further whitespace to be printed normally. ~@newline prints the newline then skips following whitespace. ~( ~) Case conversion. No parameters. Between ~( and ~) the case of all output is changed. The modifiers on ~( control the conversion. ~( -- lower case. ~:@( -- upper case. For example, (format #t "~(Hello~)") -| hello (format #t "~:@(Hello~)") -| HELLO In the future it's intended the modifiers : and @ alone will capitalize the first letters of words, as per Common Lisp `format', but the current implementation of this is flawed and not recommended for use. Case conversions do not nest, currently. This might change in the future, but if it does then it will be to Common Lisp style where the outermost conversion has priority, overriding inner ones (making those fairly pointless). ~{ ~} Iteration. Parameter: MAXREPS (for ~{). The format between ~{ and ~} is iterated. The modifiers to ~{ determine how arguments are taken. The default is a list argument with each iteration successively consuming elements from it. This is a convenient way to output a whole list. (format #t "~{~d~}" '(1 2 3)) -| 123 (format #t "~{~s=~d ~}" '("x" 1 "y" 2)) -| "x"=1 "y"=2 ~:{ takes a single argument which is a list of lists, each of those contained lists gives the arguments for the iterated format. (format #t "~:{~dx~d ~}" '((1 2) (3 4) (5 6))) -| 1x2 3x4 5x6 ~@{ takes arguments directly, with each iteration successively consuming arguments. (format #t "~@{~d~}" 1 2 3) -| 123 (format #t "~@{~s=~d ~}" "x" 1 "y" 2) -| "x"=1 "y"=2 ~:@{ takes list arguments, one argument for each iteration, using that list for the format. (format #t "~:@{~dx~d ~}" '(1 2) '(3 4) '(5 6)) -| 1x2 3x4 5x6 Iterating stops when there are no more arguments or when the MAXREPS parameter to ~{ is reached (default no maximum). (format #t "~2{~d~}" '(1 2 3 4)) -| 12 If the format between ~{ and ~} is empty, then a format string argument is taken (before iteration argument(s)) and used instead. This allows a sub-format (like ~? above) to be iterated. (format #t "~{~}" "~d" '(1 2 3)) -| 123 Iterations can be nested, an inner iteration operates in the same way as described, but of course on the arguments the outer iteration provides it. This can be used to work into nested list structures. For example in the following the inner ~{~d~}x is applied to `(1 2)' then `(3 4 5)' etc. (format #t "~{~{~d~}x~}" '((1 2) (3 4 5))) -| 12x345x See also ~^ below for escaping from iteration. ~[ ~; ~] Conditional. Parameter: SELECTOR. A conditional block is delimited by ~[ and ~], and ~; separates clauses within the block. ~[ takes an integer argument and that number clause is used. The first clause is number 0. (format #f "~[peach~;banana~;mango~]" 1) => "banana" The SELECTOR parameter can be used for the clause number, instead of taking an argument. (format #f "~2[peach~;banana~;mango~]") => "mango" If the clause number is out of range then nothing is output. Or the last clause can be ~:; to use that for a number out of range. (format #f "~[banana~;mango~]" 99) => "" (format #f "~[banana~;mango~:;fruit~]" 99) => "fruit" ~:[ treats the argument as a flag, and expects two clauses. The first is used if the argument is `#f' or the second otherwise. (format #f "~:[false~;not false~]" #f) => "false" (format #f "~:[false~;not false~]" 'abc) => "not false" (let ((n 3)) (format #t "~d gnu~:[s are~; is~] here" n (= 1 n))) -| 3 gnus are here ~@[ also treats the argument as a flag, and expects one clause. If the argument is `#f' then no output is produced and the argument is consumed, otherwise the clause is used and the argument is not consumed, it's left for the clause. This can be used for instance to suppress output if `#f' means something not available. (format #f "~@[temperature=~d~]" 27) => "temperature=27" (format #f "~@[temperature=~d~]" #f) => "" ~^ Escape. Parameters: VAL1, VAL2, VAL3. Stop formatting if there are no more arguments. This can be used for instance to have a format string adapt to a variable number of arguments. (format #t "~d~^ ~d" 1) -| 1 (format #t "~d~^ ~d" 1 2) -| 1 2 Within a ~{ ~} iteration, ~^ stops the current iteration step if there are no more arguments to that step, but continuing with possible further steps and the rest of the format. This can be used for instance to avoid a separator on the last iteration, or to adapt to variable length argument lists. (format #f "~{~d~^/~} go" '(1 2 3)) => "1/2/3 go" (format #f "~:{ ~d~^~d~} go" '((1) (2 3))) => " 1 23 go" Within a ~? sub-format, ~^ operates just on that sub-format. If it terminates the sub-format then the originating format will still continue. (format #t "~? items" "~d~^ ~d" '(1)) -| 1 items (format #t "~? items" "~d~^ ~d" '(1 2)) -| 1 2 items The parameters to ~^ (which are numbers) change the condition used to terminate. For a single parameter, termination is when that value is zero (notice this makes plain ~^ equivalent to ~#^). For two parameters, termination is when those two are equal. For three parameters, termination is when VAL1 <= VAL2 and VAL2 <= VAL3. ~q Inquiry message. Insert a copyright message into the output. ~:q inserts the format implementation version. It's an error if there are not enough arguments for the escapes in the format string, but any excess arguments are ignored. Iterations ~{ ~} and conditionals ~[ ~; ~] can be nested, but must be properly nested, meaning the inner form must be entirely within the outer form. So it's not possible, for instance, to try to conditionalize the endpoint of an iteration. (format #t "~{ ~[ ... ~] ~}" ...) ;; good (format #t "~{ ~[ ... ~} ... ~]" ...) ;; bad The same applies to case conversions ~( ~), they must properly nest with respect to iterations and conditionals (though currently a case conversion cannot nest within another case conversion). When a sub-format (~?) is used, that sub-format string must be self-contained. It cannot for instance give a ~{ to begin an iteration form and have the ~} up in the originating format, or similar. Guile contains a `format' procedure even when the module `(ice-9 format)' is not loaded. The default `format' is `simple-format' (*note Writing::), it doesn't support all escape sequences documented in this section, and will signal an error if you try to use one of them. The reason for two versions is that the full `format' is fairly large and requires some time to load. `simple-format' is often adequate too.  File: guile.info, Node: File Tree Walk, Next: Queues, Prev: Formatted Output, Up: Guile Modules 6.9 File Tree Walk ================== The functions in this section traverse a tree of files and directories, in a fashion similar to the C `ftw' and `nftw' routines (*note Working with Directory Trees: (libc)Working with Directory Trees.). (use-modules (ice-9 ftw)) -- Function: ftw startname proc ['hash-size n] Walk the filesystem tree descending from STARTNAME, calling PROC for each file and directory. Hard links and symbolic links are followed. A file or directory is reported to PROC only once, and skipped if seen again in another place. One consequence of this is that `ftw' is safe against circularly linked directory structures. Each PROC call is `(PROC filename statinfo flag)' and it should return `#t' to continue, or any other value to stop. FILENAME is the item visited, being STARTNAME plus a further path and the name of the item. STATINFO is the return from `stat' (*note File System::) on FILENAME. FLAG is one of the following symbols, `regular' FILENAME is a file, this includes special files like devices, named pipes, etc. `directory' FILENAME is a directory. `invalid-stat' An error occurred when calling `stat', so nothing is known. STATINFO is `#f' in this case. `directory-not-readable' FILENAME is a directory, but one which cannot be read and hence won't be recursed into. `symlink' FILENAME is a dangling symbolic link. Symbolic links are normally followed and their target reported, the link itself is reported if the target does not exist. The return value from `ftw' is `#t' if it ran to completion, or otherwise the non-`#t' value from PROC which caused the stop. Optional argument symbol `hash-size' and an integer can be given to set the size of the hash table used to track items already visited. (*note Hash Table Reference::) In the current implementation, returning non-`#t' from PROC is the only valid way to terminate `ftw'. PROC must not use `throw' or similar to escape. -- Function: nftw startname proc ['chdir] ['depth] ['hash-size n] ['mount] ['physical] Walk the filesystem tree starting at STARTNAME, calling PROC for each file and directory. `nftw' has extra features over the basic `ftw' described above. Like `ftw', hard links and symbolic links are followed. A file or directory is reported to PROC only once, and skipped if seen again in another place. One consequence of this is that `nftw' is safe against circular linked directory structures. Each PROC call is `(PROC filename statinfo flag base level)' and it should return `#t' to continue, or any other value to stop. FILENAME is the item visited, being STARTNAME plus a further path and the name of the item. STATINFO is the return from `stat' on FILENAME (*note File System::). BASE is an integer offset into FILENAME which is where the basename for this item begins. LEVEL is an integer giving the directory nesting level, starting from 0 for the contents of STARTNAME (or that item itself if it's a file). FLAG is one of the following symbols, `regular' FILENAME is a file, including special files like devices, named pipes, etc. `directory' FILENAME is a directory. `directory-processed' FILENAME is a directory, and its contents have all been visited. This flag is given instead of `directory' when the `depth' option below is used. `invalid-stat' An error occurred when applying `stat' to FILENAME, so nothing is known about it. STATINFO is `#f' in this case. `directory-not-readable' FILENAME is a directory, but one which cannot be read and hence won't be recursed into. `stale-symlink' FILENAME is a dangling symbolic link. Links are normally followed and their target reported, the link itself is reported if its target does not exist. `symlink' When the `physical' option described below is used, this indicates FILENAME is a symbolic link whose target exists (and is not being followed). The following optional arguments can be given to modify the way `nftw' works. Each is passed as a symbol (and `hash-size' takes a following integer value). `chdir' Change to the directory containing the item before calling PROC. When `nftw' returns the original current directory is restored. Under this option, generally the BASE parameter to each PROC call should be used to pick out the base part of the FILENAME. The FILENAME is still a path but with a changed directory it won't be valid (unless the STARTNAME directory was absolute). `depth' Visit files "depth first", meaning PROC is called for the contents of each directory before it's called for the directory itself. Normally a directory is reported first, then its contents. Under this option, the FLAG to PROC for a directory is `directory-processed' instead of `directory'. `hash-size N' Set the size of the hash table used to track items already visited. (*note Hash Table Reference::) `mount' Don't cross a mount point, meaning only visit items on the same filesystem as STARTNAME (ie. the same `stat:dev'). `physical' Don't follow symbolic links, instead report them to PROC as `symlink'. Dangling links (those whose target doesn't exist) are still reported as `stale-symlink'. The return value from `nftw' is `#t' if it ran to completion, or otherwise the non-`#t' value from PROC which caused the stop. In the current implementation, returning non-`#t' from PROC is the only valid way to terminate `ftw'. PROC must not use `throw' or similar to escape.  File: guile.info, Node: Queues, Next: Streams, Prev: File Tree Walk, Up: Guile Modules 6.10 Queues =========== The functions in this section are provided by (use-modules (ice-9 q)) This module implements queues holding arbitrary scheme objects and designed for efficient first-in / first-out operations. `make-q' creates a queue, and objects are entered and removed with `enq!' and `deq!'. `q-push!' and `q-pop!' can be used too, treating the front of the queue like a stack. -- Scheme Procedure: make-q Return a new queue. -- Scheme Procedure: q? obj Return `#t' if OBJ is a queue, or `#f' if not. Note that queues are not a distinct class of objects but are implemented with cons cells. For that reason certain list structures can get `#t' from `q?'. -- Scheme Procedure: enq! q obj Add OBJ to the rear of Q, and return Q. -- Scheme Procedure: deq! q -- Scheme Procedure: q-pop! q Remove and return the front element from Q. If Q is empty, a `q-empty' exception is thrown. `deq!' and `q-pop!' are the same operation, the two names just let an application match `enq!' with `deq!', or `q-push!' with `q-pop!'. -- Scheme Procedure: q-push! q obj Add OBJ to the front of Q, and return Q. -- Scheme Procedure: q-length q Return the number of elements in Q. -- Scheme Procedure: q-empty? q Return true if Q is empty. -- Scheme Procedure: q-empty-check q Throw a `q-empty' exception if Q is empty. -- Scheme Procedure: q-front q Return the first element of Q (without removing it). If Q is empty, a `q-empty' exception is thrown. -- Scheme Procedure: q-rear q Return the last element of Q (without removing it). If Q is empty, a `q-empty' exception is thrown. -- Scheme Procedure: q-remove! q obj Remove all occurences of OBJ from Q, and return Q. OBJ is compared to queue elements using `eq?'. The `q-empty' exceptions described above are thrown just as `(throw 'q-empty)', there's no message etc like an error throw. A queue is implemented as a cons cell, the `car' containing a list of queued elements, and the `cdr' being the last cell in that list (for ease of enqueuing). (LIST . LAST-CELL) If the queue is empty, LIST is the empty list and LAST-CELL is `#f'. An application can directly access the queue list if desired, for instance to search the elements or to insert at a specific point. -- Scheme Procedure: sync-q! q Recompute the LAST-CELL field in Q. All the operations above maintain LAST-CELL as described, so normally there's no need for `sync-q!'. But if an application modifies the queue LIST then it must either maintain LAST-CELL similarly, or call `sync-q!' to recompute it.  File: guile.info, Node: Streams, Next: Buffered Input, Prev: Queues, Up: Guile Modules 6.11 Streams ============ A stream represents a sequence of values, each of which is calculated only when required. This allows large or even infinite sequences to be represented and manipulated with familiar operations like "car", "cdr", "map" or "fold". In such manipulations only as much as needed is actually held in memory at any one time. The functions in this section are available from (use-modules (ice-9 streams)) Streams are implemented using promises (*note Delayed Evaluation::), which is how the underlying calculation of values is made only when needed, and the values then retained so the calculation is not repeated. Here is a simple example producing a stream of all odd numbers, (define odds (make-stream (lambda (state) (cons state (+ state 2))) 1)) (stream-car odds) => 1 (stream-car (stream-cdr odds)) => 3 `stream-map' could be used to derive a stream of odd squares, (define (square n) (* n n)) (define oddsquares (stream-map square odds)) These are infinite sequences, so it's not possible to convert them to a list, but they could be printed (infinitely) with for example (stream-for-each (lambda (n sq) (format #t "~a squared is ~a\n" n sq)) odds oddsquares) -| 1 squared is 1 3 squared is 9 5 squared is 25 7 squared is 49 ... -- Function: make-stream proc initial-state Return a new stream, formed by calling PROC successively. Each call is `(PROC STATE)', it should return a pair, the `car' being the value for the stream, and the `cdr' being the new STATE for the next call. For the first call STATE is the given INITIAL-STATE. At the end of the stream, PROC should return some non-pair object. -- Function: stream-car stream Return the first element from STREAM. STREAM must not be empty. -- Function: stream-cdr stream Return a stream which is the second and subsequent elements of STREAM. STREAM must not be empty. -- Function: stream-null? stream Return true if STREAM is empty. -- Function: list->stream list -- Function: vector->stream vector Return a stream with the contents of LIST or VECTOR. LIST or VECTOR should not be modified subsequently, since it's unspecified whether changes there will be reflected in the stream returned. -- Function: port->stream port readproc Return a stream which is the values obtained by reading from PORT using READPROC. Each read call is `(READPROC PORT)', and it should return an EOF object (*note Reading::) at the end of input. For example a stream of characters from a file, (port->stream (open-input-file "/foo/bar.txt") read-char) -- Function: stream->list stream Return a list which is the entire contents of STREAM. -- Function: stream->reversed-list stream Return a list which is the entire contents of STREAM, but in reverse order. -- Function: stream->list&length stream Return two values (*note Multiple Values::), being firstly a list which is the entire contents of STREAM, and secondly the number of elements in that list. -- Function: stream->reversed-list&length stream Return two values (*note Multiple Values::) being firstly a list which is the entire contents of STREAM, but in reverse order, and secondly the number of elements in that list. -- Function: stream->vector stream Return a vector which is the entire contents of STREAM. -- Function: stream-fold proc init stream0 ... streamN Apply PROC successively over the elements of the given streams, from first to last until the end of the shortest stream is reached. Return the result from the last PROC call. Each call is `(PROC elem0 ... elemN prev)', where each ELEM is from the corresponding STREAM. PREV is the return from the previous PROC call, or the given INIT for the first call. -- Function: stream-for-each proc stream0 ... streamN Call PROC on the elements from the given STREAMs. The return value is unspecified. Each call is `(PROC elem0 ... elemN)', where each ELEM is from the corresponding STREAM. `stream-for-each' stops when it reaches the end of the shortest STREAM. -- Function: stream-map proc stream0 ... streamN Return a new stream which is the results of applying PROC to the elements of the given STREAMs. Each call is `(PROC elem0 ... elemN)', where each ELEM is from the corresponding STREAM. The new stream ends when the end of the shortest given STREAM is reached.  File: guile.info, Node: Buffered Input, Next: Expect, Prev: Streams, Up: Guile Modules 6.12 Buffered Input =================== The following functions are provided by (use-modules (ice-9 buffered-input)) A buffered input port allows a reader function to return chunks of characters which are to be handed out on reading the port. A notion of further input for an application level logical expression is maintained too, and passed through to the reader. -- Function: make-buffered-input-port reader Create an input port which returns characters obtained from the given READER function. READER is called (READER cont), and should return a string or an EOF object. The new port gives precisely the characters returned by READER, nothing is added, so if any newline characters or other separators are desired they must come from the reader function. The CONT parameter to READER is `#f' for initial input, or `#t' when continuing an expression. This is an application level notion, set with `set-buffered-input-continuation?!' below. If the user has entered a partial expression then it allows READER for instance to give a different prompt to show more is required. -- Function: make-line-buffered-input-port reader Create an input port which returns characters obtained from the specified READER function, similar to `make-buffered-input-port' above, but where READER is expected to be a line-oriented. READER is called (READER cont), and should return a string or an EOF object as above. Each string is a line of input without a newline character, the port code inserts a newline after each string. -- Function: set-buffered-input-continuation?! port cont Set the input continuation flag for a given buffered input PORT. An application uses this by calling with a CONT flag of `#f' when beginning to read a new logical expression. For example with the Scheme `read' function (*note Scheme Read::), (define my-port (make-buffered-input-port my-reader)) (set-buffered-input-continuation?! my-port #f) (let ((obj (read my-port))) ...  File: guile.info, Node: Expect, Next: The Scheme shell (scsh), Prev: Buffered Input, Up: Guile Modules 6.13 Expect =========== The macros in this section are made available with: (use-modules (ice-9 expect)) `expect' is a macro for selecting actions based on the output from a port. The name comes from a tool of similar functionality by Don Libes. Actions can be taken when a particular string is matched, when a timeout occurs, or when end-of-file is seen on the port. The `expect' macro is described below; `expect-strings' is a front-end to `expect' based on regexec (see the regular expression documentation). -- Macro: expect-strings clause ... By default, `expect-strings' will read from the current input port. The first term in each clause consists of an expression evaluating to a string pattern (regular expression). As characters are read one-by-one from the port, they are accumulated in a buffer string which is matched against each of the patterns. When a pattern matches, the remaining expression(s) in the clause are evaluated and the value of the last is returned. For example: (with-input-from-file "/etc/passwd" (lambda () (expect-strings ("^nobody" (display "Got a nobody user.\n") (display "That's no problem.\n")) ("^daemon" (display "Got a daemon user.\n"))))) The regular expression is compiled with the `REG_NEWLINE' flag, so that the ^ and $ anchors will match at any newline, not just at the start and end of the string. There are two other ways to write a clause: The expression(s) to evaluate can be omitted, in which case the result of the regular expression match (converted to strings, as obtained from regexec with match-pick set to "") will be returned if the pattern matches. The symbol `=>' can be used to indicate that the expression is a procedure which will accept the result of a successful regular expression match. E.g., ("^daemon" => write) ("^d(aemon)" => (lambda args (for-each write args))) ("^da(em)on" => (lambda (all sub) (write all) (newline) (write sub) (newline))) The order of the substrings corresponds to the order in which the opening brackets occur. A number of variables can be used to control the behaviour of `expect' (and `expect-strings'). Most have default top-level bindings to the value `#f', which produces the default behaviour. They can be redefined at the top level or locally bound in a form enclosing the expect expression. `expect-port' A port to read characters from, instead of the current input port. `expect-timeout' `expect' will terminate after this number of seconds, returning `#f' or the value returned by expect-timeout-proc. `expect-timeout-proc' A procedure called if timeout occurs. The procedure takes a single argument: the accumulated string. `expect-eof-proc' A procedure called if end-of-file is detected on the input port. The procedure takes a single argument: the accumulated string. `expect-char-proc' A procedure to be called every time a character is read from the port. The procedure takes a single argument: the character which was read. `expect-strings-compile-flags' Flags to be used when compiling a regular expression, which are passed to `make-regexp' *Note Regexp Functions::. The default value is `regexp/newline'. `expect-strings-exec-flags' Flags to be used when executing a regular expression, which are passed to regexp-exec *Note Regexp Functions::. The default value is `regexp/noteol', which prevents `$' from matching the end of the string while it is still accumulating, but still allows it to match after a line break or at the end of file. Here's an example using all of the variables: (let ((expect-port (open-input-file "/etc/passwd")) (expect-timeout 1) (expect-timeout-proc (lambda (s) (display "Times up!\n"))) (expect-eof-proc (lambda (s) (display "Reached the end of the file!\n"))) (expect-char-proc display) (expect-strings-compile-flags (logior regexp/newline regexp/icase)) (expect-strings-exec-flags 0)) (expect-strings ("^nobody" (display "Got a nobody user\n")))) -- Macro: expect clause ... `expect' is used in the same way as `expect-strings', but tests are specified not as patterns, but as procedures. The procedures are called in turn after each character is read from the port, with two arguments: the value of the accumulated string and a flag to indicate whether end-of-file has been reached. The flag will usually be `#f', but if end-of-file is reached, the procedures are called an additional time with the final accumulated string and `#t'. The test is successful if the procedure returns a non-false value. If the `=>' syntax is used, then if the test succeeds it must return a list containing the arguments to be provided to the corresponding expression. In the following example, a string will only be matched at the beginning of the file: (let ((expect-port (open-input-file "/etc/passwd"))) (expect ((lambda (s eof?) (string=? s "fnord!")) (display "Got a nobody user!\n")))) The control variables described for `expect-strings' also influence the behaviour of `expect', with the exception of variables whose names begin with `expect-strings-'.  File: guile.info, Node: The Scheme shell (scsh), Next: Tracing, Prev: Expect, Up: Guile Modules 6.14 The Scheme shell (scsh) ============================ An incomplete port of the Scheme shell (scsh) is available for Guile as a separate package. The current status of guile-scsh can be found at `http://arglist.com/guile/'. For information about scsh see `http://www.scsh.net/'. The closest emulation of scsh can be obtained by running: (load-from-path "scsh/init") See the USAGE file supplied with guile-scsh for more details.  File: guile.info, Node: Tracing, Prev: The Scheme shell (scsh), Up: Guile Modules 6.15 Tracing ============ The `(ice-9 debug)' module implements tracing of procedure applications. When a procedure is "traced", it means that every call to that procedure is reported to the user during a program run. The idea is that you can mark a collection of procedures for tracing, and Guile will subsequently print out a line of the form | | [PROCEDURE ARGS ...] whenever a marked procedure is about to be applied to its arguments. This can help a programmer determine whether a function is being called at the wrong time or with the wrong set of arguments. In addition, the indentation of the output is useful for demonstrating how the traced applications are or are not tail recursive with respect to each other. Thus, a trace of a non-tail recursive factorial implementation looks like this: [fact1 4] | [fact1 3] | | [fact1 2] | | | [fact1 1] | | | | [fact1 0] | | | | 1 | | | 1 | | 2 | 6 24 While a typical tail recursive implementation would look more like this: [fact2 4] [facti 1 4] [facti 4 3] [facti 12 2] [facti 24 1] [facti 24 0] 24 -- Scheme Procedure: trace procedure Enable tracing for `procedure'. While a program is being run, Guile will print a brief report at each call to a traced procedure, advising the user which procedure was called and the arguments that were passed to it. -- Scheme Procedure: untrace procedure Disable tracing for `procedure'. Here is another example: (define (rev ls) (if (null? ls) '() (append (rev (cdr ls)) (cons (car ls) '())))) => rev (trace rev) => (rev) (rev '(a b c d e)) => [rev (a b c d e)] | [rev (b c d e)] | | [rev (c d e)] | | | [rev (d e)] | | | | [rev (e)] | | | | | [rev ()] | | | | | () | | | | (e) | | | (e d) | | (e d c) | (e d c b) (e d c b a) (e d c b a) Note the way Guile indents the output, illustrating the depth of execution at each procedure call. This can be used to demonstrate, for example, that Guile implements self-tail-recursion properly: (define (rev ls sl) (if (null? ls) sl (rev (cdr ls) (cons (car ls) sl)))) => rev (trace rev) => (rev) (rev '(a b c d e) '()) => [rev (a b c d e) ()] [rev (b c d e) (a)] [rev (c d e) (b a)] [rev (d e) (c b a)] [rev (e) (d c b a)] [rev () (e d c b a)] (e d c b a) (e d c b a) Since the tail call is effectively optimized to a `goto' statement, there is no need for Guile to create a new stack frame for each iteration. Tracing reveals this optimization in operation.  File: guile.info, Node: Autoconf Support, Next: Data Representation, Prev: Guile Modules, Up: Top 7 Autoconf Support ****************** When Guile is installed, a pkg-config description file and a set of Autoconf macros is installed. This chapter documents pkg-config and Autoconf support, as well as the high-level guile-tool Autofrisk. *Note The GNU Autoconf Manual: (autoconf)Top, for more info. * Menu: * Autoconf Background:: Why use autoconf? * Autoconf Macros:: The GUILE_* macros. * Using Autoconf Macros:: How to use them, plus examples. * Autofrisk:: AUTOFRISK_CHECKS and AUTOFRISK_SUMMARY. * Using Autofrisk:: Example modules.af files.  File: guile.info, Node: Autoconf Background, Next: Autoconf Macros, Up: Autoconf Support 7.1 Autoconf Background ======================= As explained elsewhere (*note The GNU Autoconf Manual: (autoconf)Top.), any package needs configuration at build-time. If your package uses Guile (or uses a package that in turn uses Guile), you probably need to know what specific Guile features are available and details about them. The way to do this is to write feature tests and arrange for their execution by the `configure' script, typically by adding the tests to `configure.ac', and running `autoconf' to create `configure'. Users of your package then run `configure' in the normal way. Macros are a way to make common feature tests easy to express. Autoconf provides a wide range of macros (*note Existing Tests: (autoconf)Existing Tests.), and Guile installation provides Guile-specific tests in the areas of: program detection, compilation flags reporting, and Scheme module checks.  File: guile.info, Node: Autoconf Macros, Next: Using Autoconf Macros, Prev: Autoconf Background, Up: Autoconf Support 7.2 Autoconf Macros =================== GNU Guile provides a "pkg-config" description file, installed as `PREFIX/lib/pkgconfig/guile-1.8.pc', which contains all the information necessary to compile and link C applications that use Guile. The `pkg-config' program is able to read this file and provide this information to application programmers; it can be obtained at `http://pkg-config.freedesktop.org/'. The following command lines give respectively the C compilation and link flags needed to build Guile-using programs: pkg-config guile-1.8 --cflags pkg-config guile-1.8 --libs To ease use of pkg-config with Autoconf, pkg-config comes with a convenient Autoconf macro. The following example looks for Guile and sets the `GUILE_CFLAGS' and `GUILE_LIBS' variables accordingly, or prints an error and exits if Guile was not found: PKG_CHECK_MODULES([GUILE], [guile-1.8]) Guile comes with additional Autoconf macros providing more information, installed as `PREFIX/share/aclocal/guile.m4'. Their names all begin with `GUILE_'.  File: guile.info, Node: Using Autoconf Macros, Next: Autofrisk, Prev: Autoconf Macros, Up: Autoconf Support 7.3 Using Autoconf Macros ========================= Using the autoconf macros is straightforward: Add the macro "calls" (actually instantiations) to `configure.ac', run `aclocal', and finally, run `autoconf'. If your system doesn't have guile.m4 installed, place the desired macro definitions (`AC_DEFUN' forms) in `acinclude.m4', and `aclocal' will do the right thing. Some of the macros can be used inside normal shell constructs: `if foo ; then GUILE_BAZ ; fi', but this is not guaranteed. It's probably a good idea to instantiate macros at top-level. We now include two examples, one simple and one complicated. The first example is for a package that uses libguile, and thus needs to know how to compile and link against it. So we use `GUILE_FLAGS' to set the vars `GUILE_CFLAGS' and `GUILE_LDFLAGS', which are automatically substituted in the Makefile. In configure.ac: GUILE_FLAGS In Makefile.in: GUILE_CFLAGS = @GUILE_CFLAGS@ GUILE_LDFLAGS = @GUILE_LDFLAGS@ myprog.o: myprog.c $(CC) -o $ $(GUILE_CFLAGS) $< myprog: myprog.o $(CC) -o $ $< $(GUILE_LDFLAGS) The second example is for a package of Guile Scheme modules that uses an external program and other Guile Scheme modules (some might call this a "pure scheme" package). So we use the `GUILE_SITE_DIR' macro, a regular `AC_PATH_PROG' macro, and the `GUILE_MODULE_AVAILABLE' macro. In configure.ac: GUILE_SITE_DIR probably_wont_work="" # pgtype pgtable GUILE_MODULE_AVAILABLE(have_guile_pg, (database postgres)) test $have_guile_pg = no && probably_wont_work="(my pgtype) (my pgtable) $probably_wont_work" # gpgutils AC_PATH_PROG(GNUPG,gpg) test x"$GNUPG" = x && probably_wont_work="(my gpgutils) $probably_wont_work" if test ! "$probably_wont_work" = "" ; then p=" ***" echo echo "$p" echo "$p NOTE:" echo "$p The following modules probably won't work:" echo "$p $probably_wont_work" echo "$p They can be installed anyway, and will work if their" echo "$p dependencies are installed later. Please see README." echo "$p" echo fi In Makefile.in: instdir = @GUILE_SITE@/my install: $(INSTALL) my/*.scm $(instdir)  File: guile.info, Node: Autofrisk, Next: Using Autofrisk, Prev: Using Autoconf Macros, Up: Autoconf Support 7.4 Autofrisk ============= The "guile-tools autofrisk" command looks for the file `modules.af' in the current directory and writes out `modules.af.m4' containing autoconf definitions for `AUTOFRISK_CHECKS' and `AUTOFRISK_SUMMARY'. *Note Autoconf Background::, and *Note Using Autoconf Macros::, for more info. The modules.af file consists of a series of configuration forms (Scheme lists), which have one of the following formats: (files-glob PATTERN ...) ;; required (non-critical-external MODULE ...) ;; optional (non-critical-internal MODULE ...) ;; optional (programs (MODULE PROG ...) ...) ;; optional (pww-varname VARNAME) ;; optional PATTERN is a string that may contain "*" and "?" characters to be expanded into filenames. MODULE is a list of symbols naming a module, such as `(srfi srfi-1)'. VARNAME is a shell-safe name to use instead of `probably_wont_work', the default. This var is passed to `AC_SUBST'. PROG is a string that names a program, such as "gpg". Autofrisk expands the `files-glob' pattern(s) into a list of files, scans each file's module definition form(s), and constructs a module dependency graph wherein modules defined by `define-module' are considered "internal" and the remaining, "external". For each external module that has an internal dependency, Autofrisk emits a `GUILE_MODULE_REQUIRED' check (*note Autoconf Macros::), which altogether form the body of `AUTOFRISK_CHECKS'. `GUILE_MODULE_REQUIRED' causes the `configure' script to exit with an error message if the specified module is not available; it enforces a strong dependency. You can temper dependency strength by using the `non-critical-external' and `non-critical-internal' configuration forms in modules.af. For graph edges that touch such non-critical modules, Autofrisk uses `GUILE_MODULE_AVAILABLE', and arranges for `AUTOFRISK_SUMMARY' to display a warning if they are not found. The shell code resulting from the expansion of `AUTOFRISK_CHECKS' and `AUTOFRISK_SUMMARY' uses the shell variable `probably_wont_work' to collect the names of unfound non-critical modules. If this bothers you, use configuration form `(pww-name foo)' in modules.af. Although Autofrisk does not detect when a module uses a program (for example, in a `system' call), it can generate `AC_PATH_PROG' forms anyway if you use the `programs' configuration form in modules.af. These are collected into `AUTOCONF_CHECKS'. *Note Using Autofrisk::, for some modules.af examples.  File: guile.info, Node: Using Autofrisk, Prev: Autofrisk, Up: Autoconf Support 7.5 Using Autofrisk =================== Using Autofrisk (*note Autofrisk::) involves writing `modules.af' and adding two macro calls to `configure.in'. Here is an example of the latter: AUTOFRISK_CHECKS AUTOFRISK_SUMMARY Here is an adaptation of the second "GUILE_*" example (*note Using Autoconf Macros::) that does basically the same thing. (files-glob "my/*.scm") (non-critical-external (database postgres)) (programs ((my gpgutils) "gpg")) ;; (my gpgutils) uses "gpg" If the SRFI modules (*note SRFI Support::) were a separate package, we could use `guile-tools frisk' to find out its dependencies: $ guile-tools frisk srfi/*.scm 13 files, 18 modules (13 internal, 5 external), 9 edges x (ice-9 and-let-star) regular (srfi srfi-2) x (ice-9 syncase) regular (srfi srfi-11) x (ice-9 rdelim) regular (srfi srfi-10) x (ice-9 receive) regular (srfi srfi-8) regular (srfi srfi-1) x (ice-9 session) regular (srfi srfi-1) Then, we could use the following modules.af to help configure it: (files-glob "srfi/*.scm") (non-critical-external ;; relatively recent (ice-9 rdelim) (ice-9 receive) (ice-9 and-let-star)) (pww-varname not_fully_supported)  File: guile.info, Node: Data Representation, Next: GNU Free Documentation License, Prev: Autoconf Support, Up: Top Appendix A Data Representation in Guile *************************************** *by Jim Blandy* [Due to the rather non-orthogonal and performance-oriented nature of the SCM interface, you need to understand SCM internals *before* you can use the SCM API. That's why this chapter comes first.] [NOTE: this is Jim Blandy's essay almost entirely unmodified. It has to be adapted to fit this manual smoothly.] In order to make sense of Guile's SCM_ functions, or read libguile's source code, it's essential to have a good grasp of how Guile actually represents Scheme values. Otherwise, a lot of the code, and the conventions it follows, won't make very much sense. This essay is meant to provide the background necessary to read and write C code that manipulates Scheme values in a way that is compatible with libguile. We assume you know both C and Scheme, but we do not assume you are familiar with Guile's implementation. * Menu: * Data Representation in Scheme:: Why things aren't just totally straightforward, in general terms. * How Guile does it:: How to write C code that manipulates Guile values, with an explanation of Guile's garbage collector.  File: guile.info, Node: Data Representation in Scheme, Next: How Guile does it, Up: Data Representation A.1 Data Representation in Scheme ================================= Scheme is a latently-typed language; this means that the system cannot, in general, determine the type of a given expression at compile time. Types only become apparent at run time. Variables do not have fixed types; a variable may hold a pair at one point, an integer at the next, and a thousand-element vector later. Instead, values, not variables, have fixed types. In order to implement standard Scheme functions like `pair?' and `string?' and provide garbage collection, the representation of every value must contain enough information to accurately determine its type at run time. Often, Scheme systems also use this information to determine whether a program has attempted to apply an operation to an inappropriately typed value (such as taking the `car' of a string). Because variables, pairs, and vectors may hold values of any type, Scheme implementations use a uniform representation for values -- a single type large enough to hold either a complete value or a pointer to a complete value, along with the necessary typing information. The following sections will present a simple typing system, and then make some refinements to correct its major weaknesses. However, this is not a description of the system Guile actually uses. It is only an illustration of the issues Guile's system must address. We provide all the information one needs to work with Guile's data in *note How Guile does it::. * Menu: * A Simple Representation:: * Faster Integers:: * Cheaper Pairs:: * Guile Is Hairier::  File: guile.info, Node: A Simple Representation, Next: Faster Integers, Up: Data Representation in Scheme A.1.1 A Simple Representation ----------------------------- The simplest way to meet the above requirements in C would be to represent each value as a pointer to a structure containing a type indicator, followed by a union carrying the real value. Assuming that `SCM' is the name of our universal type, we can write: enum type { integer, pair, string, vector, ... }; typedef struct value *SCM; struct value { enum type type; union { int integer; struct { SCM car, cdr; } pair; struct { int length; char *elts; } string; struct { int length; SCM *elts; } vector; ... } value; }; with the ellipses replaced with code for the remaining Scheme types. This representation is sufficient to implement all of Scheme's semantics. If X is an `SCM' value: * To test if X is an integer, we can write `X->type == integer'. * To find its value, we can write `X->value.integer'. * To test if X is a vector, we can write `X->type == vector'. * If we know X is a vector, we can write `X->value.vector.elts[0]' to refer to its first element. * If we know X is a pair, we can write `X->value.pair.car' to extract its car.  File: guile.info, Node: Faster Integers, Next: Cheaper Pairs, Prev: A Simple Representation, Up: Data Representation in Scheme A.1.2 Faster Integers --------------------- Unfortunately, the above representation has a serious disadvantage. In order to return an integer, an expression must allocate a `struct value', initialize it to represent that integer, and return a pointer to it. Furthermore, fetching an integer's value requires a memory reference, which is much slower than a register reference on most processors. Since integers are extremely common, this representation is too costly, in both time and space. Integers should be very cheap to create and manipulate. One possible solution comes from the observation that, on many architectures, structures must be aligned on a four-byte boundary. (Whether or not the machine actually requires it, we can write our own allocator for `struct value' objects that assures this is true.) In this case, the lower two bits of the structure's address are known to be zero. This gives us the room we need to provide an improved representation for integers. We make the following rules: * If the lower two bits of an `SCM' value are zero, then the SCM value is a pointer to a `struct value', and everything proceeds as before. * Otherwise, the `SCM' value represents an integer, whose value appears in its upper bits. Here is C code implementing this convention: enum type { pair, string, vector, ... }; typedef struct value *SCM; struct value { enum type type; union { struct { SCM car, cdr; } pair; struct { int length; char *elts; } string; struct { int length; SCM *elts; } vector; ... } value; }; #define POINTER_P(x) (((int) (x) & 3) == 0) #define INTEGER_P(x) (! POINTER_P (x)) #define GET_INTEGER(x) ((int) (x) >> 2) #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1)) Notice that `integer' no longer appears as an element of `enum type', and the union has lost its `integer' member. Instead, we use the `POINTER_P' and `INTEGER_P' macros to make a coarse classification of values into integers and non-integers, and do further type testing as before. Here's how we would answer the questions posed above (again, assume X is an `SCM' value): * To test if X is an integer, we can write `INTEGER_P (X)'. * To find its value, we can write `GET_INTEGER (X)'. * To test if X is a vector, we can write: `POINTER_P (X) && X->type == vector' Given the new representation, we must make sure X is truly a pointer before we dereference it to determine its complete type. * If we know X is a vector, we can write `X->value.vector.elts[0]' to refer to its first element, as before. * If we know X is a pair, we can write `X->value.pair.car' to extract its car, just as before. This representation allows us to operate more efficiently on integers than the first. For example, if X and Y are known to be integers, we can compute their sum as follows: MAKE_INTEGER (GET_INTEGER (X) + GET_INTEGER (Y)) Now, integer math requires no allocation or memory references. Most real Scheme systems actually use an even more efficient representation, but this essay isn't about bit-twiddling. (Hint: what if pointers had `01' in their least significant bits, and integers had `00'?)  File: guile.info, Node: Cheaper Pairs, Next: Guile Is Hairier, Prev: Faster Integers, Up: Data Representation in Scheme A.1.3 Cheaper Pairs ------------------- However, there is yet another issue to confront. Most Scheme heaps contain more pairs than any other type of object; Jonathan Rees says that pairs occupy 45% of the heap in his Scheme implementation, Scheme 48. However, our representation above spends three `SCM'-sized words per pair -- one for the type, and two for the CAR and CDR. Is there any way to represent pairs using only two words? Let us refine the convention we established earlier. Let us assert that: * If the bottom two bits of an `SCM' value are `#b00', then it is a pointer, as before. * If the bottom two bits are `#b01', then the upper bits are an integer. This is a bit more restrictive than before. * If the bottom two bits are `#b10', then the value, with the bottom two bits masked out, is the address of a pair. Here is the new C code: enum type { string, vector, ... }; typedef struct value *SCM; struct value { enum type type; union { struct { int length; char *elts; } string; struct { int length; SCM *elts; } vector; ... } value; }; struct pair { SCM car, cdr; }; #define POINTER_P(x) (((int) (x) & 3) == 0) #define INTEGER_P(x) (((int) (x) & 3) == 1) #define GET_INTEGER(x) ((int) (x) >> 2) #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1)) #define PAIR_P(x) (((int) (x) & 3) == 2) #define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3)) Notice that `enum type' and `struct value' now only contain provisions for vectors and strings; both integers and pairs have become special cases. The code above also assumes that an `int' is large enough to hold a pointer, which isn't generally true. Our list of examples is now as follows: * To test if X is an integer, we can write `INTEGER_P (X)'; this is as before. * To find its value, we can write `GET_INTEGER (X)', as before. * To test if X is a vector, we can write: `POINTER_P (X) && X->type == vector' We must still make sure that X is a pointer to a `struct value' before dereferencing it to find its type. * If we know X is a vector, we can write `X->value.vector.elts[0]' to refer to its first element, as before. * We can write `PAIR_P (X)' to determine if X is a pair, and then write `GET_PAIR (X)->car' to refer to its car. This change in representation reduces our heap size by 15%. It also makes it cheaper to decide if a value is a pair, because no memory references are necessary; it suffices to check the bottom two bits of the `SCM' value. This may be significant when traversing lists, a common activity in a Scheme system. Again, most real Scheme systems use a slightly different implementation; for example, if GET_PAIR subtracts off the low bits of `x', instead of masking them off, the optimizer will often be able to combine that subtraction with the addition of the offset of the structure member we are referencing, making a modified pointer as fast to use as an unmodified pointer.  File: guile.info, Node: Guile Is Hairier, Prev: Cheaper Pairs, Up: Data Representation in Scheme A.1.4 Guile Is Hairier ---------------------- We originally started with a very simple typing system -- each object has a field that indicates its type. Then, for the sake of efficiency in both time and space, we moved some of the typing information directly into the `SCM' value, and left the rest in the `struct value'. Guile itself employs a more complex hierarchy, storing finer and finer gradations of type information in different places, depending on the object's coarser type. In the author's opinion, Guile could be simplified greatly without significant loss of efficiency, but the simplified system would still be more complex than what we've presented above.  File: guile.info, Node: How Guile does it, Prev: Data Representation in Scheme, Up: Data Representation A.2 How Guile does it ===================== Here we present the specifics of how Guile represents its data. We don't go into complete detail; an exhaustive description of Guile's system would be boring, and we do not wish to encourage people to write code which depends on its details anyway. We do, however, present everything one need know to use Guile's data. This section is in limbo. It used to document the 'low-level' C API of Guile that was used both by clients of libguile and by libguile itself. In the future, clients should only need to look into the sections *note Programming in C:: and *note API Reference::. This section will in the end only contain stuff about the internals of Guile. * Menu: * General Rules:: * Conservative GC:: * Immediates vs Non-immediates:: * Immediate Datatypes:: * Non-immediate Datatypes:: * Signalling Type Errors:: * Unpacking the SCM type::  File: guile.info, Node: General Rules, Next: Conservative GC, Up: How Guile does it A.2.1 General Rules ------------------- Any code which operates on Guile datatypes must `#include' the header file `'. This file contains a definition for the `SCM' typedef (Guile's universal type, as in the examples above), and definitions and declarations for a host of macros and functions that operate on `SCM' values. All identifiers declared by `' begin with `scm_' or `SCM_'. The functions described here generally check the types of their `SCM' arguments, and signal an error if their arguments are of an inappropriate type. Macros generally do not, unless that is their specified purpose. You must verify their argument types beforehand, as necessary. Macros and functions that return a boolean value have names ending in `P' or `_p' (for "predicate"). Those that return a negated boolean value have names starting with `SCM_N'. For example, `SCM_IMP (X)' is a predicate which returns non-zero iff X is an immediate value (an `IM'). `SCM_NCONSP (X)' is a predicate which returns non-zero iff X is _not_ a pair object (a `CONS').  File: guile.info, Node: Conservative GC, Next: Immediates vs Non-immediates, Prev: General Rules, Up: How Guile does it A.2.2 Conservative Garbage Collection ------------------------------------- Aside from the latent typing, the major source of constraints on a Scheme implementation's data representation is the garbage collector. The collector must be able to traverse every live object in the heap, to determine which objects are not live. There are many ways to implement this, but Guile uses an algorithm called "mark and sweep". The collector scans the system's global variables and the local variables on the stack to determine which objects are immediately accessible by the C code. It then scans those objects to find the objects they point to, et cetera. The collector sets a "mark bit" on each object it finds, so each object is traversed only once. This process is called "tracing". When the collector can find no unmarked objects pointed to by marked objects, it assumes that any objects that are still unmarked will never be used by the program (since there is no path of dereferences from any global or local variable that reaches them) and deallocates them. In the above paragraphs, we did not specify how the garbage collector finds the global and local variables; as usual, there are many different approaches. Frequently, the programmer must maintain a list of pointers to all global variables that refer to the heap, and another list (adjusted upon entry to and exit from each function) of local variables, for the collector's benefit. The list of global variables is usually not too difficult to maintain, since global variables are relatively rare. However, an explicitly maintained list of local variables (in the author's personal experience) is a nightmare to maintain. Thus, Guile uses a technique called "conservative garbage collection", to make the local variable list unnecessary. The trick to conservative collection is to treat the stack as an ordinary range of memory, and assume that _every_ word on the stack is a pointer into the heap. Thus, the collector marks all objects whose addresses appear anywhere in the stack, without knowing for sure how that word is meant to be interpreted. Obviously, such a system will occasionally retain objects that are actually garbage, and should be freed. In practice, this is not a problem. The alternative, an explicitly maintained list of local variable addresses, is effectively much less reliable, due to programmer error. To accommodate this technique, data must be represented so that the collector can accurately determine whether a given stack word is a pointer or not. Guile does this as follows: * Every heap object has a two-word header, called a "cell". Some objects, like pairs, fit entirely in a cell's two words; others may store pointers to additional memory in either of the words. For example, strings and vectors store their length in the first word, and a pointer to their elements in the second. * Guile allocates whole arrays of cells at a time, called "heap segments". These segments are always allocated so that the cells they contain fall on eight-byte boundaries, or whatever is appropriate for the machine's word size. Guile keeps all cells in a heap segment initialized, whether or not they are currently in use. * Guile maintains a sorted table of heap segments. Thus, given any random word W fetched from the stack, Guile's garbage collector can consult the table to see if W falls within a known heap segment, and check W's alignment. If both tests pass, the collector knows that W is a valid pointer to a cell, intentional or not, and proceeds to trace the cell. Note that heap segments do not contain all the data Guile uses; cells for objects like vectors and strings contain pointers to other memory areas. However, since those pointers are internal, and not shared among many pieces of code, it is enough for the collector to find the cell, and then use the cell's type to find more pointers to trace.  File: guile.info, Node: Immediates vs Non-immediates, Next: Immediate Datatypes, Prev: Conservative GC, Up: How Guile does it A.2.3 Immediates vs Non-immediates ---------------------------------- Guile classifies Scheme objects into two kinds: those that fit entirely within an `SCM', and those that require heap storage. The former class are called "immediates". The class of immediates includes small integers, characters, boolean values, the empty list, the mysterious end-of-file object, and some others. The remaining types are called, not surprisingly, "non-immediates". They include pairs, procedures, strings, vectors, and all other data types in Guile. -- Macro: int SCM_IMP (SCM X) Return non-zero iff X is an immediate object. -- Macro: int SCM_NIMP (SCM X) Return non-zero iff X is a non-immediate object. This is the exact complement of `SCM_IMP', above. Note that for versions of Guile prior to 1.4 it was necessary to use the `SCM_NIMP' macro before calling a finer-grained predicate to determine X's type, such as `SCM_CONSP' or `SCM_VECTORP'. This is no longer required: the definitions of all Guile type predicates now include a call to `SCM_NIMP' where necessary.  File: guile.info, Node: Immediate Datatypes, Next: Non-immediate Datatypes, Prev: Immediates vs Non-immediates, Up: How Guile does it A.2.4 Immediate Datatypes ------------------------- The following datatypes are immediate values; that is, they fit entirely within an `SCM' value. The `SCM_IMP' and `SCM_NIMP' macros will distinguish these from non-immediates; see *note Immediates vs Non-immediates:: for an explanation of the distinction. Note that the type predicates for immediate values work correctly on any `SCM' value; you do not need to call `SCM_IMP' first, to establish that a value is immediate. * Menu: * Integer Data:: * Character Data:: * Boolean Data:: * Unique Values::  File: guile.info, Node: Integer Data, Next: Character Data, Up: Immediate Datatypes A.2.4.1 Integers ................ Here are functions for operating on small integers, that fit within an `SCM'. Such integers are called "immediate numbers", or "INUMs". In general, INUMs occupy all but two bits of an `SCM'. Bignums and floating-point numbers are non-immediate objects, and have their own, separate accessors. The functions here will not work on them. This is not as much of a problem as you might think, however, because the system never constructs bignums that could fit in an INUM, and never uses floating point values for exact integers. -- Macro: int SCM_INUMP (SCM X) Return non-zero iff X is a small integer value. -- Macro: int SCM_NINUMP (SCM X) The complement of SCM_INUMP. -- Macro: int SCM_INUM (SCM X) Return the value of X as an ordinary, C integer. If X is not an INUM, the result is undefined. -- Macro: SCM SCM_MAKINUM (int I) Given a C integer I, return its representation as an `SCM'. This function does not check for overflow.  File: guile.info, Node: Character Data, Next: Boolean Data, Prev: Integer Data, Up: Immediate Datatypes A.2.4.2 Characters .................. Here are functions for operating on characters. -- Macro: int SCM_CHARP (SCM X) Return non-zero iff X is a character value. -- Macro: unsigned int SCM_CHAR (SCM X) Return the value of `x' as a C character. If X is not a Scheme character, the result is undefined. -- Macro: SCM SCM_MAKE_CHAR (int C) Given a C character C, return its representation as a Scheme character value.  File: guile.info, Node: Boolean Data, Next: Unique Values, Prev: Character Data, Up: Immediate Datatypes A.2.4.3 Booleans ................ Booleans are represented as two specific immediate SCM values, `SCM_BOOL_T' and `SCM_BOOL_F'. *Note Booleans::, for more information.  File: guile.info, Node: Unique Values, Prev: Boolean Data, Up: Immediate Datatypes A.2.4.4 Unique Values ..................... The immediate values that are neither small integers, characters, nor booleans are all unique values -- that is, datatypes with only one instance. -- Macro: SCM SCM_EOL The Scheme empty list object, or "End Of List" object, usually written in Scheme as `'()'. -- Macro: SCM SCM_EOF_VAL The Scheme end-of-file value. It has no standard written representation, for obvious reasons. -- Macro: SCM SCM_UNSPECIFIED The value returned by expressions which the Scheme standard says return an "unspecified" value. This is sort of a weirdly literal way to take things, but the standard read-eval-print loop prints nothing when the expression returns this value, so it's not a bad idea to return this when you can't think of anything else helpful. -- Macro: SCM SCM_UNDEFINED The "undefined" value. Its most important property is that is not equal to any valid Scheme value. This is put to various internal uses by C code interacting with Guile. For example, when you write a C function that is callable from Scheme and which takes optional arguments, the interpreter passes `SCM_UNDEFINED' for any arguments you did not receive. We also use this to mark unbound variables. -- Macro: int SCM_UNBNDP (SCM X) Return true if X is `SCM_UNDEFINED'. Apply this to a symbol's value to see if it has a binding as a global variable.  File: guile.info, Node: Non-immediate Datatypes, Next: Signalling Type Errors, Prev: Immediate Datatypes, Up: How Guile does it A.2.5 Non-immediate Datatypes ----------------------------- A non-immediate datatype is one which lives in the heap, either because it cannot fit entirely within a `SCM' word, or because it denotes a specific storage location (in the nomenclature of the Revised^5 Report on Scheme). The `SCM_IMP' and `SCM_NIMP' macros will distinguish these from immediates; see *note Immediates vs Non-immediates::. Given a cell, Guile distinguishes between pairs and other non-immediate types by storing special "tag" values in a non-pair cell's car, that cannot appear in normal pairs. A cell with a non-tag value in its car is an ordinary pair. The type of a cell with a tag in its car depends on the tag; the non-immediate type predicates test this value. If a tag value appears elsewhere (in a vector, for example), the heap may become corrupted. Note how the type information for a non-immediate object is split between the `SCM' word and the cell that the `SCM' word points to. The `SCM' word itself only indicates that the object is non-immediate -- in other words stored in a heap cell. The tag stored in the first word of the heap cell indicates more precisely the type of that object. The type predicates for non-immediate values work correctly on any `SCM' value; you do not need to call `SCM_NIMP' first, to establish that a value is non-immediate. * Menu: * Pair Data:: * Vector Data:: * Procedures:: * Closures:: * Subrs:: * Port Data::  File: guile.info, Node: Pair Data, Next: Vector Data, Up: Non-immediate Datatypes A.2.5.1 Pairs ............. Pairs are the essential building block of list structure in Scheme. A pair object has two fields, called the "car" and the "cdr". It is conventional for a pair's CAR to contain an element of a list, and the CDR to point to the next pair in the list, or to contain `SCM_EOL', indicating the end of the list. Thus, a set of pairs chained through their CDRs constitutes a singly-linked list. Scheme and libguile define many functions which operate on lists constructed in this fashion, so although lists chained through the CARs of pairs will work fine too, they may be less convenient to manipulate, and receive less support from the community. Guile implements pairs by mapping the CAR and CDR of a pair directly into the two words of the cell. -- Macro: int SCM_CONSP (SCM X) Return non-zero iff X is a Scheme pair object. -- Macro: int SCM_NCONSP (SCM X) The complement of SCM_CONSP. -- Function: SCM scm_cons (SCM CAR, SCM CDR) Allocate ("CONStruct") a new pair, with CAR and CDR as its contents. The macros below perform no type checking. The results are undefined if CELL is an immediate. However, since all non-immediate Guile objects are constructed from cells, and these macros simply return the first element of a cell, they actually can be useful on datatypes other than pairs. (Of course, it is not very modular to use them outside of the code which implements that datatype.) -- Macro: SCM SCM_CAR (SCM CELL) Return the CAR, or first field, of CELL. -- Macro: SCM SCM_CDR (SCM CELL) Return the CDR, or second field, of CELL. -- Macro: void SCM_SETCAR (SCM CELL, SCM X) Set the CAR of CELL to X. -- Macro: void SCM_SETCDR (SCM CELL, SCM X) Set the CDR of CELL to X. -- Macro: SCM SCM_CAAR (SCM CELL) -- Macro: SCM SCM_CADR (SCM CELL) -- Macro: SCM SCM_CDAR (SCM CELL) ... -- Macro: SCM SCM_CDDDDR (SCM CELL) Return the CAR of the CAR of CELL, the CAR of the CDR of CELL, et cetera.  File: guile.info, Node: Vector Data, Next: Procedures, Prev: Pair Data, Up: Non-immediate Datatypes A.2.5.2 Vectors, Strings, and Symbols ..................................... Vectors, strings, and symbols have some properties in common. They all have a length, and they all have an array of elements. In the case of a vector, the elements are `SCM' values; in the case of a string or symbol, the elements are characters. All these types store their length (along with some tagging bits) in the CAR of their header cell, and store a pointer to the elements in their CDR. Thus, the `SCM_CAR' and `SCM_CDR' macros are (somewhat) meaningful when applied to these datatypes. -- Macro: int SCM_VECTORP (SCM X) Return non-zero iff X is a vector. -- Macro: int SCM_STRINGP (SCM X) Return non-zero iff X is a string. -- Macro: int SCM_SYMBOLP (SCM X) Return non-zero iff X is a symbol. -- Macro: int SCM_VECTOR_LENGTH (SCM X) -- Macro: int SCM_STRING_LENGTH (SCM X) -- Macro: int SCM_SYMBOL_LENGTH (SCM X) Return the length of the object X. The result is undefined if X is not a vector, string, or symbol, respectively. -- Macro: SCM * SCM_VECTOR_BASE (SCM X) Return a pointer to the array of elements of the vector X. The result is undefined if X is not a vector. -- Macro: char * SCM_STRING_CHARS (SCM X) -- Macro: char * SCM_SYMBOL_CHARS (SCM X) Return a pointer to the characters of X. The result is undefined if X is not a symbol or string, respectively. There are also a few magic values stuffed into memory before a symbol's characters, but you don't want to know about those. What cruft! Note that `SCM_VECTOR_BASE', `SCM_STRING_CHARS' and `SCM_SYMBOL_CHARS' return pointers to data within the respective object. Care must be taken that the object is not garbage collected while that data is still being accessed. This is the same as for a smob, *Note Remembering During Operations::.  File: guile.info, Node: Procedures, Next: Closures, Prev: Vector Data, Up: Non-immediate Datatypes A.2.5.3 Procedures .................. Guile provides two kinds of procedures: "closures", which are the result of evaluating a `lambda' expression, and "subrs", which are C functions packaged up as Scheme objects, to make them available to Scheme programmers. (There are actually other sorts of procedures: compiled closures, and continuations; see the source code for details about them.) -- Function: SCM scm_procedure_p (SCM X) Return `SCM_BOOL_T' iff X is a Scheme procedure object, of any sort. Otherwise, return `SCM_BOOL_F'.  File: guile.info, Node: Closures, Next: Subrs, Prev: Procedures, Up: Non-immediate Datatypes A.2.5.4 Closures ................ [FIXME: this needs to be further subbed, but texinfo has no subsubsub] A closure is a procedure object, generated as the value of a `lambda' expression in Scheme. The representation of a closure is straightforward -- it contains a pointer to the code of the lambda expression from which it was created, and a pointer to the environment it closes over. In Guile, each closure also has a property list, allowing the system to store information about the closure. I'm not sure what this is used for at the moment -- the debugger, maybe? -- Macro: int SCM_CLOSUREP (SCM X) Return non-zero iff X is a closure. -- Macro: SCM SCM_PROCPROPS (SCM X) Return the property list of the closure X. The results are undefined if X is not a closure. -- Macro: void SCM_SETPROCPROPS (SCM X, SCM P) Set the property list of the closure X to P. The results are undefined if X is not a closure. -- Macro: SCM SCM_CODE (SCM X) Return the code of the closure X. The result is undefined if X is not a closure. This function should probably only be used internally by the interpreter, since the representation of the code is intimately connected with the interpreter's implementation. -- Macro: SCM SCM_ENV (SCM X) Return the environment enclosed by X. The result is undefined if X is not a closure. This function should probably only be used internally by the interpreter, since the representation of the environment is intimately connected with the interpreter's implementation.  File: guile.info, Node: Subrs, Next: Port Data, Prev: Closures, Up: Non-immediate Datatypes A.2.5.5 Subrs ............. [FIXME: this needs to be further subbed, but texinfo has no subsubsub] A subr is a pointer to a C function, packaged up as a Scheme object to make it callable by Scheme code. In addition to the function pointer, the subr also contains a pointer to the name of the function, and information about the number of arguments accepted by the C function, for the sake of error checking. There is no single type predicate macro that recognizes subrs, as distinct from other kinds of procedures. The closest thing is `scm_procedure_p'; see *note Procedures::. -- Macro: char * SCM_SNAME (X) Return the name of the subr X. The result is undefined if X is not a subr. -- Function: SCM scm_c_define_gsubr (char *NAME, int REQ, int OPT, int REST, SCM (*FUNCTION)()) Create a new subr object named NAME, based on the C function FUNCTION, make it visible to Scheme the value of as a global variable named NAME, and return the subr object. The subr object accepts REQ required arguments, OPT optional arguments, and a REST argument iff REST is non-zero. The C function FUNCTION should accept `REQ + OPT' arguments, or `REQ + OPT + 1' arguments if `rest' is non-zero. When a subr object is applied, it must be applied to at least REQ arguments, or else Guile signals an error. FUNCTION receives the subr's first REQ arguments as its first REQ arguments. If there are fewer than OPT arguments remaining, then FUNCTION receives the value `SCM_UNDEFINED' for any missing optional arguments. If RST is non-zero, then any arguments after the first `REQ + OPT' are packaged up as a list and passed as FUNCTION's last argument. FUNCTION must not modify that list. (Because when subr is called through `apply' the list is directly from the `apply' argument, which the caller will expect to be unchanged.) Note that subrs can actually only accept a predefined set of combinations of required, optional, and rest arguments. For example, a subr can take one required argument, or one required and one optional argument, but a subr can't take one required and two optional arguments. It's bizarre, but that's the way the interpreter was written. If the arguments to `scm_c_define_gsubr' do not fit one of the predefined patterns, then `scm_c_define_gsubr' will return a compiled closure object instead of a subr object.  File: guile.info, Node: Port Data, Prev: Subrs, Up: Non-immediate Datatypes A.2.5.6 Ports ............. Haven't written this yet, 'cos I don't understand ports yet.  File: guile.info, Node: Signalling Type Errors, Next: Unpacking the SCM type, Prev: Non-immediate Datatypes, Up: How Guile does it A.2.6 Signalling Type Errors ---------------------------- Every function visible at the Scheme level should aggressively check the types of its arguments, to avoid misinterpreting a value, and perhaps causing a segmentation fault. Guile provides some macros to make this easier. -- Macro: void SCM_ASSERT (int TEST, SCM OBJ, unsigned int POSITION, const char *SUBR) If TEST is zero, signal a "wrong type argument" error, attributed to the subroutine named SUBR, operating on the value OBJ, which is the POSITION'th argument of SUBR. -- Macro: int SCM_ARG1 -- Macro: int SCM_ARG2 -- Macro: int SCM_ARG3 -- Macro: int SCM_ARG4 -- Macro: int SCM_ARG5 -- Macro: int SCM_ARG6 -- Macro: int SCM_ARG7 One of the above values can be used for POSITION to indicate the number of the argument of SUBR which is being checked. Alternatively, a positive integer number can be used, which allows to check arguments after the seventh. However, for parameter numbers up to seven it is preferable to use `SCM_ARGN' instead of the corresponding raw number, since it will make the code easier to understand. -- Macro: int SCM_ARGn Passing a value of zero or `SCM_ARGn' for POSITION allows to leave it unspecified which argument's type is incorrect. Again, `SCM_ARGn' should be preferred over a raw zero constant.  File: guile.info, Node: Unpacking the SCM type, Prev: Signalling Type Errors, Up: How Guile does it A.2.7 Unpacking the SCM Type ---------------------------- The previous sections have explained how `SCM' values can refer to immediate and non-immediate Scheme objects. For immediate objects, the complete object value is stored in the `SCM' word itself, while for non-immediates, the `SCM' word contains a pointer to a heap cell, and further information about the object in question is stored in that cell. This section describes how the `SCM' type is actually represented and used at the C level. In fact, there are two basic C data types to represent objects in Guile: `SCM' and `scm_t_bits'. * Menu: * Relationship between SCM and scm_t_bits:: * Immediate objects:: * Non-immediate objects:: * Allocating Cells:: * Heap Cell Type Information:: * Accessing Cell Entries:: * Basic Rules for Accessing Cell Entries::  File: guile.info, Node: Relationship between SCM and scm_t_bits, Next: Immediate objects, Up: Unpacking the SCM type A.2.7.1 Relationship between `SCM' and `scm_t_bits' ................................................... A variable of type `SCM' is guaranteed to hold a valid Scheme object. A variable of type `scm_t_bits', on the other hand, may hold a representation of a `SCM' value as a C integral type, but may also hold any C value, even if it does not correspond to a valid Scheme object. For a variable X of type `SCM', the Scheme object's type information is stored in a form that is not directly usable. To be able to work on the type encoding of the scheme value, the `SCM' variable has to be transformed into the corresponding representation as a `scm_t_bits' variable Y by using the `SCM_UNPACK' macro. Once this has been done, the type of the scheme object X can be derived from the content of the bits of the `scm_t_bits' value Y, in the way illustrated by the example earlier in this chapter (*note Cheaper Pairs::). Conversely, a valid bit encoding of a Scheme value as a `scm_t_bits' variable can be transformed into the corresponding `SCM' value using the `SCM_PACK' macro.  File: guile.info, Node: Immediate objects, Next: Non-immediate objects, Prev: Relationship between SCM and scm_t_bits, Up: Unpacking the SCM type A.2.7.2 Immediate objects ......................... A Scheme object may either be an immediate, i.e. carrying all necessary information by itself, or it may contain a reference to a "cell" with additional information on the heap. Although in general it should be irrelevant for user code whether an object is an immediate or not, within Guile's own code the distinction is sometimes of importance. Thus, the following low level macro is provided: -- Macro: int SCM_IMP (SCM X) A Scheme object is an immediate if it fulfills the `SCM_IMP' predicate, otherwise it holds an encoded reference to a heap cell. The result of the predicate is delivered as a C style boolean value. User code and code that extends Guile should normally not be required to use this macro. Summary: * Given a Scheme object X of unknown type, check first with `SCM_IMP (X)' if it is an immediate object. * If so, all of the type and value information can be determined from the `scm_t_bits' value that is delivered by `SCM_UNPACK (X)'.  File: guile.info, Node: Non-immediate objects, Next: Allocating Cells, Prev: Immediate objects, Up: Unpacking the SCM type A.2.7.3 Non-immediate objects ............................. A Scheme object of type `SCM' that does not fulfill the `SCM_IMP' predicate holds an encoded reference to a heap cell. This reference can be decoded to a C pointer to a heap cell using the `SCM2PTR' macro. The encoding of a pointer to a heap cell into a `SCM' value is done using the `PTR2SCM' macro. -- Macro: ( scm_t_cell *) SCM2PTR (SCM X) Extract and return the heap cell pointer from a non-immediate `SCM' object X. -- Macro: SCM PTR2SCM (scm_t_cell * X) Return a `SCM' value that encodes a reference to the heap cell pointer X. Note that it is also possible to transform a non-immediate `SCM' value by using `SCM_UNPACK' into a `scm_t_bits' variable. However, the result of `SCM_UNPACK' may not be used as a pointer to a `scm_t_cell': only `SCM2PTR' is guaranteed to transform a `SCM' object into a valid pointer to a heap cell. Also, it is not allowed to apply `PTR2SCM' to anything that is not a valid pointer to a heap cell. Summary: * Only use `SCM2PTR' on `SCM' values for which `SCM_IMP' is false! * Don't use `(scm_t_cell *) SCM_UNPACK (X)'! Use `SCM2PTR (X)' instead! * Don't use `PTR2SCM' for anything but a cell pointer!  File: guile.info, Node: Allocating Cells, Next: Heap Cell Type Information, Prev: Non-immediate objects, Up: Unpacking the SCM type A.2.7.4 Allocating Cells ........................ Guile provides both ordinary cells with two slots, and double cells with four slots. The following two function are the most primitive way to allocate such cells. If the caller intends to use it as a header for some other type, she must pass an appropriate magic value in WORD_0, to mark it as a member of that type, and pass whatever value as WORD_1, etc that the type expects. You should generally not need these functions, unless you are implementing a new datatype, and thoroughly understand the code in `'. If you just want to allocate pairs, use `scm_cons'. -- Function: SCM scm_cell (scm_t_bits word_0, scm_t_bits word_1) Allocate a new cell, initialize the two slots with WORD_0 and WORD_1, and return it. Note that WORD_0 and WORD_1 are of type `scm_t_bits'. If you want to pass a `SCM' object, you need to use `SCM_UNPACK'. -- Function: SCM scm_double_cell (scm_t_bits word_0, scm_t_bits word_1, scm_t_bits word_2, scm_t_bits word_3) Like `scm_cell', but allocates a double cell with four slots.  File: guile.info, Node: Heap Cell Type Information, Next: Accessing Cell Entries, Prev: Allocating Cells, Up: Unpacking the SCM type A.2.7.5 Heap Cell Type Information .................................. Heap cells contain a number of entries, each of which is either a scheme object of type `SCM' or a raw C value of type `scm_t_bits'. Which of the cell entries contain Scheme objects and which contain raw C values is determined by the first entry of the cell, which holds the cell type information. -- Macro: scm_t_bits SCM_CELL_TYPE (SCM X) For a non-immediate Scheme object X, deliver the content of the first entry of the heap cell referenced by X. This value holds the information about the cell type. -- Macro: void SCM_SET_CELL_TYPE (SCM X, scm_t_bits T) For a non-immediate Scheme object X, write the value T into the first entry of the heap cell referenced by X. The value T must hold a valid cell type.  File: guile.info, Node: Accessing Cell Entries, Next: Basic Rules for Accessing Cell Entries, Prev: Heap Cell Type Information, Up: Unpacking the SCM type A.2.7.6 Accessing Cell Entries .............................. For a non-immediate Scheme object X, the object type can be determined by reading the cell type entry using the `SCM_CELL_TYPE' macro. For each different type of cell it is known which cell entries hold Scheme objects and which cell entries hold raw C data. To access the different cell entries appropriately, the following macros are provided. -- Macro: scm_t_bits SCM_CELL_WORD (SCM X, unsigned int N) Deliver the cell entry N of the heap cell referenced by the non-immediate Scheme object X as raw data. It is illegal, to access cell entries that hold Scheme objects by using these macros. For convenience, the following macros are also provided. * SCM_CELL_WORD_0 (X) => SCM_CELL_WORD (X, 0) * SCM_CELL_WORD_1 (X) => SCM_CELL_WORD (X, 1) * ... * SCM_CELL_WORD_N (X) => SCM_CELL_WORD (X, N) -- Macro: SCM SCM_CELL_OBJECT (SCM X, unsigned int N) Deliver the cell entry N of the heap cell referenced by the non-immediate Scheme object X as a Scheme object. It is illegal, to access cell entries that do not hold Scheme objects by using these macros. For convenience, the following macros are also provided. * SCM_CELL_OBJECT_0 (X) => SCM_CELL_OBJECT (X, 0) * SCM_CELL_OBJECT_1 (X) => SCM_CELL_OBJECT (X, 1) * ... * SCM_CELL_OBJECT_N (X) => SCM_CELL_OBJECT (X, N) -- Macro: void SCM_SET_CELL_WORD (SCM X, unsigned int N, scm_t_bits W) Write the raw C value W into entry number N of the heap cell referenced by the non-immediate Scheme value X. Values that are written into cells this way may only be read from the cells using the `SCM_CELL_WORD' macros or, in case cell entry 0 is written, using the `SCM_CELL_TYPE' macro. For the special case of cell entry 0 it has to be made sure that W contains a cell type information which does not describe a Scheme object. For convenience, the following macros are also provided. * SCM_SET_CELL_WORD_0 (X, W) => SCM_SET_CELL_WORD (X, 0, W) * SCM_SET_CELL_WORD_1 (X, W) => SCM_SET_CELL_WORD (X, 1, W) * ... * SCM_SET_CELL_WORD_N (X, W) => SCM_SET_CELL_WORD (X, N, W) -- Macro: void SCM_SET_CELL_OBJECT (SCM X, unsigned int N, SCM O) Write the Scheme object O into entry number N of the heap cell referenced by the non-immediate Scheme value X. Values that are written into cells this way may only be read from the cells using the `SCM_CELL_OBJECT' macros or, in case cell entry 0 is written, using the `SCM_CELL_TYPE' macro. For the special case of cell entry 0 the writing of a Scheme object into this cell is only allowed if the cell forms a Scheme pair. For convenience, the following macros are also provided. * SCM_SET_CELL_OBJECT_0 (X, O) => SCM_SET_CELL_OBJECT (X, 0, O) * SCM_SET_CELL_OBJECT_1 (X, O) => SCM_SET_CELL_OBJECT (X, 1, O) * ... * SCM_SET_CELL_OBJECT_N (X, O) => SCM_SET_CELL_OBJECT (X, N, O) Summary: * For a non-immediate Scheme object X of unknown type, get the type information by using `SCM_CELL_TYPE (X)'. * As soon as the cell type information is available, only use the appropriate access methods to read and write data to the different cell entries.  File: guile.info, Node: Basic Rules for Accessing Cell Entries, Prev: Accessing Cell Entries, Up: Unpacking the SCM type A.2.7.7 Basic Rules for Accessing Cell Entries .............................................. For each cell type it is generally up to the implementation of that type which of the corresponding cell entries hold Scheme objects and which hold raw C values. However, there is one basic rule that has to be followed: Scheme pairs consist of exactly two cell entries, which both contain Scheme objects. Further, a cell which contains a Scheme object in it first entry has to be a Scheme pair. In other words, it is not allowed to store a Scheme object in the first cell entry and a non Scheme object in the second cell entry. -- Macro: int SCM_CONSP (SCM X) Determine, whether the Scheme object X is a Scheme pair, i.e. whether X references a heap cell consisting of exactly two entries, where both entries contain a Scheme object. In this case, both entries will have to be accessed using the `SCM_CELL_OBJECT' macros. On the contrary, if the `SCM_CONSP' predicate is not fulfilled, the first entry of the Scheme cell is guaranteed not to be a Scheme value and thus the first cell entry must be accessed using the `SCM_CELL_WORD_0' macro.  File: guile.info, Node: GNU Free Documentation License, Next: Concept Index, Prev: Data Representation, Up: Top Appendix B GNU Free Documentation License ***************************************** Version 1.2, November 2002 Copyright (C) 2000,2001,2002, 2006 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements." 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See `http://www.gnu.org/copyleft/'. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. B.0.1 ADDENDUM: How to use this License for your documents ---------------------------------------------------------- To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.  File: guile.info, Node: Concept Index, Next: Procedure Index, Prev: GNU Free Documentation License, Up: Top Concept Index ************* This index contains concepts, keywords and non-Schemey names for several features, to make it easier to locate the desired sections. [index] * Menu: * !#: Block Comments. (line 6) * #!: Block Comments. (line 6) * #,(): SRFI-10. (line 6) * .guile_history: Loading Readline Support. (line 32) * .inputrc: Loading Readline Support. (line 38) * /etc/hosts: Network Databases. (line 13) * /etc/protocols: Network Databases. (line 143) * /etc/services: Network Databases. (line 192) * aatabase: Association Lists. (line 6) * alist <1>: SRFI-1 Association Lists. (line 6) * alist: Association Lists. (line 6) * Applications: Evaluation Model. (line 15) * arbiters: Arbiters. (line 6) * argument specialize: SRFI-26. (line 6) * arity, variable: SRFI-16. (line 6) * association list: SRFI-1 Association Lists. (line 6) * association List: Association Lists. (line 6) * asyncs: Asyncs. (line 6) * atomic time: SRFI-19 Introduction. (line 6) * autoconf: Autoconf Macros. (line 6) * autoload: Creating Guile Modules. (line 40) * begin: begin. (line 6) * binding renamer: Using Guile Modules. (line 32) * bindir: Build Config. (line 83) * bitwise logical: SRFI-60. (line 6) * block comments: Block Comments. (line 6) * Block read/write: Block Reading and Writing. (line 6) * Breakpoints: Traps. (line 6) * Buffered input: Buffered Input. (line 6) * buildstamp: Build Config. (line 90) * C port interface: C Port Interface. (line 6) * case: if cond case. (line 6) * chaining environments: Chaining. (line 6) * charset: Standard Character Sets. (line 9) * child processes: Processes. (line 6) * Closing ports: Closing. (line 6) * closure: About Closure. (line 6) * Code coverage: Traps. (line 6) * codeset: Standard Character Sets. (line 9) * command line: Runtime Environment. (line 11) * command line history: Readline Support. (line 6) * cond: if cond case. (line 6) * condition variable: Mutexes and Condition Variables. (line 6) * conditional evaluation: if cond case. (line 6) * conditions: SRFI-35. (line 6) * continuations: Continuations. (line 6) * converting data: Converting data between C and Scheme. (line 6) * copying: Guile License. (line 6) * current directory: Processes. (line 8) * data conversion: Converting data between C and Scheme. (line 6) * datadir: Build Config. (line 83) * date <1>: SRFI-19 Date. (line 6) * date: SRFI-19. (line 6) * date conversion: SRFI-19 Time/Date conversions. (line 6) * date to string: SRFI-19 Date to string. (line 6) * date, from string: SRFI-19 String to date. (line 6) * Debugging: Debugging. (line 6) * Default ports: Default Ports. (line 6) * delayed evaluation: Delayed Evaluation. (line 6) * device file: File System. (line 244) * directory contents: File System. (line 204) * duplicate binding: Creating Guile Modules. (line 85) * duplicate binding handlers: Creating Guile Modules. (line 121) * Emacs: Using Guile in Emacs. (line 6) * emacs regexp: Regular Expressions. (line 6) * encapsulation: Modules. (line 14) * encryption: Encryption. (line 6) * End of file object: Reading. (line 8) * environment <1>: Runtime Environment. (line 66) * environment <2>: Environments. (line 6) * environment: About Environments. (line 6) * environment, local: Local Variables. (line 6) * environment, top level: About Environments. (line 6) * equality: Equality. (line 6) * errno: Conventions. (line 48) * error handling: Exceptions. (line 6) * error messages in libguile: Error messages. (line 6) * error-signal: Handling Errors. (line 46) * Evaluations: Evaluation Model. (line 15) * Evaluator trap calls: Traps. (line 6) * exception handling: Exceptions. (line 6) * exceptions: SRFI-35. (line 6) * exec_prefix: Build Config. (line 83) * executing Scheme: Executing Scheme code. (line 6) * export: Creating Guile Modules. (line 62) * export-syntax: Creating Guile Modules. (line 73) * expression sequencing: begin. (line 6) * FDL, GNU Free Documentation License: GNU Free Documentation License. (line 6) * file descriptor: Ports and File Descriptors. (line 6) * file locking: Ports and File Descriptors. (line 352) * File port: File Ports. (line 6) * file system: File System. (line 6) * file times: File System. (line 157) * file tree walk: File Tree Walk. (line 6) * fluids: Fluids and Dynamic States. (line 6) * formatted output: Formatted Output. (line 6) * Frames: Evaluation Model. (line 27) * GDS: Using Guile in Emacs. (line 6) * general cond clause: if cond case. (line 41) * gh: GH. (line 6) * gh - headers: GH preliminaries. (line 9) * gh - linking: GH preliminaries. (line 12) * gh - reference manual: GH. (line 6) * GPL: Guile License. (line 6) * group file: User Information. (line 6) * guardians, testing for GC'd objects: GC Hooks. (line 46) * Guile threads: Threads. (line 6) * guile-snarf deprecated macros: Snarfing Macros. (line 6) * guile-snarf example: Function Snarfing. (line 24) * guile-snarf invocation: Function Snarfing. (line 24) * guile-snarf recognized macros: Snarfing Macros. (line 6) * GUILE_HISTORY: Loading Readline Support. (line 38) * GUILE_LOAD_PATH: Build Config. (line 54) * guileversion: Build Config. (line 90) * hash-comma: SRFI-10. (line 6) * host name: System Identification. (line 36) * if: if cond case. (line 6) * iff: Manual Conventions. (line 13) * includedir: Build Config. (line 83) * infodir: Build Config. (line 83) * information encapsulation: Modules. (line 14) * Initializing Guile: Initialization. (line 6) * Installing and uninstalling traps: How to Set a Trap. (line 6) * integers as bits: SRFI-60. (line 6) * invocation: Invoking Guile. (line 6) * IPv4: Network Address Conversion. (line 12) * IPv6: Network Address Conversion. (line 70) * iteration: while do. (line 6) * JACAL: JACAL. (line 6) * Jaffer, Aubrey: JACAL. (line 6) * julian day <1>: SRFI-19 Date. (line 64) * julian day: SRFI-19 Introduction. (line 28) * keyword objects: SRFI-88. (line 6) * lambda: Lambda. (line 6) * LANG: Locales. (line 24) * leap second: SRFI-19 Introduction. (line 16) * LGPL: Guile License. (line 6) * libdir: Build Config. (line 83) * libexecdir: Build Config. (line 83) * libguile - converting data: Converting data between C and Scheme. (line 6) * libguile - error messages: Error messages. (line 6) * libguile - executing Scheme: Executing Scheme code. (line 6) * libguile - gh: GH. (line 6) * libguile - new procedures: Defining new Scheme procedures in C. (line 6) * libguile - start interpreter: Starting and controlling the interpreter. (line 6) * libguileinterface: Build Config. (line 90) * LIBS: Build Config. (line 87) * license: Guile License. (line 6) * Line buffered input: Buffered Input. (line 31) * Line continuation: Buffered Input. (line 6) * Line input/output: Line/Delimited. (line 6) * list: SRFI-1. (line 6) * list constructor: SRFI-1 Constructors. (line 6) * list delete: SRFI-1 Deleting. (line 6) * list filter: SRFI-1 Filtering and Partitioning. (line 6) * list fold: SRFI-1 Fold and Map. (line 6) * list map: SRFI-1 Fold and Map. (line 6) * list partition: SRFI-1 Filtering and Partitioning. (line 6) * list predicate: SRFI-1 Predicates. (line 6) * list search: SRFI-1 Searching. (line 6) * list selector: SRFI-1 Selectors. (line 6) * list set operation: SRFI-1 Set Operations. (line 6) * local bindings: Local Bindings. (line 6) * local environment: Local Variables. (line 6) * local time: Time. (line 77) * local variable: Local Variables. (line 6) * local variables: Local Bindings. (line 6) * locale <1>: Locales. (line 6) * locale: Standard Character Sets. (line 9) * localstatedir: Build Config. (line 83) * location: About Environments. (line 6) * looping: while do. (line 6) * Low level trap calls: Traps. (line 42) * macros: Macros. (line 6) * mandir: Build Config. (line 83) * match structures: Match Structures. (line 6) * math - symbolic: JACAL. (line 6) * memory-allocation-error: Handling Errors. (line 65) * misc-error: Handling Errors. (line 72) * modified julian day <1>: SRFI-19 Date. (line 67) * modified julian day: SRFI-19 Introduction. (line 28) * modules: Modules. (line 6) * multiline comments: Block Comments. (line 6) * multiple values: Multiple Values. (line 6) * multiple values and cond: if cond case. (line 41) * mutex: Mutexes and Condition Variables. (line 6) * name space: Modules. (line 14) * name space - private: Modules. (line 29) * named let: while do. (line 6) * network: Networking. (line 6) * network address: Network Address Conversion. (line 6) * network database: Network Databases. (line 6) * network examples: Internet Socket Examples. (line 6) * network protocols: Network Databases. (line 143) * network services: Network Databases. (line 192) * network socket: Network Sockets and Communication. (line 6) * network socket address: Network Socket Address. (line 6) * new primitives: Defining new Scheme procedures in C. (line 6) * new procedures: Defining new Scheme procedures in C. (line 6) * no backtrace: Creating Guile Modules. (line 181) * numerical-overflow: Handling Errors. (line 55) * optargs: Optional Arguments. (line 23) * options - read: Reader options. (line 6) * out-of-range: Handling Errors. (line 57) * overflow, stack: Debugger options. (line 25) * overriding binding: Creating Guile Modules. (line 85) * parallel forms: Parallel Forms. (line 6) * parameter object: SRFI-39. (line 6) * parameter specialize: SRFI-26. (line 6) * password: Encryption. (line 23) * password file: User Information. (line 6) * pipe <1>: Pipes. (line 6) * pipe: Ports and File Descriptors. (line 186) * pkg-config: Autoconf Macros. (line 6) * pkgdatadir: Build Config. (line 83) * pkgincludedir: Build Config. (line 83) * pkglibdir: Build Config. (line 83) * polar form <1>: Complex. (line 13) * polar form: Complex Numbers. (line 23) * Port: Ports. (line 6) * port buffering: Ports and File Descriptors. (line 292) * Port implemenation: Port Implementation. (line 6) * Port, block read/write: Block Reading and Writing. (line 6) * Port, C interface: C Port Interface. (line 6) * Port, close: Closing. (line 6) * Port, default: Default Ports. (line 6) * Port, file: File Ports. (line 6) * Port, line input/output: Line/Delimited. (line 6) * Port, random access: Random Access. (line 6) * Port, soft: Soft Ports. (line 6) * Port, string: String Ports. (line 6) * Port, types: Port Types. (line 6) * Port, void: Void Ports. (line 6) * POSIX: POSIX. (line 6) * POSIX threads: Threads. (line 6) * prefix: Build Config. (line 83) * pretty printing: Pretty Printing. (line 6) * primitive procedures: Primitive Procedures. (line 6) * primitives: Primitive Procedures. (line 6) * primitives, new: Defining new Scheme procedures in C. (line 6) * procedure documentation: Procedure Properties. (line 64) * procedure properties: Procedure Properties. (line 32) * procedure with setter: Procedures with Setters. (line 6) * procedures, new: Defining new Scheme procedures in C. (line 6) * process group: Terminals and Ptys. (line 23) * process priority: Processes. (line 280) * process time: SRFI-19 Time. (line 34) * processes: Processes. (line 6) * Profiling: Traps. (line 6) * program arguments: Runtime Environment. (line 11) * promises: Delayed Evaluation. (line 6) * protocols: Network Databases. (line 143) * ptob: C Port Interface. (line 11) * pure module: Creating Guile Modules. (line 185) * q-empty: Queues. (line 65) * queues: Queues. (line 6) * R5RS syntax-rules system: Syntax Rules. (line 6) * Random access, ports: Random Access. (line 6) * re-export: Creating Guile Modules. (line 67) * re-export-syntax: Creating Guile Modules. (line 79) * read eval print loop - from the gh_ interface: Starting and controlling the interpreter. (line 23) * read options: Reader options. (line 6) * Reading: Reading. (line 6) * readline: Readline Support. (line 6) * readline options: Readline Options. (line 6) * receive: Multiple Values. (line 6) * record: SRFI-9. (line 6) * recursion: Tail Calls. (line 6) * recursive expression: SRFI-31. (line 6) * regex: Regular Expressions. (line 6) * regular expressions: Regular Expressions. (line 6) * regular-expression-syntax: Handling Errors. (line 69) * remembering: Remembering During Operations. (line 6) * REPL - from the gh_ interface: Starting and controlling the interpreter. (line 23) * replace: Creating Guile Modules. (line 85) * replacing binding: Creating Guile Modules. (line 85) * sameness: Equality. (line 6) * sbindir: Build Config. (line 83) * Scheme Shell: The Scheme shell (scsh). (line 6) * SCM data type: The SCM Type. (line 16) * SCSH: The Scheme shell (scsh). (line 6) * search and replace: Regexp Functions. (line 203) * sequencing: begin. (line 6) * services: Network Databases. (line 192) * setter: Procedures with Setters. (line 6) * Setting traps: How to Set a Trap. (line 6) * shadowing an imported variable binding: Chaining. (line 6) * sharedstatedir: Build Config. (line 83) * signal: Signals. (line 6) * SLIB: SLIB. (line 6) * socket: Network Sockets and Communication. (line 6) * socket address: Network Socket Address. (line 6) * socket client example: Internet Socket Examples. (line 11) * socket examples: Internet Socket Examples. (line 6) * socket server example: Internet Socket Examples. (line 27) * Soft port: Soft Ports. (line 6) * sorting: Sorting. (line 6) * sorting lists: Sorting. (line 6) * sorting vectors: Sorting. (line 6) * source properties: Source Properties. (line 6) * specialize parameter: SRFI-26. (line 6) * srcdir: Build Config. (line 83) * SRFI: SRFI Support. (line 6) * SRFI-0: SRFI-0. (line 6) * SRFI-1: SRFI-1. (line 6) * SRFI-10: SRFI-10. (line 6) * SRFI-11: SRFI-11. (line 6) * SRFI-13: SRFI-13. (line 6) * SRFI-14: SRFI-14. (line 6) * SRFI-16: SRFI-16. (line 6) * SRFI-17: SRFI-17. (line 6) * SRFI-19: SRFI-19. (line 6) * SRFI-2: SRFI-2. (line 6) * SRFI-26: SRFI-26. (line 6) * SRFI-31: SRFI-31. (line 6) * SRFI-34: SRFI-34. (line 6) * SRFI-35: SRFI-35. (line 6) * SRFI-37: SRFI-37. (line 6) * SRFI-39: SRFI-39. (line 6) * SRFI-4: SRFI-4. (line 6) * SRFI-55: SRFI-55. (line 6) * SRFI-6: SRFI-6. (line 6) * SRFI-60: SRFI-60. (line 6) * SRFI-61: if cond case. (line 41) * SRFI-69: SRFI-69. (line 6) * SRFI-8: SRFI-8. (line 6) * SRFI-88: SRFI-88. (line 6) * SRFI-88 keyword syntax: Keyword Read Syntax. (line 18) * SRFI-9: SRFI-9. (line 6) * Stack: Evaluation Model. (line 27) * Stack frames: Evaluation Model. (line 27) * stack overflow: Debugger options. (line 25) * stack-overflow: Handling Errors. (line 67) * standard error output: Default Ports. (line 40) * standard input: Default Ports. (line 8) * standard output: Default Ports. (line 25) * streams: Streams. (line 6) * String port: String Ports. (line 6) * string to date: SRFI-19 String to date. (line 6) * string, from date: SRFI-19 Date to string. (line 6) * symbolic math: JACAL. (line 6) * syncase: Syntax Rules. (line 36) * sysconfdir: Build Config. (line 83) * system asyncs: Asyncs. (line 6) * system clock: SRFI-19 Introduction. (line 24) * system name: System Identification. (line 6) * system-error: Handling Errors. (line 51) * TAI <1>: SRFI-19 Time. (line 18) * TAI: SRFI-19 Introduction. (line 6) * tail calls: Tail Calls. (line 6) * TCP, use of: GDS Architecture. (line 48) * temporary file: File System. (line 259) * terminal: Terminals and Ptys. (line 8) * thread time: SRFI-19 Time. (line 37) * threads: Threads. (line 6) * time <1>: SRFI-19 Time. (line 6) * time <2>: SRFI-19. (line 6) * time: Time. (line 6) * time conversion: SRFI-19 Time/Date conversions. (line 6) * time formatting: Time. (line 126) * time parsing: Time. (line 147) * top level environment: About Environments. (line 6) * top_srcdir: Build Config. (line 83) * Trace <1>: Specifying Trap Behaviour. (line 21) * Trace: Traps. (line 6) * Tracing <1>: Specifying Trap Behaviour. (line 21) * Tracing: Traps. (line 6) * transformation: Macros. (line 6) * Trap behaviour: Specifying Trap Behaviour. (line 6) * Trap classes: Traps. (line 18) * Trap context: Specifying Trap Behaviour. (line 46) * Trap objects: Traps. (line 18) * Trap terminology: Traps. (line 37) * Traps: Traps. (line 6) * Types of ports: Port Types. (line 6) * universal time: SRFI-19 Introduction. (line 6) * user asyncs: Asyncs. (line 6) * user information: User Information. (line 6) * UTC <1>: SRFI-19 Time. (line 15) * UTC: SRFI-19 Introduction. (line 6) * value history: Value History. (line 6) * variable arity: SRFI-16. (line 6) * variable definition: Top Level. (line 6) * variable, local: Local Variables. (line 6) * vcell: About Environments. (line 6) * Void port: Void Ports. (line 6) * Writing: Writing. (line 6) * wrong-number-of-args: Handling Errors. (line 62) * wrong-type-arg: Handling Errors. (line 60)