1This is guile.info, produced by makeinfo version 6.7 from guile.texi. 2 3This manual documents Guile version 3.0.7. 4 5 Copyright (C) 1996-1997, 2000-2005, 2009-2021 Free Software 6Foundation, Inc. 7 8 Permission is granted to copy, distribute and/or modify this document 9under the terms of the GNU Free Documentation License, Version 1.3 or 10any later version published by the Free Software Foundation; with no 11Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A 12copy of the license is included in the section entitled “GNU Free 13Documentation License.” 14INFO-DIR-SECTION The Algorithmic Language Scheme 15START-INFO-DIR-ENTRY 16* Guile Reference: (guile). The Guile reference manual. 17END-INFO-DIR-ENTRY 18 19 20File: guile.info, Node: SRFI-171 Helpers, Prev: SRFI-171 Transducers, Up: SRFI-171 21 227.5.46.5 Helper functions for writing transducers 23................................................. 24 25These functions are in the ‘(srfi srfi-171 meta)’ module and are only 26usable when you want to write your own transducers. 27 28 -- Scheme Procedure: reduced value 29 Wraps a value in a ‘<reduced>’ container, signalling that the 30 reduction should stop. 31 32 -- Scheme Procedure: reduced? value 33 Returns #t if value is a ‘<reduced>’ record. 34 35 -- Scheme Procedure: unreduce reduced-container 36 Returns the value in reduced-container. 37 38 -- Scheme Procedure: ensure-reduced value 39 Wraps value in a ‘<reduced>’ container if it is not already 40 reduced. 41 42 -- Scheme Procedure: preserving-reduced reducer 43 Wraps ‘reducer’ in another reducer that encapsulates any returned 44 reduced value in another reduced container. This is useful in 45 places where you re-use a reducer with [collection]-reduce. If the 46 reducer returns a reduced value, [collection]-reduce unwraps it. 47 Unless handled, this leads to the reduction continuing. 48 49 -- Scheme Procedure: list-reduce f identity lst 50 The reducing function used internally by ‘list-transduce’. F is a 51 reducer as returned by a transducer. IDENTITY is the identity 52 (sometimes called "seed") of the reduction. LST is a list. If F 53 returns a reduced value, the reduction stops immediately and the 54 unreduced value is returned. 55 56 -- Scheme Procedure: vector-reduce f identity vec 57 The vector version of list-reduce. 58 59 -- Scheme Procedure: string-reduce f identity str 60 The string version of list-reduce. 61 62 -- Scheme Procedure: bytevector-u8-reduce f identity bv 63 The bytevector-u8 version of list-reduce. 64 65 -- Scheme Procedure: port-reduce f identity reader port 66 The port version of list-reducer. It reduces over port using 67 reader until reader returns the EOF object. 68 69 -- Scheme Procedure: generator-reduce f identity gen 70 The port version of list-reduce. It reduces over ‘gen’ until it 71 returns the EOF object 72 73 74File: guile.info, Node: R6RS Support, Next: R7RS Support, Prev: SRFI Support, Up: Guile Modules 75 767.6 R6RS Support 77================ 78 79*Note R6RS Libraries::, for more information on how to define R6RS 80libraries, and their integration with Guile modules. 81 82* Menu: 83 84* R6RS Incompatibilities:: Guile mostly implements R6RS. 85* R6RS Standard Libraries:: Modules defined by the R6RS. 86 87 88File: guile.info, Node: R6RS Incompatibilities, Next: R6RS Standard Libraries, Up: R6RS Support 89 907.6.1 Incompatibilities with the R6RS 91------------------------------------- 92 93There are some incompatibilities between Guile and the R6RS. Some of 94them are intentional, some of them are bugs, and some are simply 95unimplemented features. Please let the Guile developers know if you 96find one that is not on this list. 97 98 • The R6RS specifies many situations in which a conforming 99 implementation must signal a specific error. Guile doesn’t really 100 care about that too much—if a correct R6RS program would not hit 101 that error, we don’t bother checking for it. 102 103 • Multiple ‘library’ forms in one file are not yet supported. This 104 is because the expansion of ‘library’ sets the current module, but 105 does not restore it. This is a bug. 106 107 • R6RS unicode escapes within strings are disabled by default, 108 because they conflict with Guile’s already-existing escapes. The 109 same is the case for R6RS treatment of escaped newlines in strings. 110 111 R6RS behavior can be turned on via a reader option. *Note String 112 Syntax::, for more information. 113 114 • Guile does not yet support Unicode escapes in symbols, such as 115 ‘H\x65;llo’ (the same as ‘Hello’), or ‘\x3BB;’ (the same as ‘λ’). 116 117 • A ‘set!’ to a variable transformer may only expand to an 118 expression, not a definition—even if the original ‘set!’ expression 119 was in definition context. 120 121 • Instead of using the algorithm detailed in chapter 10 of the R6RS, 122 expansion of toplevel forms happens sequentially. 123 124 For example, while the expansion of the following set of toplevel 125 definitions does the correct thing: 126 127 (begin 128 (define even? 129 (lambda (x) 130 (or (= x 0) (odd? (- x 1))))) 131 (define-syntax odd? 132 (syntax-rules () 133 ((odd? x) (not (even? x))))) 134 (even? 10)) 135 ⇒ #t 136 137 The same definitions outside of the ‘begin’ wrapper do not: 138 139 (define even? 140 (lambda (x) 141 (or (= x 0) (odd? (- x 1))))) 142 (define-syntax odd? 143 (syntax-rules () 144 ((odd? x) (not (even? x))))) 145 (even? 10) 146 <unnamed port>:4:18: In procedure even?: 147 <unnamed port>:4:18: Wrong type to apply: #<syntax-transformer odd?> 148 149 This is because when expanding the right-hand-side of ‘even?’, the 150 reference to ‘odd?’ is not yet marked as a syntax transformer, so 151 it is assumed to be a function. 152 153 This bug will only affect top-level programs, not code in ‘library’ 154 forms. Fixing it for toplevel forms seems doable, but tricky to 155 implement in a backward-compatible way. Suggestions and/or patches 156 would be appreciated. 157 158 • The ‘(rnrs io ports)’ module is incomplete. Work is ongoing to fix 159 this. 160 161 • Guile does not prevent use of textual I/O procedures on binary 162 ports, or vice versa. All ports in Guile support both binary and 163 textual I/O. *Note Encoding::, for full details. 164 165 • Guile’s implementation of ‘equal?’ may fail to terminate when 166 applied to arguments containing cycles. 167 168 Guile exposes a procedure in the root module to choose R6RS defaults 169over Guile’s historical defaults. 170 171 -- Scheme Procedure: install-r6rs! 172 Alter Guile’s default settings to better conform to the R6RS. 173 174 While Guile’s defaults may evolve over time, the current changes 175 that this procedure imposes are to add ‘.sls’ and ‘.guile.sls’ to 176 the set of supported ‘%load-extensions’, to better support R6RS 177 conventions. *Note Load Paths::. Also, enable R6RS unicode 178 escapes in strings; see the discussion above. 179 180 Finally, note that the ‘--r6rs’ command-line argument will call 181‘install-r6rs!’ before calling user code. R6RS users probably want to 182pass this argument to their Guile. 183 184 185File: guile.info, Node: R6RS Standard Libraries, Prev: R6RS Incompatibilities, Up: R6RS Support 186 1877.6.2 R6RS Standard Libraries 188----------------------------- 189 190In contrast with earlier versions of the Revised Report, the R6RS 191organizes the procedures and syntactic forms required of conforming 192implementations into a set of “standard libraries” which can be imported 193as necessary by user programs and libraries. Here we briefly list the 194libraries that have been implemented for Guile. 195 196 We do not attempt to document these libraries fully here, as most of 197their functionality is already available in Guile itself. The 198expectation is that most Guile users will use the well-known and 199well-documented Guile modules. These R6RS libraries are mostly useful 200to users who want to port their code to other R6RS systems. 201 202 The documentation in the following sections reproduces some of the 203content of the library section of the Report, but is mostly intended to 204provide supplementary information about Guile’s implementation of the 205R6RS standard libraries. For complete documentation, design rationales 206and further examples, we advise you to consult the “Standard Libraries” 207section of the Report (*note R6RS Standard Libraries: (r6rs)Standard 208Libraries.). 209 210* Menu: 211 212* Library Usage:: What to know about Guile’s library support. 213* rnrs base:: The base library. 214* rnrs unicode:: Access to Unicode operations. 215* rnrs bytevectors:: Functions for working with binary data. 216* rnrs lists:: List utilities. 217* rnrs sorting:: Sorting for lists and vectors. 218* rnrs control:: Additional control structures. 219 220* R6RS Records:: A note about R6RS records. 221* rnrs records syntactic:: Syntactic API for R6RS records. 222* rnrs records procedural:: Procedural API for R6RS records. 223* rnrs records inspection:: Reflection on R6RS records. 224 225* rnrs exceptions:: Handling exceptional situations. 226* rnrs conditions:: Data structures for exceptions. 227 228* R6RS I/O Conditions:: Predefined I/O error types. 229* R6RS Transcoders:: Characters and bytes. 230* rnrs io ports:: Support for port-based I/O. 231* R6RS File Ports:: Working with files. 232* rnrs io simple:: High-level I/O API. 233 234* rnrs files:: Functions for working with files. 235* rnrs programs:: Functions for working with processes. 236* rnrs arithmetic fixnums:: Fixed-precision arithmetic operations. 237* rnrs arithmetic flonums:: Floating-point arithmetic operations. 238* rnrs arithmetic bitwise:: Exact bitwise arithmetic operations. 239* rnrs syntax-case:: Support for ‘syntax-case’ macros. 240* rnrs hashtables:: Hashtables. 241* rnrs enums:: Enumerations. 242* rnrs:: The composite library. 243* rnrs eval:: Support for on-the-fly evaluation. 244* rnrs mutable-pairs:: Support for mutable pairs. 245* rnrs mutable-strings:: Support for mutable strings. 246* rnrs r5rs:: Compatibility layer for R5RS Scheme. 247 248 249File: guile.info, Node: Library Usage, Next: rnrs base, Up: R6RS Standard Libraries 250 2517.6.2.1 Library Usage 252..................... 253 254Guile implements the R6RS ‘library’ form as a transformation to a native 255Guile module definition. As a consequence of this, all of the libraries 256described in the following subsections, in addition to being available 257for use by R6RS libraries and top-level programs, can also be imported 258as if they were normal Guile modules—via a ‘use-modules’ form, say. For 259example, the R6RS “composite” library can be imported by: 260 261 (import (rnrs (6))) 262 263 (use-modules ((rnrs) :version (6))) 264 265 For more information on Guile’s library implementation, see (*note 266R6RS Libraries::). 267 268 269File: guile.info, Node: rnrs base, Next: rnrs unicode, Prev: Library Usage, Up: R6RS Standard Libraries 270 2717.6.2.2 rnrs base 272................. 273 274The ‘(rnrs base (6))’ library exports the procedures and syntactic forms 275described in the main section of the Report (*note R6RS Base library: 276(r6rs)Base library.). They are grouped below by the existing manual 277sections to which they correspond. 278 279 -- Scheme Procedure: boolean? obj 280 -- Scheme Procedure: not x 281 *Note Booleans::, for documentation. 282 283 -- Scheme Procedure: symbol? obj 284 -- Scheme Procedure: symbol->string sym 285 -- Scheme Procedure: string->symbol str 286 *Note Symbol Primitives::, for documentation. 287 288 -- Scheme Procedure: char? obj 289 -- Scheme Procedure: char=? 290 -- Scheme Procedure: char<? 291 -- Scheme Procedure: char>? 292 -- Scheme Procedure: char<=? 293 -- Scheme Procedure: char>=? 294 -- Scheme Procedure: integer->char n 295 -- Scheme Procedure: char->integer chr 296 *Note Characters::, for documentation. 297 298 -- Scheme Procedure: list? x 299 -- Scheme Procedure: null? x 300 *Note List Predicates::, for documentation. 301 302 -- Scheme Procedure: pair? x 303 -- Scheme Procedure: cons x y 304 -- Scheme Procedure: car pair 305 -- Scheme Procedure: cdr pair 306 -- Scheme Procedure: caar pair 307 -- Scheme Procedure: cadr pair 308 -- Scheme Procedure: cdar pair 309 -- Scheme Procedure: cddr pair 310 -- Scheme Procedure: caaar pair 311 -- Scheme Procedure: caadr pair 312 -- Scheme Procedure: cadar pair 313 -- Scheme Procedure: cdaar pair 314 -- Scheme Procedure: caddr pair 315 -- Scheme Procedure: cdadr pair 316 -- Scheme Procedure: cddar pair 317 -- Scheme Procedure: cdddr pair 318 -- Scheme Procedure: caaaar pair 319 -- Scheme Procedure: caaadr pair 320 -- Scheme Procedure: caadar pair 321 -- Scheme Procedure: cadaar pair 322 -- Scheme Procedure: cdaaar pair 323 -- Scheme Procedure: cddaar pair 324 -- Scheme Procedure: cdadar pair 325 -- Scheme Procedure: cdaadr pair 326 -- Scheme Procedure: cadadr pair 327 -- Scheme Procedure: caaddr pair 328 -- Scheme Procedure: caddar pair 329 -- Scheme Procedure: cadddr pair 330 -- Scheme Procedure: cdaddr pair 331 -- Scheme Procedure: cddadr pair 332 -- Scheme Procedure: cdddar pair 333 -- Scheme Procedure: cddddr pair 334 *Note Pairs::, for documentation. 335 336 -- Scheme Procedure: number? obj 337 *Note Numerical Tower::, for documentation. 338 339 -- Scheme Procedure: string? obj 340 *Note String Predicates::, for documentation. 341 342 -- Scheme Procedure: procedure? obj 343 *Note Procedure Properties::, for documentation. 344 345 -- Scheme Syntax: define name value 346 -- Scheme Syntax: set! variable-name value 347 *Note Definition::, for documentation. 348 349 -- Scheme Syntax: define-syntax keyword expression 350 -- Scheme Syntax: let-syntax ((keyword transformer) ...) exp1 exp2 ... 351 -- Scheme Syntax: letrec-syntax ((keyword transformer) ...) exp1 exp2 352 ... 353 *Note Defining Macros::, for documentation. 354 355 -- Scheme Syntax: identifier-syntax exp 356 *Note Identifier Macros::, for documentation. 357 358 -- Scheme Syntax: syntax-rules literals (pattern template) ... 359 *Note Syntax Rules::, for documentation. 360 361 -- Scheme Syntax: lambda formals body 362 *Note Lambda::, for documentation. 363 364 -- Scheme Syntax: let bindings body 365 -- Scheme Syntax: let* bindings body 366 -- Scheme Syntax: letrec bindings body 367 -- Scheme Syntax: letrec* bindings body 368 *Note Local Bindings::, for documentation. 369 370 -- Scheme Syntax: let-values bindings body 371 -- Scheme Syntax: let*-values bindings body 372 *Note SRFI-11::, for documentation. 373 374 -- Scheme Syntax: begin expr1 expr2 ... 375 *Note begin::, for documentation. 376 377 -- Scheme Syntax: quote expr 378 -- Scheme Syntax: quasiquote expr 379 -- Scheme Syntax: unquote expr 380 -- Scheme Syntax: unquote-splicing expr 381 *Note Expression Syntax::, for documentation. 382 383 -- Scheme Syntax: if test consequence [alternate] 384 -- Scheme Syntax: cond clause1 clause2 ... 385 -- Scheme Syntax: case key clause1 clause2 ... 386 *Note Conditionals::, for documentation. 387 388 -- Scheme Syntax: and expr ... 389 -- Scheme Syntax: or expr ... 390 *Note and or::, for documentation. 391 392 -- Scheme Procedure: eq? x y 393 -- Scheme Procedure: eqv? x y 394 -- Scheme Procedure: equal? x y 395 -- Scheme Procedure: symbol=? symbol1 symbol2 ... 396 *Note Equality::, for documentation. 397 398 ‘symbol=?’ is identical to ‘eq?’. 399 400 -- Scheme Procedure: complex? z 401 *Note Complex Numbers::, for documentation. 402 403 -- Scheme Procedure: real-part z 404 -- Scheme Procedure: imag-part z 405 -- Scheme Procedure: make-rectangular real_part imaginary_part 406 -- Scheme Procedure: make-polar x y 407 -- Scheme Procedure: magnitude z 408 -- Scheme Procedure: angle z 409 *Note Complex::, for documentation. 410 411 -- Scheme Procedure: sqrt z 412 -- Scheme Procedure: exp z 413 -- Scheme Procedure: expt z1 z2 414 -- Scheme Procedure: log z 415 -- Scheme Procedure: sin z 416 -- Scheme Procedure: cos z 417 -- Scheme Procedure: tan z 418 -- Scheme Procedure: asin z 419 -- Scheme Procedure: acos z 420 -- Scheme Procedure: atan z 421 *Note Scientific::, for documentation. 422 423 -- Scheme Procedure: real? x 424 -- Scheme Procedure: rational? x 425 -- Scheme Procedure: numerator x 426 -- Scheme Procedure: denominator x 427 -- Scheme Procedure: rationalize x eps 428 *Note Reals and Rationals::, for documentation. 429 430 -- Scheme Procedure: exact? x 431 -- Scheme Procedure: inexact? x 432 -- Scheme Procedure: exact z 433 -- Scheme Procedure: inexact z 434 *Note Exactness::, for documentation. The ‘exact’ and ‘inexact’ 435 procedures are identical to the ‘inexact->exact’ and 436 ‘exact->inexact’ procedures provided by Guile’s code library. 437 438 -- Scheme Procedure: integer? x 439 *Note Integers::, for documentation. 440 441 -- Scheme Procedure: odd? n 442 -- Scheme Procedure: even? n 443 -- Scheme Procedure: gcd x ... 444 -- Scheme Procedure: lcm x ... 445 -- Scheme Procedure: exact-integer-sqrt k 446 *Note Integer Operations::, for documentation. 447 448 -- Scheme Procedure: = 449 -- Scheme Procedure: < 450 -- Scheme Procedure: > 451 -- Scheme Procedure: <= 452 -- Scheme Procedure: >= 453 -- Scheme Procedure: zero? x 454 -- Scheme Procedure: positive? x 455 -- Scheme Procedure: negative? x 456 *Note Comparison::, for documentation. 457 458 -- Scheme Procedure: for-each f lst1 lst2 ... 459 *Note SRFI-1 Fold and Map::, for documentation. 460 461 -- Scheme Procedure: list elem ... 462 *Note List Constructors::, for documentation. 463 464 -- Scheme Procedure: length lst 465 -- Scheme Procedure: list-ref lst k 466 -- Scheme Procedure: list-tail lst k 467 *Note List Selection::, for documentation. 468 469 -- Scheme Procedure: append lst ... obj 470 -- Scheme Procedure: append 471 -- Scheme Procedure: reverse lst 472 *Note Append/Reverse::, for documentation. 473 474 -- Scheme Procedure: number->string n [radix] 475 -- Scheme Procedure: string->number str [radix] 476 *Note Conversion::, for documentation. 477 478 -- Scheme Procedure: string char ... 479 -- Scheme Procedure: make-string k [chr] 480 -- Scheme Procedure: list->string lst 481 *Note String Constructors::, for documentation. 482 483 -- Scheme Procedure: string->list str [start [end]] 484 *Note List/String Conversion::, for documentation. 485 486 -- Scheme Procedure: string-length str 487 -- Scheme Procedure: string-ref str k 488 -- Scheme Procedure: string-copy str [start [end]] 489 -- Scheme Procedure: substring str start [end] 490 *Note String Selection::, for documentation. 491 492 -- Scheme Procedure: string=? s1 s2 s3 ... 493 -- Scheme Procedure: string<? s1 s2 s3 ... 494 -- Scheme Procedure: string>? s1 s2 s3 ... 495 -- Scheme Procedure: string<=? s1 s2 s3 ... 496 -- Scheme Procedure: string>=? s1 s2 s3 ... 497 *Note String Comparison::, for documentation. 498 499 -- Scheme Procedure: string-append arg ... 500 *Note Reversing and Appending Strings::, for documentation. 501 502 -- Scheme Procedure: string-for-each proc s [start [end]] 503 *Note Mapping Folding and Unfolding::, for documentation. 504 505 -- Scheme Procedure: + z1 ... 506 -- Scheme Procedure: - z1 z2 ... 507 -- Scheme Procedure: * z1 ... 508 -- Scheme Procedure: / z1 z2 ... 509 -- Scheme Procedure: max x1 x2 ... 510 -- Scheme Procedure: min x1 x2 ... 511 -- Scheme Procedure: abs x 512 -- Scheme Procedure: truncate x 513 -- Scheme Procedure: floor x 514 -- Scheme Procedure: ceiling x 515 -- Scheme Procedure: round x 516 *Note Arithmetic::, for documentation. 517 518 -- Scheme Procedure: div x y 519 -- Scheme Procedure: mod x y 520 -- Scheme Procedure: div-and-mod x y 521 These procedures accept two real numbers X and Y, where the divisor 522 Y must be non-zero. ‘div’ returns the integer Q and ‘mod’ returns 523 the real number R such that X = Q*Y + R and 0 <= R < abs(Y). 524 ‘div-and-mod’ returns both Q and R, and is more efficient than 525 computing each separately. Note that when Y > 0, ‘div’ returns 526 floor(X/Y), otherwise it returns ceiling(X/Y). 527 528 (div 123 10) ⇒ 12 529 (mod 123 10) ⇒ 3 530 (div-and-mod 123 10) ⇒ 12 and 3 531 (div-and-mod 123 -10) ⇒ -12 and 3 532 (div-and-mod -123 10) ⇒ -13 and 7 533 (div-and-mod -123 -10) ⇒ 13 and 7 534 (div-and-mod -123.2 -63.5) ⇒ 2.0 and 3.8 535 (div-and-mod 16/3 -10/7) ⇒ -3 and 22/21 536 537 -- Scheme Procedure: div0 x y 538 -- Scheme Procedure: mod0 x y 539 -- Scheme Procedure: div0-and-mod0 x y 540 These procedures accept two real numbers X and Y, where the divisor 541 Y must be non-zero. ‘div0’ returns the integer Q and ‘mod0’ 542 returns the real number R such that X = Q*Y + R and -abs(Y/2) <= R 543 < abs(Y/2). ‘div0-and-mod0’ returns both Q and R, and is more 544 efficient than computing each separately. 545 546 Note that ‘div0’ returns X/Y rounded to the nearest integer. When 547 X/Y lies exactly half-way between two integers, the tie is broken 548 according to the sign of Y. If Y > 0, ties are rounded toward 549 positive infinity, otherwise they are rounded toward negative 550 infinity. This is a consequence of the requirement that -abs(Y/2) 551 <= R < abs(Y/2). 552 553 (div0 123 10) ⇒ 12 554 (mod0 123 10) ⇒ 3 555 (div0-and-mod0 123 10) ⇒ 12 and 3 556 (div0-and-mod0 123 -10) ⇒ -12 and 3 557 (div0-and-mod0 -123 10) ⇒ -12 and -3 558 (div0-and-mod0 -123 -10) ⇒ 12 and -3 559 (div0-and-mod0 -123.2 -63.5) ⇒ 2.0 and 3.8 560 (div0-and-mod0 16/3 -10/7) ⇒ -4 and -8/21 561 562 -- Scheme Procedure: real-valued? obj 563 -- Scheme Procedure: rational-valued? obj 564 -- Scheme Procedure: integer-valued? obj 565 These procedures return ‘#t’ if and only if their arguments can, 566 respectively, be coerced to a real, rational, or integer value 567 without a loss of numerical precision. 568 569 ‘real-valued?’ will return ‘#t’ for complex numbers whose imaginary 570 parts are zero. 571 572 -- Scheme Procedure: nan? x 573 -- Scheme Procedure: infinite? x 574 -- Scheme Procedure: finite? x 575 ‘nan?’ returns ‘#t’ if X is a NaN value, ‘#f’ otherwise. 576 ‘infinite?’ returns ‘#t’ if X is an infinite value, ‘#f’ otherwise. 577 ‘finite?’ returns ‘#t’ if X is neither infinite nor a NaN value, 578 otherwise it returns ‘#f’. Every real number satisfies exactly one 579 of these predicates. An exception is raised if X is not real. 580 581 -- Scheme Syntax: assert expr 582 Raises an ‘&assertion’ condition if EXPR evaluates to ‘#f’; 583 otherwise evaluates to the value of EXPR. 584 585 -- Scheme Procedure: error who message irritant1 ... 586 -- Scheme Procedure: assertion-violation who message irritant1 ... 587 These procedures raise compound conditions based on their 588 arguments: If WHO is not ‘#f’, the condition will include a ‘&who’ 589 condition whose ‘who’ field is set to WHO; a ‘&message’ condition 590 will be included with a ‘message’ field equal to MESSAGE; an 591 ‘&irritants’ condition will be included with its ‘irritants’ list 592 given by ‘irritant1 ...’. 593 594 ‘error’ produces a compound condition with the simple conditions 595 described above, as well as an ‘&error’ condition; 596 ‘assertion-violation’ produces one that includes an ‘&assertion’ 597 condition. 598 599 -- Scheme Procedure: vector-map proc v 600 -- Scheme Procedure: vector-for-each proc v 601 These procedures implement the ‘map’ and ‘for-each’ contracts over 602 vectors. 603 604 -- Scheme Procedure: vector arg ... 605 -- Scheme Procedure: vector? obj 606 -- Scheme Procedure: make-vector len 607 -- Scheme Procedure: make-vector len fill 608 -- Scheme Procedure: list->vector l 609 -- Scheme Procedure: vector->list v 610 *Note Vector Creation::, for documentation. 611 612 -- Scheme Procedure: vector-length vector 613 -- Scheme Procedure: vector-ref vector k 614 -- Scheme Procedure: vector-set! vector k obj 615 -- Scheme Procedure: vector-fill! v fill 616 *Note Vector Accessors::, for documentation. 617 618 -- Scheme Procedure: call-with-current-continuation proc 619 -- Scheme Procedure: call/cc proc 620 *Note Continuations::, for documentation. 621 622 -- Scheme Procedure: values arg ... 623 -- Scheme Procedure: call-with-values producer consumer 624 *Note Multiple Values::, for documentation. 625 626 -- Scheme Procedure: dynamic-wind in_guard thunk out_guard 627 *Note Dynamic Wind::, for documentation. 628 629 -- Scheme Procedure: apply proc arg ... arglst 630 *Note Fly Evaluation::, for documentation. 631 632 633File: guile.info, Node: rnrs unicode, Next: rnrs bytevectors, Prev: rnrs base, Up: R6RS Standard Libraries 634 6357.6.2.3 rnrs unicode 636.................... 637 638The ‘(rnrs unicode (6))’ library provides procedures for manipulating 639Unicode characters and strings. 640 641 -- Scheme Procedure: char-upcase char 642 -- Scheme Procedure: char-downcase char 643 -- Scheme Procedure: char-titlecase char 644 -- Scheme Procedure: char-foldcase char 645 These procedures translate their arguments from one Unicode 646 character set to another. ‘char-upcase’, ‘char-downcase’, and 647 ‘char-titlecase’ are identical to their counterparts in the Guile 648 core library; *Note Characters::, for documentation. 649 650 ‘char-foldcase’ returns the result of applying ‘char-upcase’ to its 651 argument, followed by ‘char-downcase’—except in the case of the 652 Turkic characters ‘U+0130’ and ‘U+0131’, for which the procedure 653 acts as the identity function. 654 655 -- Scheme Procedure: char-ci=? char1 char2 char3 ... 656 -- Scheme Procedure: char-ci<? char1 char2 char3 ... 657 -- Scheme Procedure: char-ci>? char1 char2 char3 ... 658 -- Scheme Procedure: char-ci<=? char1 char2 char3 ... 659 -- Scheme Procedure: char-ci>=? char1 char2 char3 ... 660 These procedures facilitate case-insensitive comparison of Unicode 661 characters. They are identical to the procedures provided by 662 Guile’s core library. *Note Characters::, for documentation. 663 664 -- Scheme Procedure: char-alphabetic? char 665 -- Scheme Procedure: char-numeric? char 666 -- Scheme Procedure: char-whitespace? char 667 -- Scheme Procedure: char-upper-case? char 668 -- Scheme Procedure: char-lower-case? char 669 -- Scheme Procedure: char-title-case? char 670 These procedures implement various Unicode character set 671 predicates. They are identical to the procedures provided by 672 Guile’s core library. *Note Characters::, for documentation. 673 674 -- Scheme Procedure: char-general-category char 675 *Note Characters::, for documentation. 676 677 -- Scheme Procedure: string-upcase string 678 -- Scheme Procedure: string-downcase string 679 -- Scheme Procedure: string-titlecase string 680 -- Scheme Procedure: string-foldcase string 681 These procedures perform Unicode case folding operations on their 682 input. *Note Alphabetic Case Mapping::, for documentation. 683 684 -- Scheme Procedure: string-ci=? string1 string2 string3 ... 685 -- Scheme Procedure: string-ci<? string1 string2 string3 ... 686 -- Scheme Procedure: string-ci>? string1 string2 string3 ... 687 -- Scheme Procedure: string-ci<=? string1 string2 string3 ... 688 -- Scheme Procedure: string-ci>=? string1 string2 string3 ... 689 These procedures perform case-insensitive comparison on their 690 input. *Note String Comparison::, for documentation. 691 692 -- Scheme Procedure: string-normalize-nfd string 693 -- Scheme Procedure: string-normalize-nfkd string 694 -- Scheme Procedure: string-normalize-nfc string 695 -- Scheme Procedure: string-normalize-nfkc string 696 These procedures perform Unicode string normalization operations on 697 their input. *Note String Comparison::, for documentation. 698 699 700File: guile.info, Node: rnrs bytevectors, Next: rnrs lists, Prev: rnrs unicode, Up: R6RS Standard Libraries 701 7027.6.2.4 rnrs bytevectors 703........................ 704 705The ‘(rnrs bytevectors (6))’ library provides procedures for working 706with blocks of binary data. This functionality is documented in its own 707section of the manual; *Note Bytevectors::. 708 709 710File: guile.info, Node: rnrs lists, Next: rnrs sorting, Prev: rnrs bytevectors, Up: R6RS Standard Libraries 711 7127.6.2.5 rnrs lists 713.................. 714 715The ‘(rnrs lists (6))’ library provides procedures additional procedures 716for working with lists. 717 718 -- Scheme Procedure: find proc list 719 This procedure is identical to the one defined in Guile’s SRFI-1 720 implementation. *Note SRFI-1 Searching::, for documentation. 721 722 -- Scheme Procedure: for-all proc list1 list2 ... 723 -- Scheme Procedure: exists proc list1 list2 ... 724 725 The ‘for-all’ procedure is identical to the ‘every’ procedure 726 defined by SRFI-1; the ‘exists’ procedure is identical to SRFI-1’s 727 ‘any’. *Note SRFI-1 Searching::, for documentation. 728 729 -- Scheme Procedure: filter proc list 730 -- Scheme Procedure: partition proc list 731 These procedures are identical to the ones provided by SRFI-1. 732 *Note List Modification::, for a description of ‘filter’; *Note 733 SRFI-1 Filtering and Partitioning::, for ‘partition’. 734 735 -- Scheme Procedure: fold-right combine nil list1 list2 ... 736 This procedure is identical the ‘fold-right’ procedure provided by 737 SRFI-1. *Note SRFI-1 Fold and Map::, for documentation. 738 739 -- Scheme Procedure: fold-left combine nil list1 list2 ... 740 This procedure is like ‘fold’ from SRFI-1, but COMBINE is called 741 with the seed as the first argument. *Note SRFI-1 Fold and Map::, 742 for documentation. 743 744 -- Scheme Procedure: remp proc list 745 -- Scheme Procedure: remove obj list 746 -- Scheme Procedure: remv obj list 747 -- Scheme Procedure: remq obj list 748 ‘remove’, ‘remv’, and ‘remq’ are identical to the ‘delete’, ‘delv’, 749 and ‘delq’ procedures provided by Guile’s core library, (*note List 750 Modification::). ‘remp’ is identical to the alternate ‘remove’ 751 procedure provided by SRFI-1; *Note SRFI-1 Deleting::. 752 753 -- Scheme Procedure: memp proc list 754 -- Scheme Procedure: member obj list 755 -- Scheme Procedure: memv obj list 756 -- Scheme Procedure: memq obj list 757 ‘member’, ‘memv’, and ‘memq’ are identical to the procedures 758 provided by Guile’s core library; *Note List Searching::, for their 759 documentation. ‘memp’ uses the specified predicate function ‘proc’ 760 to test elements of the list LIST—it behaves similarly to ‘find’, 761 except that it returns the first sublist of LIST whose ‘car’ 762 satisfies PROC. 763 764 -- Scheme Procedure: assp proc alist 765 -- Scheme Procedure: assoc obj alist 766 -- Scheme Procedure: assv obj alist 767 -- Scheme Procedure: assq obj alist 768 ‘assoc’, ‘assv’, and ‘assq’ are identical to the procedures 769 provided by Guile’s core library; *Note Alist Key Equality::, for 770 their documentation. ‘assp’ uses the specified predicate function 771 ‘proc’ to test keys in the association list ALIST. 772 773 -- Scheme Procedure: cons* obj1 ... obj 774 -- Scheme Procedure: cons* obj 775 This procedure is identical to the one exported by Guile’s core 776 library. *Note List Constructors::, for documentation. 777 778 779File: guile.info, Node: rnrs sorting, Next: rnrs control, Prev: rnrs lists, Up: R6RS Standard Libraries 780 7817.6.2.6 rnrs sorting 782.................... 783 784The ‘(rnrs sorting (6))’ library provides procedures for sorting lists 785and vectors. 786 787 -- Scheme Procedure: list-sort proc list 788 -- Scheme Procedure: vector-sort proc vector 789 These procedures return their input sorted in ascending order, 790 without modifying the original data. PROC must be a procedure that 791 takes two elements from the input list or vector as arguments, and 792 returns a true value if the first is “less” than the second, ‘#f’ 793 otherwise. ‘list-sort’ returns a list; ‘vector-sort’ returns a 794 vector. 795 796 Both ‘list-sort’ and ‘vector-sort’ are implemented in terms of the 797 ‘stable-sort’ procedure from Guile’s core library. *Note 798 Sorting::, for a discussion of the behavior of that procedure. 799 800 -- Scheme Procedure: vector-sort! proc vector 801 Performs a destructive, “in-place” sort of VECTOR, using PROC as 802 described above to determine an ascending ordering of elements. 803 ‘vector-sort!’ returns an unspecified value. 804 805 This procedure is implemented in terms of the ‘sort!’ procedure 806 from Guile’s core library. *Note Sorting::, for more information. 807 808 809File: guile.info, Node: rnrs control, Next: R6RS Records, Prev: rnrs sorting, Up: R6RS Standard Libraries 810 8117.6.2.7 rnrs control 812.................... 813 814The ‘(rnrs control (6))’ library provides syntactic forms useful for 815constructing conditional expressions and controlling the flow of 816execution. 817 818 -- Scheme Syntax: when test expression1 expression2 ... 819 -- Scheme Syntax: unless test expression1 expression2 ... 820 The ‘when’ form is evaluated by evaluating the specified TEST 821 expression; if the result is a true value, the EXPRESSIONs that 822 follow it are evaluated in order, and the value of the final 823 EXPRESSION becomes the value of the entire ‘when’ expression. 824 825 The ‘unless’ form behaves similarly, with the exception that the 826 specified EXPRESSIONs are only evaluated if the value of TEST is 827 false. 828 829 -- Scheme Syntax: do ((variable init step) ...) (test expression ...) 830 command ... 831 This form is identical to the one provided by Guile’s core library. 832 *Note while do::, for documentation. 833 834 -- Scheme Syntax: case-lambda clause ... 835 This form is identical to the one provided by Guile’s core library. 836 *Note Case-lambda::, for documentation. 837 838 839File: guile.info, Node: R6RS Records, Next: rnrs records syntactic, Prev: rnrs control, Up: R6RS Standard Libraries 840 8417.6.2.8 R6RS Records 842.................... 843 844The manual sections below describe Guile’s implementation of R6RS 845records, which provide support for user-defined data types. The R6RS 846records API provides a superset of the features provided by Guile’s 847“native” records, as well as those of the SRFI-9 records API; *Note 848Records::, and *note SRFI-9 Records::, for a description of those 849interfaces. 850 851 As with SRFI-9 and Guile’s native records, R6RS records are 852constructed using a record-type descriptor that specifies attributes 853like the record’s name, its fields, and the mutability of those fields. 854 855 R6RS records extend this framework to support single inheritance via 856the specification of a “parent” type for a record type at definition 857time. Accessors and mutator procedures for the fields of a parent type 858may be applied to records of a subtype of this parent. A record type 859may be “sealed”, in which case it cannot be used as the parent of 860another record type. 861 862 The inheritance mechanism for record types also informs the process 863of initializing the fields of a record and its parents. Constructor 864procedures that generate new instances of a record type are obtained 865from a record constructor descriptor, which encapsulates the record-type 866descriptor of the record to be constructed along with a “protocol” 867procedure that defines how constructors for record subtypes delegate to 868the constructors of their parent types. 869 870 A protocol is a procedure used by the record system at construction 871time to bind arguments to the fields of the record being constructed. 872The protocol procedure is passed a procedure N that accepts the 873arguments required to construct the record’s parent type; this 874procedure, when invoked, will return a procedure P that accepts the 875arguments required to construct a new instance of the record type itself 876and returns a new instance of the record type. 877 878 The protocol should in turn return a procedure that uses N and P to 879initialize the fields of the record type and its parent type(s). This 880procedure will be the constructor returned by 881 882 As a trivial example, consider the hypothetical record type ‘pixel’, 883which encapsulates an x-y location on a screen, and ‘voxel’, which has 884‘pixel’ as its parent type and stores an additional coordinate. The 885following protocol produces a constructor procedure that accepts all 886three coordinates, uses the first two to initialize the fields of 887‘pixel’, and binds the third to the single field of ‘voxel’. 888 889 (lambda (n) 890 (lambda (x y z) 891 (let ((p (n x y))) 892 (p z)))) 893 894 It may be helpful to think of protocols as “constructor factories” 895that produce chains of delegating constructors glued together by the 896helper procedure N. 897 898 An R6RS record type may be declared to be “nongenerative” via the use 899of a unique generated or user-supplied symbol—or “uid”—such that 900subsequent record type declarations with the same uid and attributes 901will return the previously-declared record-type descriptor. 902 903 R6RS record types may also be declared to be “opaque”, in which case 904the various predicates and introspection procedures defined in ‘(rnrs 905records introspection)’ will behave as if records of this type are not 906records at all. 907 908 Note that while the R6RS records API shares much of its namespace 909with both the SRFI-9 and native Guile records APIs, it is not currently 910compatible with either. 911 912 913File: guile.info, Node: rnrs records syntactic, Next: rnrs records procedural, Prev: R6RS Records, Up: R6RS Standard Libraries 914 9157.6.2.9 rnrs records syntactic 916.............................. 917 918The ‘(rnrs records syntactic (6))’ library exports the syntactic API for 919working with R6RS records. 920 921 -- Scheme Syntax: define-record-type name-spec record-clause ... 922 Defines a new record type, introducing bindings for a record-type 923 descriptor, a record constructor descriptor, a constructor 924 procedure, a record predicate, and accessor and mutator procedures 925 for the new record type’s fields. 926 927 NAME-SPEC must either be an identifier or must take the form 928 ‘(record-name constructor-name predicate-name)’, where RECORD-NAME, 929 CONSTRUCTOR-NAME, and PREDICATE-NAME are all identifiers and 930 specify the names to which, respectively, the record-type 931 descriptor, constructor, and predicate procedures will be bound. 932 If NAME-SPEC is only an identifier, it specifies the name to which 933 the generated record-type descriptor will be bound. 934 935 Each RECORD-CLAUSE must be one of the following: 936 937 • ‘(fields field-spec*)’, where each FIELD-SPEC specifies a 938 field of the new record type and takes one of the following 939 forms: 940 • ‘(immutable field-name accessor-name)’, which specifies 941 an immutable field with the name FIELD-NAME and binds an 942 accessor procedure for it to the name given by 943 ACCESSOR-NAME 944 • ‘(mutable field-name accessor-name mutator-name)’, which 945 specifies a mutable field with the name FIELD-NAME and 946 binds accessor and mutator procedures to ACCESSOR-NAME 947 and MUTATOR-NAME, respectively 948 • ‘(immutable field-name)’, which specifies an immutable 949 field with the name FIELD-NAME; an accessor procedure for 950 it will be created and named by appending record name and 951 FIELD-NAME with a hyphen separator 952 • ‘(mutable field-name’), which specifies a mutable field 953 with the name FIELD-NAME; an accessor procedure for it 954 will be created and named as described above; a mutator 955 procedure will also be created and named by appending 956 ‘-set!’ to the accessor name 957 • ‘field-name’, which specifies an immutable field with the 958 name FIELD-NAME; an access procedure for it will be 959 created and named as described above 960 • ‘(parent parent-name)’, where PARENT-NAME is a symbol giving 961 the name of the record type to be used as the parent of the 962 new record type 963 • ‘(protocol expression)’, where EXPRESSION evaluates to a 964 protocol procedure which behaves as described above, and is 965 used to create a record constructor descriptor for the new 966 record type 967 • ‘(sealed sealed?)’, where SEALED? is a boolean value that 968 specifies whether or not the new record type is sealed 969 • ‘(opaque opaque?)’, where OPAQUE? is a boolean value that 970 specifies whether or not the new record type is opaque 971 • ‘(nongenerative [uid])’, which specifies that the record type 972 is nongenerative via the optional uid UID. If UID is not 973 specified, a unique uid will be generated at expansion time 974 • ‘(parent-rtd parent-rtd parent-cd)’, a more explicit form of 975 the ‘parent’ form above; PARENT-RTD and PARENT-CD should 976 evaluate to a record-type descriptor and a record constructor 977 descriptor, respectively 978 979 -- Scheme Syntax: record-type-descriptor record-name 980 Evaluates to the record-type descriptor associated with the type 981 specified by RECORD-NAME. 982 983 -- Scheme Syntax: record-constructor-descriptor record-name 984 Evaluates to the record-constructor descriptor associated with the 985 type specified by RECORD-NAME. 986 987 988File: guile.info, Node: rnrs records procedural, Next: rnrs records inspection, Prev: rnrs records syntactic, Up: R6RS Standard Libraries 989 9907.6.2.10 rnrs records procedural 991................................ 992 993The ‘(rnrs records procedural (6))’ library exports the procedural API 994for working with R6RS records. 995 996 -- Scheme Procedure: make-record-type-descriptor name parent uid 997 sealed? opaque? fields 998 Returns a new record-type descriptor with the specified 999 characteristics: NAME must be a symbol giving the name of the new 1000 record type; PARENT must be either ‘#f’ or a non-sealed record-type 1001 descriptor for the returned record type to extend; UID must be 1002 either ‘#f’, indicating that the record type is generative, or a 1003 symbol giving the type’s nongenerative uid; SEALED? and OPAQUE? 1004 must be boolean values that specify the sealedness and opaqueness 1005 of the record type; FIELDS must be a vector of zero or more field 1006 specifiers of the form ‘(mutable name)’ or ‘(immutable name)’, 1007 where name is a symbol giving a name for the field. 1008 1009 If UID is not ‘#f’, it must be a symbol 1010 1011 -- Scheme Procedure: record-type-descriptor? obj 1012 Returns ‘#t’ if OBJ is a record-type descriptor, ‘#f’ otherwise. 1013 1014 -- Scheme Procedure: make-record-constructor-descriptor rtd 1015 parent-constructor-descriptor protocol 1016 Returns a new record constructor descriptor that can be used to 1017 produce constructors for the record type specified by the 1018 record-type descriptor RTD and whose delegation and binding 1019 behavior are specified by the protocol procedure PROTOCOL. 1020 1021 PARENT-CONSTRUCTOR-DESCRIPTOR specifies a record constructor 1022 descriptor for the parent type of RTD, if one exists. If RTD 1023 represents a base type, then PARENT-CONSTRUCTOR-DESCRIPTOR must be 1024 ‘#f’. If RTD is an extension of another type, 1025 PARENT-CONSTRUCTOR-DESCRIPTOR may still be ‘#f’, but protocol must 1026 also be ‘#f’ in this case. 1027 1028 -- Scheme Procedure: record-constructor rcd 1029 Returns a record constructor procedure by invoking the protocol 1030 defined by the record-constructor descriptor RCD. 1031 1032 -- Scheme Procedure: record-predicate rtd 1033 Returns the record predicate procedure for the record-type 1034 descriptor RTD. 1035 1036 -- Scheme Procedure: record-accessor rtd k 1037 Returns the record field accessor procedure for the Kth field of 1038 the record-type descriptor RTD. 1039 1040 -- Scheme Procedure: record-mutator rtd k 1041 Returns the record field mutator procedure for the Kth field of the 1042 record-type descriptor RTD. An ‘&assertion’ condition will be 1043 raised if this field is not mutable. 1044 1045 1046File: guile.info, Node: rnrs records inspection, Next: rnrs exceptions, Prev: rnrs records procedural, Up: R6RS Standard Libraries 1047 10487.6.2.11 rnrs records inspection 1049................................ 1050 1051The ‘(rnrs records inspection (6))’ library provides procedures useful 1052for accessing metadata about R6RS records. 1053 1054 -- Scheme Procedure: record? obj 1055 Return ‘#t’ if the specified object is a non-opaque R6RS record, 1056 ‘#f’ otherwise. 1057 1058 -- Scheme Procedure: record-rtd record 1059 Returns the record-type descriptor for RECORD. An ‘&assertion’ is 1060 raised if RECORD is opaque. 1061 1062 -- Scheme Procedure: record-type-name rtd 1063 Returns the name of the record-type descriptor RTD. 1064 1065 -- Scheme Procedure: record-type-parent rtd 1066 Returns the parent of the record-type descriptor RTD, or ‘#f’ if it 1067 has none. 1068 1069 -- Scheme Procedure: record-type-uid rtd 1070 Returns the uid of the record-type descriptor RTD, or ‘#f’ if it 1071 has none. 1072 1073 -- Scheme Procedure: record-type-generative? rtd 1074 Returns ‘#t’ if the record-type descriptor RTD is generative, ‘#f’ 1075 otherwise. 1076 1077 -- Scheme Procedure: record-type-sealed? rtd 1078 Returns ‘#t’ if the record-type descriptor RTD is sealed, ‘#f’ 1079 otherwise. 1080 1081 -- Scheme Procedure: record-type-opaque? rtd 1082 Returns ‘#t’ if the record-type descriptor RTD is opaque, ‘#f’ 1083 otherwise. 1084 1085 -- Scheme Procedure: record-type-field-names rtd 1086 Returns a vector of symbols giving the names of the fields defined 1087 by the record-type descriptor RTD (and not any of its sub- or 1088 supertypes). 1089 1090 -- Scheme Procedure: record-field-mutable? rtd k 1091 Returns ‘#t’ if the field at index K of the record-type descriptor 1092 RTD (and not any of its sub- or supertypes) is mutable. 1093 1094 1095File: guile.info, Node: rnrs exceptions, Next: rnrs conditions, Prev: rnrs records inspection, Up: R6RS Standard Libraries 1096 10977.6.2.12 rnrs exceptions 1098........................ 1099 1100The ‘(rnrs exceptions (6))’ library provides functionality related to 1101signaling and handling exceptional situations. This functionality 1102re-exports Guile’s core exception-handling primitives. *Note 1103Exceptions::, for a full discussion. *Note SRFI-34::, for a similar 1104pre-R6RS facility. In Guile, SRFI-34, SRFI-35, and R6RS exception 1105handling are all built on the same core facilities, and so are 1106interoperable. 1107 1108 -- Scheme Procedure: with-exception-handler handler thunk 1109 *Note Raising and Handling Exceptions::, for more information on 1110 ‘with-exception-handler’. 1111 1112 -- Scheme Syntax: guard (variable clause1 clause2 ...) body 1113 Evaluates the expression given by BODY, first creating an ad hoc 1114 exception handler that binds a raised exception to VARIABLE and 1115 then evaluates the specified CLAUSEs as if they were part of a 1116 ‘cond’ expression, with the value of the first matching clause 1117 becoming the value of the ‘guard’ expression (*note 1118 Conditionals::). If none of the clause’s test expressions 1119 evaluates to ‘#t’, the exception is re-raised, with the exception 1120 handler that was current before the evaluation of the ‘guard’ form. 1121 1122 For example, the expression 1123 1124 (guard (ex ((eq? ex 'foo) 'bar) ((eq? ex 'bar) 'baz)) 1125 (raise 'bar)) 1126 1127 evaluates to ‘baz’. 1128 1129 -- Scheme Procedure: raise obj 1130 Equivalent to core Guile ‘(raise-exception OBJ)’. *Note Raising 1131 and Handling Exceptions::. (Unfortunately, ‘raise’ is already 1132 bound to a different function in core Guile. *Note Signals::.) 1133 1134 -- Scheme Procedure: raise-continuable obj 1135 Equivalent to core Guile ‘(raise-exception OBJ #:continuable? #t)’. 1136 *Note Raising and Handling Exceptions::. 1137 1138 1139File: guile.info, Node: rnrs conditions, Next: R6RS I/O Conditions, Prev: rnrs exceptions, Up: R6RS Standard Libraries 1140 11417.6.2.13 rnrs conditions 1142........................ 1143 1144The ‘(rnrs condition (6))’ library provides forms and procedures for 1145constructing new condition types, as well as a library of pre-defined 1146condition types that represent a variety of common exceptional 1147situations. Conditions are records of a subtype of the ‘&condition’ 1148record type, which is neither sealed nor opaque. *Note R6RS Records::. 1149 1150 Conditions may be manipulated singly, as “simple conditions”, or when 1151composed with other conditions to form “compound conditions”. Compound 1152conditions do not “nest”—constructing a new compound condition out of 1153existing compound conditions will “flatten” them into their component 1154simple conditions. For example, making a new condition out of a 1155‘&message’ condition and a compound condition that contains an 1156‘&assertion’ condition and another ‘&message’ condition will produce a 1157compound condition that contains two ‘&message’ conditions and one 1158‘&assertion’ condition. 1159 1160 The record type predicates and field accessors described below can 1161operate on either simple or compound conditions. In the latter case, 1162the predicate returns ‘#t’ if the compound condition contains a 1163component simple condition of the appropriate type; the field accessors 1164return the requisite fields from the first component simple condition 1165found to be of the appropriate type. 1166 1167 Guile’s R6RS layer uses core exception types from the ‘(ice-9 1168exceptions)’ module as the basis for its R6RS condition system. Guile 1169prefers to use the term “exception object” and “exception type” rather 1170than “condition” or “condition type”, but that’s just a naming 1171difference. Guile also has different names for the types in the 1172condition hierarchy. *Note Exception Objects::, for full details. 1173 1174 This library is quite similar to the SRFI-35 conditions module (*note 1175SRFI-35::). Among other minor differences, the ‘(rnrs conditions)’ 1176library features slightly different semantics around condition field 1177accessors, and comes with a larger number of pre-defined condition 1178types. The two APIs are compatible; the ‘condition?’ predicate from one 1179API will return ‘#t’ when applied to a condition object created in the 1180other. of the condition types are the same, also. 1181 1182 -- Condition Type: &condition 1183 -- Scheme Procedure: condition? obj 1184 The base record type for conditions. Known as ‘&exception’ in core 1185 Guile. 1186 1187 -- Scheme Procedure: condition condition1 ... 1188 -- Scheme Procedure: simple-conditions condition 1189 The ‘condition’ procedure creates a new compound condition out of 1190 its condition arguments, flattening any specified compound 1191 conditions into their component simple conditions as described 1192 above. 1193 1194 ‘simple-conditions’ returns a list of the component simple 1195 conditions of the compound condition ‘condition’, in the order in 1196 which they were specified at construction time. 1197 1198 -- Scheme Procedure: condition-predicate rtd 1199 -- Scheme Procedure: condition-accessor rtd proc 1200 These procedures return condition predicate and accessor procedures 1201 for the specified condition record type RTD. 1202 1203 -- Scheme Syntax: define-condition-type condition-type supertype 1204 constructor predicate field-spec ... 1205 Evaluates to a new record type definition for a condition type with 1206 the name CONDITION-TYPE that has the condition type SUPERTYPE as 1207 its parent. A default constructor, which binds its arguments to 1208 the fields of this type and its parent types, will be bound to the 1209 identifier CONSTRUCTOR; a condition predicate will be bound to 1210 PREDICATE. The fields of the new type, which are immutable, are 1211 specified by the FIELD-SPECs, each of which must be of the form: 1212 (field accessor) 1213 where FIELD gives the name of the field and ACCESSOR gives the name 1214 for a binding to an accessor procedure created for this field. 1215 1216 -- Condition Type: &message 1217 -- Scheme Procedure: make-message-condition message 1218 -- Scheme Procedure: message-condition? obj 1219 -- Scheme Procedure: condition-message condition 1220 A type that includes a message describing the condition that 1221 occurred. 1222 1223 -- Condition Type: &warning 1224 -- Scheme Procedure: make-warning 1225 -- Scheme Procedure: warning? obj 1226 A base type for representing non-fatal conditions during execution. 1227 1228 -- Condition Type: &serious 1229 -- Scheme Procedure: make-serious-condition 1230 -- Scheme Procedure: serious-condition? obj 1231 A base type for conditions representing errors serious enough that 1232 cannot be ignored. Known as ‘&error’ in core Guile. 1233 1234 -- Condition Type: &error 1235 -- Scheme Procedure: make-error 1236 -- Scheme Procedure: error? obj 1237 A base type for conditions representing errors. Known as 1238 ‘&external-error’ in core Guile. 1239 1240 -- Condition Type: &violation 1241 -- Scheme Procedure: make-violation 1242 -- Scheme Procedure: violation? 1243 A subtype of ‘&serious’ that can be used to represent violations of 1244 a language or library standard. Known as ‘&programming-error’ in 1245 core Guile. 1246 1247 -- Condition Type: &assertion 1248 -- Scheme Procedure: make-assertion-violation 1249 -- Scheme Procedure: assertion-violation? obj 1250 A subtype of ‘&violation’ that indicates an invalid call to a 1251 procedure. Known as ‘&assertion-failure’ in core Guile. 1252 1253 -- Condition Type: &irritants 1254 -- Scheme Procedure: make-irritants-condition irritants 1255 -- Scheme Procedure: irritants-condition? obj 1256 -- Scheme Procedure: condition-irritants condition 1257 A base type used for storing information about the causes of 1258 another condition in a compound condition. 1259 1260 -- Condition Type: &who 1261 -- Scheme Procedure: make-who-condition who 1262 -- Scheme Procedure: who-condition? obj 1263 -- Scheme Procedure: condition-who condition 1264 A base type used for storing the identity, a string or symbol, of 1265 the entity responsible for another condition in a compound 1266 condition. 1267 1268 -- Condition Type: &non-continuable 1269 -- Scheme Procedure: make-non-continuable-violation 1270 -- Scheme Procedure: non-continuable-violation? obj 1271 A subtype of ‘&violation’ used to indicate that an exception 1272 handler invoked by ‘raise’ has returned locally. 1273 1274 -- Condition Type: &implementation-restriction 1275 -- Scheme Procedure: make-implementation-restriction-violation 1276 -- Scheme Procedure: implementation-restriction-violation? obj 1277 A subtype of ‘&violation’ used to indicate a violation of an 1278 implementation restriction. 1279 1280 -- Condition Type: &lexical 1281 -- Scheme Procedure: make-lexical-violation 1282 -- Scheme Procedure: lexical-violation? obj 1283 A subtype of ‘&violation’ used to indicate a syntax violation at 1284 the level of the datum syntax. 1285 1286 -- Condition Type: &syntax 1287 -- Scheme Procedure: make-syntax-violation form subform 1288 -- Scheme Procedure: syntax-violation? obj 1289 -- Scheme Procedure: syntax-violation-form condition 1290 -- Scheme Procedure: syntax-violation-subform condition 1291 A subtype of ‘&violation’ that indicates a syntax violation. The 1292 FORM and SUBFORM fields, which must be datum values, indicate the 1293 syntactic form responsible for the condition. 1294 1295 -- Condition Type: &undefined 1296 -- Scheme Procedure: make-undefined-violation 1297 -- Scheme Procedure: undefined-violation? obj 1298 A subtype of ‘&violation’ that indicates a reference to an unbound 1299 identifier. Known as ‘&undefined-variable’ in core Guile. 1300 1301 1302File: guile.info, Node: R6RS I/O Conditions, Next: R6RS Transcoders, Prev: rnrs conditions, Up: R6RS Standard Libraries 1303 13047.6.2.14 I/O Conditions 1305....................... 1306 1307These condition types are exported by both the ‘(rnrs io ports (6))’ and 1308‘(rnrs io simple (6))’ libraries. 1309 1310 -- Condition Type: &i/o 1311 -- Scheme Procedure: make-i/o-error 1312 -- Scheme Procedure: i/o-error? obj 1313 A condition supertype for more specific I/O errors. 1314 1315 -- Condition Type: &i/o-read 1316 -- Scheme Procedure: make-i/o-read-error 1317 -- Scheme Procedure: i/o-read-error? obj 1318 A subtype of ‘&i/o’; represents read-related I/O errors. 1319 1320 -- Condition Type: &i/o-write 1321 -- Scheme Procedure: make-i/o-write-error 1322 -- Scheme Procedure: i/o-write-error? obj 1323 A subtype of ‘&i/o’; represents write-related I/O errors. 1324 1325 -- Condition Type: &i/o-invalid-position 1326 -- Scheme Procedure: make-i/o-invalid-position-error position 1327 -- Scheme Procedure: i/o-invalid-position-error? obj 1328 -- Scheme Procedure: i/o-error-position condition 1329 A subtype of ‘&i/o’; represents an error related to an attempt to 1330 set the file position to an invalid position. 1331 1332 -- Condition Type: &i/o-filename 1333 -- Scheme Procedure: make-io-filename-error filename 1334 -- Scheme Procedure: i/o-filename-error? obj 1335 -- Scheme Procedure: i/o-error-filename condition 1336 A subtype of ‘&i/o’; represents an error related to an operation on 1337 a named file. 1338 1339 -- Condition Type: &i/o-file-protection 1340 -- Scheme Procedure: make-i/o-file-protection-error filename 1341 -- Scheme Procedure: i/o-file-protection-error? obj 1342 A subtype of ‘&i/o-filename’; represents an error resulting from an 1343 attempt to access a named file for which the caller had 1344 insufficient permissions. 1345 1346 -- Condition Type: &i/o-file-is-read-only 1347 -- Scheme Procedure: make-i/o-file-is-read-only-error filename 1348 -- Scheme Procedure: i/o-file-is-read-only-error? obj 1349 A subtype of ‘&i/o-file-protection’; represents an error related to 1350 an attempt to write to a read-only file. 1351 1352 -- Condition Type: &i/o-file-already-exists 1353 -- Scheme Procedure: make-i/o-file-already-exists-error filename 1354 -- Scheme Procedure: i/o-file-already-exists-error? obj 1355 A subtype of ‘&i/o-filename’; represents an error related to an 1356 operation on an existing file that was assumed not to exist. 1357 1358 -- Condition Type: &i/o-file-does-not-exist 1359 -- Scheme Procedure: make-i/o-file-does-not-exist-error 1360 -- Scheme Procedure: i/o-file-does-not-exist-error? obj 1361 A subtype of ‘&i/o-filename’; represents an error related to an 1362 operation on a non-existent file that was assumed to exist. 1363 1364 -- Condition Type: &i/o-port 1365 -- Scheme Procedure: make-i/o-port-error port 1366 -- Scheme Procedure: i/o-port-error? obj 1367 -- Scheme Procedure: i/o-error-port condition 1368 A subtype of ‘&i/o’; represents an error related to an operation on 1369 the port PORT. 1370 1371 1372File: guile.info, Node: R6RS Transcoders, Next: rnrs io ports, Prev: R6RS I/O Conditions, Up: R6RS Standard Libraries 1373 13747.6.2.15 Transcoders 1375.................... 1376 1377The transcoder facilities are exported by ‘(rnrs io ports)’. 1378 1379 Several different Unicode encoding schemes describe standard ways to 1380encode characters and strings as byte sequences and to decode those 1381sequences. Within this document, a “codec” is an immutable Scheme 1382object that represents a Unicode or similar encoding scheme. 1383 1384 An “end-of-line style” is a symbol that, if it is not ‘none’, 1385describes how a textual port transcodes representations of line endings. 1386 1387 A “transcoder” is an immutable Scheme object that combines a codec 1388with an end-of-line style and a method for handling decoding errors. 1389Each transcoder represents some specific bidirectional (but not 1390necessarily lossless), possibly stateful translation between byte 1391sequences and Unicode characters and strings. Every transcoder can 1392operate in the input direction (bytes to characters) or in the output 1393direction (characters to bytes). A TRANSCODER parameter name means that 1394the corresponding argument must be a transcoder. 1395 1396 A “binary port” is a port that supports binary I/O, does not have an 1397associated transcoder and does not support textual I/O. A “textual port” 1398is a port that supports textual I/O, and does not support binary I/O. A 1399textual port may or may not have an associated transcoder. 1400 1401 -- Scheme Procedure: latin-1-codec 1402 -- Scheme Procedure: utf-8-codec 1403 -- Scheme Procedure: utf-16-codec 1404 1405 These are predefined codecs for the ISO 8859-1, UTF-8, and UTF-16 1406 encoding schemes. 1407 1408 A call to any of these procedures returns a value that is equal in 1409 the sense of ‘eqv?’ to the result of any other call to the same 1410 procedure. 1411 1412 -- Scheme Syntax: eol-style EOL-STYLE-SYMBOL 1413 1414 EOL-STYLE-SYMBOL should be a symbol whose name is one of ‘lf’, 1415 ‘cr’, ‘crlf’, ‘nel’, ‘crnel’, ‘ls’, and ‘none’. 1416 1417 The form evaluates to the corresponding symbol. If the name of 1418 EOL-STYLE-SYMBOL is not one of these symbols, the effect and result 1419 are implementation-dependent; in particular, the result may be an 1420 eol-style symbol acceptable as an EOL-STYLE argument to 1421 ‘make-transcoder’. Otherwise, an exception is raised. 1422 1423 All eol-style symbols except ‘none’ describe a specific line-ending 1424 encoding: 1425 1426 ‘lf’ 1427 linefeed 1428 ‘cr’ 1429 carriage return 1430 ‘crlf’ 1431 carriage return, linefeed 1432 ‘nel’ 1433 next line 1434 ‘crnel’ 1435 carriage return, next line 1436 ‘ls’ 1437 line separator 1438 1439 For a textual port with a transcoder, and whose transcoder has an 1440 eol-style symbol ‘none’, no conversion occurs. For a textual input 1441 port, any eol-style symbol other than ‘none’ means that all of the 1442 above line-ending encodings are recognized and are translated into 1443 a single linefeed. For a textual output port, ‘none’ and ‘lf’ are 1444 equivalent. Linefeed characters are encoded according to the 1445 specified eol-style symbol, and all other characters that 1446 participate in possible line endings are encoded as is. 1447 1448 Note: Only the name of EOL-STYLE-SYMBOL is significant. 1449 1450 -- Scheme Procedure: native-eol-style 1451 Returns the default end-of-line style of the underlying platform, 1452 e.g., ‘lf’ on Unix and ‘crlf’ on Windows. 1453 1454 -- Condition Type: &i/o-decoding 1455 -- Scheme Procedure: make-i/o-decoding-error port 1456 -- Scheme Procedure: i/o-decoding-error? obj 1457 This condition type could be defined by 1458 1459 (define-condition-type &i/o-decoding &i/o-port 1460 make-i/o-decoding-error i/o-decoding-error?) 1461 1462 An exception with this type is raised when one of the operations 1463 for textual input from a port encounters a sequence of bytes that 1464 cannot be translated into a character or string by the input 1465 direction of the port’s transcoder. 1466 1467 When such an exception is raised, the port’s position is past the 1468 invalid encoding. 1469 1470 -- Condition Type: &i/o-encoding 1471 -- Scheme Procedure: make-i/o-encoding-error port char 1472 -- Scheme Procedure: i/o-encoding-error? obj 1473 -- Scheme Procedure: i/o-encoding-error-char condition 1474 This condition type could be defined by 1475 1476 (define-condition-type &i/o-encoding &i/o-port 1477 make-i/o-encoding-error i/o-encoding-error? 1478 (char i/o-encoding-error-char)) 1479 1480 An exception with this type is raised when one of the operations 1481 for textual output to a port encounters a character that cannot be 1482 translated into bytes by the output direction of the port’s 1483 transcoder. CHAR is the character that could not be encoded. 1484 1485 -- Scheme Syntax: error-handling-mode ERROR-HANDLING-MODE-SYMBOL 1486 ERROR-HANDLING-MODE-SYMBOL should be a symbol whose name is one of 1487 ‘ignore’, ‘raise’, and ‘replace’. The form evaluates to the 1488 corresponding symbol. If ERROR-HANDLING-MODE-SYMBOL is not one of 1489 these identifiers, effect and result are implementation-dependent: 1490 The result may be an error-handling-mode symbol acceptable as a 1491 HANDLING-MODE argument to ‘make-transcoder’. If it is not 1492 acceptable as a HANDLING-MODE argument to ‘make-transcoder’, an 1493 exception is raised. 1494 1495 Note: Only the name of ERROR-HANDLING-MODE-SYMBOL is 1496 significant. 1497 1498 The error-handling mode of a transcoder specifies the behavior of 1499 textual I/O operations in the presence of encoding or decoding 1500 errors. 1501 1502 If a textual input operation encounters an invalid or incomplete 1503 character encoding, and the error-handling mode is ‘ignore’, an 1504 appropriate number of bytes of the invalid encoding are ignored and 1505 decoding continues with the following bytes. 1506 1507 If the error-handling mode is ‘replace’, the replacement character 1508 U+FFFD is injected into the data stream, an appropriate number of 1509 bytes are ignored, and decoding continues with the following bytes. 1510 1511 If the error-handling mode is ‘raise’, an exception with condition 1512 type ‘&i/o-decoding’ is raised. 1513 1514 If a textual output operation encounters a character it cannot 1515 encode, and the error-handling mode is ‘ignore’, the character is 1516 ignored and encoding continues with the next character. If the 1517 error-handling mode is ‘replace’, a codec-specific replacement 1518 character is emitted by the transcoder, and encoding continues with 1519 the next character. The replacement character is U+FFFD for 1520 transcoders whose codec is one of the Unicode encodings, but is the 1521 ‘?’ character for the Latin-1 encoding. If the error-handling mode 1522 is ‘raise’, an exception with condition type ‘&i/o-encoding’ is 1523 raised. 1524 1525 -- Scheme Procedure: make-transcoder codec 1526 -- Scheme Procedure: make-transcoder codec eol-style 1527 -- Scheme Procedure: make-transcoder codec eol-style handling-mode 1528 CODEC must be a codec; EOL-STYLE, if present, an eol-style symbol; 1529 and HANDLING-MODE, if present, an error-handling-mode symbol. 1530 1531 EOL-STYLE may be omitted, in which case it defaults to the native 1532 end-of-line style of the underlying platform. HANDLING-MODE may be 1533 omitted, in which case it defaults to ‘replace’. The result is a 1534 transcoder with the behavior specified by its arguments. 1535 1536 -- Scheme procedure: native-transcoder 1537 Returns an implementation-dependent transcoder that represents a 1538 possibly locale-dependent “native” transcoding. 1539 1540 -- Scheme Procedure: transcoder-codec transcoder 1541 -- Scheme Procedure: transcoder-eol-style transcoder 1542 -- Scheme Procedure: transcoder-error-handling-mode transcoder 1543 These are accessors for transcoder objects; when applied to a 1544 transcoder returned by ‘make-transcoder’, they return the CODEC, 1545 EOL-STYLE, and HANDLING-MODE arguments, respectively. 1546 1547 -- Scheme Procedure: bytevector->string bytevector transcoder 1548 Returns the string that results from transcoding the BYTEVECTOR 1549 according to the input direction of the transcoder. 1550 1551 -- Scheme Procedure: string->bytevector string transcoder 1552 Returns the bytevector that results from transcoding the STRING 1553 according to the output direction of the transcoder. 1554 1555 1556File: guile.info, Node: rnrs io ports, Next: R6RS File Ports, Prev: R6RS Transcoders, Up: R6RS Standard Libraries 1557 15587.6.2.16 rnrs io ports 1559...................... 1560 1561Guile’s binary and textual port interface was heavily inspired by R6RS, 1562so many R6RS port interfaces are documented elsewhere. Note that R6RS 1563ports are not disjoint from Guile’s native ports, so Guile-specific 1564procedures will work on ports created using the R6RS API, and vice 1565versa. Also note that in Guile, all ports are both textual and binary. 1566*Note Input and Output::, for more on Guile’s core port API. The R6RS 1567ports module wraps Guile’s I/O routines in a helper that will translate 1568native Guile exceptions to R6RS conditions; *Note R6RS I/O Conditions::, 1569for more. *Note R6RS File Ports::, for documentation on the R6RS file 1570port interface. 1571 1572 _Note_: The implementation of this R6RS API is not complete yet. 1573 1574 -- Scheme Procedure: eof-object? obj 1575 *Note Binary I/O::, for documentation. 1576 1577 -- Scheme Procedure: eof-object 1578 Return the end-of-file (EOF) object. 1579 1580 (eof-object? (eof-object)) 1581 ⇒ #t 1582 1583 -- Scheme Procedure: port? obj 1584 -- Scheme Procedure: input-port? obj 1585 -- Scheme Procedure: output-port? obj 1586 -- Scheme Procedure: call-with-port port proc 1587 *Note Ports::, for documentation. 1588 1589 -- Scheme Procedure: port-transcoder port 1590 Return a transcoder associated with the encoding of PORT. *Note 1591 Encoding::, and *Note R6RS Transcoders::. 1592 1593 -- Scheme Procedure: binary-port? port 1594 Return ‘#t’ if PORT appears to be a binary port, else return ‘#f’. 1595 Note that Guile does not currently distinguish between binary and 1596 textual ports, so this predicate is not a reliable indicator of 1597 whether the port was created as a binary port. Currently, it 1598 returns ‘#t’ if and only if the port encoding is “ISO-8859-1”, 1599 because Guile uses this encoding when creating a binary port. 1600 *Note Encoding::, for more details. 1601 1602 -- Scheme Procedure: textual-port? port 1603 Return ‘#t’ if PORT appears to be a textual port, else return ‘#f’. 1604 Note that Guile does not currently distinguish between binary and 1605 textual ports, so this predicate is not a reliable indicator of 1606 whether the port was created as a textual port. Currently, it 1607 always returns ‘#t’, because all ports can be used for textual I/O 1608 in Guile. *Note Encoding::, for more details. 1609 1610 -- Scheme Procedure: transcoded-port binary-port transcoder 1611 The ‘transcoded-port’ procedure returns a new textual port with the 1612 specified TRANSCODER. Otherwise the new textual port’s state is 1613 largely the same as that of BINARY-PORT. If BINARY-PORT is an 1614 input port, the new textual port will be an input port and will 1615 transcode the bytes that have not yet been read from BINARY-PORT. 1616 If BINARY-PORT is an output port, the new textual port will be an 1617 output port and will transcode output characters into bytes that 1618 are written to the byte sink represented by BINARY-PORT. 1619 1620 As a side effect, however, ‘transcoded-port’ closes BINARY-PORT in 1621 a special way that allows the new textual port to continue to use 1622 the byte source or sink represented by BINARY-PORT, even though 1623 BINARY-PORT itself is closed and cannot be used by the input and 1624 output operations described in this chapter. 1625 1626 -- Scheme Procedure: port-position port 1627 Equivalent to ‘(seek PORT 0 SEEK_CUR)’. *Note Random Access::. 1628 1629 -- Scheme Procedure: port-has-port-position? port 1630 Return ‘#t’ is PORT supports ‘port-position’. 1631 1632 -- Scheme Procedure: set-port-position! port offset 1633 Equivalent to ‘(seek PORT OFFSET SEEK_SET)’. *Note Random 1634 Access::. 1635 1636 -- Scheme Procedure: port-has-set-port-position!? port 1637 Return ‘#t’ is PORT supports ‘set-port-position!’. 1638 1639 -- Scheme Procedure: port-eof? input-port 1640 Equivalent to ‘(eof-object? (lookahead-u8 INPUT-PORT))’. 1641 1642 -- Scheme Procedure: standard-input-port 1643 -- Scheme Procedure: standard-output-port 1644 -- Scheme Procedure: standard-error-port 1645 Returns a fresh binary input port connected to standard input, or a 1646 binary output port connected to the standard output or standard 1647 error, respectively. Whether the port supports the ‘port-position’ 1648 and ‘set-port-position!’ operations is implementation-dependent. 1649 1650 -- Scheme Procedure: current-input-port 1651 -- Scheme Procedure: current-output-port 1652 -- Scheme Procedure: current-error-port 1653 *Note Default Ports::. 1654 1655 -- Scheme Procedure: open-bytevector-input-port bv [transcoder] 1656 -- Scheme Procedure: open-bytevector-output-port [transcoder] 1657 *Note Bytevector Ports::. 1658 1659 -- Scheme Procedure: make-custom-binary-input-port id read! 1660 get-position set-position! close 1661 -- Scheme Procedure: make-custom-binary-output-port id write! 1662 get-position set-position! close 1663 -- Scheme Procedure: make-custom-binary-input/output-port id read! 1664 write! get-position set-position! close 1665 *Note Custom Ports::. 1666 1667 -- Scheme Procedure: get-u8 port 1668 -- Scheme Procedure: lookahead-u8 port 1669 -- Scheme Procedure: get-bytevector-n port count 1670 -- Scheme Procedure: get-bytevector-n! port bv start count 1671 -- Scheme Procedure: get-bytevector-some port 1672 -- Scheme Procedure: get-bytevector-all port 1673 -- Scheme Procedure: put-u8 port octet 1674 -- Scheme Procedure: put-bytevector port bv [start [count]] 1675 *Note Binary I/O::. 1676 1677 -- Scheme Procedure: get-char textual-input-port 1678 -- Scheme Procedure: lookahead-char textual-input-port 1679 -- Scheme Procedure: get-string-n textual-input-port count 1680 -- Scheme Procedure: get-string-n! textual-input-port string start 1681 count 1682 -- Scheme Procedure: get-string-all textual-input-port 1683 -- Scheme Procedure: get-line textual-input-port 1684 -- Scheme Procedure: put-char port char 1685 -- Scheme Procedure: put-string port string [start [count]] 1686 *Note Textual I/O::. 1687 1688 -- Scheme Procedure: get-datum textual-input-port count 1689 Reads an external representation from TEXTUAL-INPUT-PORT and 1690 returns the datum it represents. The ‘get-datum’ procedure returns 1691 the next datum that can be parsed from the given 1692 TEXTUAL-INPUT-PORT, updating TEXTUAL-INPUT-PORT to point exactly 1693 past the end of the external representation of the object. 1694 1695 Any _interlexeme space_ (comment or whitespace, *note Scheme 1696 Syntax::) in the input is first skipped. If an end of file occurs 1697 after the interlexeme space, the end-of-file object is returned. 1698 1699 If a character inconsistent with an external representation is 1700 encountered in the input, an exception with condition types 1701 ‘&lexical’ and ‘&i/o-read’ is raised. Also, if the end of file is 1702 encountered after the beginning of an external representation, but 1703 the external representation is incomplete and therefore cannot be 1704 parsed, an exception with condition types ‘&lexical’ and 1705 ‘&i/o-read’ is raised. 1706 1707 -- Scheme Procedure: put-datum textual-output-port datum 1708 DATUM should be a datum value. The ‘put-datum’ procedure writes an 1709 external representation of DATUM to TEXTUAL-OUTPUT-PORT. The 1710 specific external representation is implementation-dependent. 1711 However, whenever possible, an implementation should produce a 1712 representation for which ‘get-datum’, when reading the 1713 representation, will return an object equal (in the sense of 1714 ‘equal?’) to DATUM. 1715 1716 Note: Not all datums may allow producing an external 1717 representation for which ‘get-datum’ will produce an object 1718 that is equal to the original. Specifically, NaNs contained 1719 in DATUM may make this impossible. 1720 1721 Note: The ‘put-datum’ procedure merely writes the external 1722 representation, but no trailing delimiter. If ‘put-datum’ is 1723 used to write several subsequent external representations to 1724 an output port, care should be taken to delimit them properly 1725 so they can be read back in by subsequent calls to 1726 ‘get-datum’. 1727 1728 -- Scheme Procedure: flush-output-port port 1729 *Note Buffering::, for documentation on ‘force-output’. 1730 1731 1732File: guile.info, Node: R6RS File Ports, Next: rnrs io simple, Prev: rnrs io ports, Up: R6RS Standard Libraries 1733 17347.6.2.17 R6RS File Ports 1735........................ 1736 1737The facilities described in this section are exported by the ‘(rnrs io 1738ports)’ module. 1739 1740 -- Scheme Syntax: buffer-mode BUFFER-MODE-SYMBOL 1741 BUFFER-MODE-SYMBOL must be a symbol whose name is one of ‘none’, 1742 ‘line’, and ‘block’. The result is the corresponding symbol, and 1743 specifies the associated buffer mode. *Note Buffering::, for a 1744 discussion of these different buffer modes. To control the amount 1745 of buffering, use ‘setvbuf’ instead. Note that only the name of 1746 BUFFER-MODE-SYMBOL is significant. 1747 1748 *Note Buffering::, for a discussion of port buffering. 1749 1750 -- Scheme Procedure: buffer-mode? obj 1751 Returns ‘#t’ if the argument is a valid buffer-mode symbol, and 1752 returns ‘#f’ otherwise. 1753 1754 When opening a file, the various procedures accept a ‘file-options’ 1755object that encapsulates flags to specify how the file is to be opened. 1756A ‘file-options’ object is an enum-set (*note rnrs enums::) over the 1757symbols constituting valid file options. 1758 1759 A FILE-OPTIONS parameter name means that the corresponding argument 1760must be a file-options object. 1761 1762 -- Scheme Syntax: file-options FILE-OPTIONS-SYMBOL ... 1763 1764 Each FILE-OPTIONS-SYMBOL must be a symbol. 1765 1766 The ‘file-options’ syntax returns a file-options object that 1767 encapsulates the specified options. 1768 1769 When supplied to an operation that opens a file for output, the 1770 file-options object returned by ‘(file-options)’ specifies that the 1771 file is created if it does not exist and an exception with 1772 condition type ‘&i/o-file-already-exists’ is raised if it does 1773 exist. The following standard options can be included to modify 1774 the default behavior. 1775 1776 ‘no-create’ 1777 If the file does not already exist, it is not created; 1778 instead, an exception with condition type 1779 ‘&i/o-file-does-not-exist’ is raised. If the file already 1780 exists, the exception with condition type 1781 ‘&i/o-file-already-exists’ is not raised and the file is 1782 truncated to zero length. 1783 ‘no-fail’ 1784 If the file already exists, the exception with condition type 1785 ‘&i/o-file-already-exists’ is not raised, even if ‘no-create’ 1786 is not included, and the file is truncated to zero length. 1787 ‘no-truncate’ 1788 If the file already exists and the exception with condition 1789 type ‘&i/o-file-already-exists’ has been inhibited by 1790 inclusion of ‘no-create’ or ‘no-fail’, the file is not 1791 truncated, but the port’s current position is still set to the 1792 beginning of the file. 1793 1794 These options have no effect when a file is opened only for input. 1795 Symbols other than those listed above may be used as 1796 FILE-OPTIONS-SYMBOLs; they have implementation-specific meaning, if 1797 any. 1798 1799 Note: Only the name of FILE-OPTIONS-SYMBOL is significant. 1800 1801 -- Scheme Procedure: open-file-input-port filename 1802 -- Scheme Procedure: open-file-input-port filename file-options 1803 -- Scheme Procedure: open-file-input-port filename file-options 1804 buffer-mode 1805 -- Scheme Procedure: open-file-input-port filename file-options 1806 buffer-mode maybe-transcoder 1807 MAYBE-TRANSCODER must be either a transcoder or ‘#f’. 1808 1809 The ‘open-file-input-port’ procedure returns an input port for the 1810 named file. The FILE-OPTIONS and MAYBE-TRANSCODER arguments are 1811 optional. 1812 1813 The FILE-OPTIONS argument, which may determine various aspects of 1814 the returned port, defaults to the value of ‘(file-options)’. 1815 1816 The BUFFER-MODE argument, if supplied, must be one of the symbols 1817 that name a buffer mode. The BUFFER-MODE argument defaults to 1818 ‘block’. 1819 1820 If MAYBE-TRANSCODER is a transcoder, it becomes the transcoder 1821 associated with the returned port. 1822 1823 If MAYBE-TRANSCODER is ‘#f’ or absent, the port will be a binary 1824 port and will support the ‘port-position’ and ‘set-port-position!’ 1825 operations. Otherwise the port will be a textual port, and whether 1826 it supports the ‘port-position’ and ‘set-port-position!’ operations 1827 is implementation-dependent (and possibly transcoder-dependent). 1828 1829 -- Scheme Procedure: open-file-output-port filename 1830 -- Scheme Procedure: open-file-output-port filename file-options 1831 -- Scheme Procedure: open-file-output-port filename file-options 1832 buffer-mode 1833 -- Scheme Procedure: open-file-output-port filename file-options 1834 buffer-mode maybe-transcoder 1835 MAYBE-TRANSCODER must be either a transcoder or ‘#f’. 1836 1837 The ‘open-file-output-port’ procedure returns an output port for 1838 the named file. 1839 1840 The FILE-OPTIONS argument, which may determine various aspects of 1841 the returned port, defaults to the value of ‘(file-options)’. 1842 1843 The BUFFER-MODE argument, if supplied, must be one of the symbols 1844 that name a buffer mode. The BUFFER-MODE argument defaults to 1845 ‘block’. 1846 1847 If MAYBE-TRANSCODER is a transcoder, it becomes the transcoder 1848 associated with the port. 1849 1850 If MAYBE-TRANSCODER is ‘#f’ or absent, the port will be a binary 1851 port and will support the ‘port-position’ and ‘set-port-position!’ 1852 operations. Otherwise the port will be a textual port, and whether 1853 it supports the ‘port-position’ and ‘set-port-position!’ operations 1854 is implementation-dependent (and possibly transcoder-dependent). 1855 1856 1857File: guile.info, Node: rnrs io simple, Next: rnrs files, Prev: R6RS File Ports, Up: R6RS Standard Libraries 1858 18597.6.2.18 rnrs io simple 1860....................... 1861 1862The ‘(rnrs io simple (6))’ library provides convenience functions for 1863performing textual I/O on ports. This library also exports all of the 1864condition types and associated procedures described in (*note R6RS I/O 1865Conditions::). In the context of this section, when stating that a 1866procedure behaves “identically” to the corresponding procedure in 1867Guile’s core library, this is modulo the behavior wrt. conditions: such 1868procedures raise the appropriate R6RS conditions in case of error, but 1869otherwise behave identically. 1870 1871 Note: There are still known issues regarding condition-correctness; 1872 some errors may still be thrown as native Guile exceptions instead 1873 of the appropriate R6RS conditions. 1874 1875 -- Scheme Procedure: eof-object 1876 -- Scheme Procedure: eof-object? obj 1877 These procedures are identical to the ones provided by the ‘(rnrs 1878 io ports (6))’ library. *Note rnrs io ports::, for documentation. 1879 1880 -- Scheme Procedure: input-port? obj 1881 -- Scheme Procedure: output-port? obj 1882 These procedures are identical to the ones provided by Guile’s core 1883 library. *Note Ports::, for documentation. 1884 1885 -- Scheme Procedure: call-with-input-file filename proc 1886 -- Scheme Procedure: call-with-output-file filename proc 1887 -- Scheme Procedure: open-input-file filename 1888 -- Scheme Procedure: open-output-file filename 1889 -- Scheme Procedure: with-input-from-file filename thunk 1890 -- Scheme Procedure: with-output-to-file filename thunk 1891 These procedures are identical to the ones provided by Guile’s core 1892 library. *Note File Ports::, for documentation. 1893 1894 -- Scheme Procedure: close-input-port input-port 1895 -- Scheme Procedure: close-output-port output-port 1896 Closes the given INPUT-PORT or OUTPUT-PORT. These are legacy 1897 interfaces; just use ‘close-port’. 1898 1899 -- Scheme Procedure: peek-char 1900 -- Scheme Procedure: peek-char textual-input-port 1901 -- Scheme Procedure: read-char 1902 -- Scheme Procedure: read-char textual-input-port 1903 These procedures are identical to the ones provided by Guile’s core 1904 library. *Note Venerable Port Interfaces::, for documentation. 1905 1906 -- Scheme Procedure: read 1907 -- Scheme Procedure: read textual-input-port 1908 This procedure is identical to the one provided by Guile’s core 1909 library. *Note Scheme Read::, for documentation. 1910 1911 -- Scheme Procedure: display obj 1912 -- Scheme Procedure: display obj textual-output-port 1913 -- Scheme Procedure: newline 1914 -- Scheme Procedure: newline textual-output-port 1915 -- Scheme Procedure: write obj 1916 -- Scheme Procedure: write obj textual-output-port 1917 -- Scheme Procedure: write-char char 1918 -- Scheme Procedure: write-char char textual-output-port 1919 These procedures are identical to the ones provided by Guile’s core 1920 library. *Note Venerable Port Interfaces::, and *Note Scheme 1921 Write::, for documentation. 1922 1923 1924File: guile.info, Node: rnrs files, Next: rnrs programs, Prev: rnrs io simple, Up: R6RS Standard Libraries 1925 19267.6.2.19 rnrs files 1927................... 1928 1929The ‘(rnrs files (6))’ library provides the ‘file-exists?’ and 1930‘delete-file’ procedures, which test for the existence of a file and 1931allow the deletion of files from the file system, respectively. 1932 1933 These procedures are identical to the ones provided by Guile’s core 1934library. *Note File System::, for documentation. 1935 1936 1937File: guile.info, Node: rnrs programs, Next: rnrs arithmetic fixnums, Prev: rnrs files, Up: R6RS Standard Libraries 1938 19397.6.2.20 rnrs programs 1940...................... 1941 1942The ‘(rnrs programs (6))’ library provides procedures for process 1943management and introspection. 1944 1945 -- Scheme Procedure: command-line 1946 This procedure is identical to the one provided by Guile’s core 1947 library. *Note Runtime Environment::, for documentation. 1948 1949 -- Scheme Procedure: exit [status] 1950 This procedure is identical to the one provided by Guile’s core 1951 library. *Note Processes::, for documentation. 1952 1953 1954File: guile.info, Node: rnrs arithmetic fixnums, Next: rnrs arithmetic flonums, Prev: rnrs programs, Up: R6RS Standard Libraries 1955 19567.6.2.21 rnrs arithmetic fixnums 1957................................ 1958 1959The ‘(rnrs arithmetic fixnums (6))’ library provides procedures for 1960performing arithmetic operations on an implementation-dependent range of 1961exact integer values, which R6RS refers to as “fixnums”. In Guile, the 1962size of a fixnum is determined by the size of the ‘SCM’ type; a single 1963SCM struct is guaranteed to be able to hold an entire fixnum, making 1964fixnum computations particularly efficient—(*note The SCM Type::). On 196532-bit systems, the most negative and most positive fixnum values are, 1966respectively, -536870912 and 536870911. 1967 1968 Unless otherwise specified, all of the procedures below take fixnums 1969as arguments, and will raise an ‘&assertion’ condition if passed a 1970non-fixnum argument or an ‘&implementation-restriction’ condition if 1971their result is not itself a fixnum. 1972 1973 -- Scheme Procedure: fixnum? obj 1974 Returns ‘#t’ if OBJ is a fixnum, ‘#f’ otherwise. 1975 1976 -- Scheme Procedure: fixnum-width 1977 -- Scheme Procedure: least-fixnum 1978 -- Scheme Procedure: greatest-fixnum 1979 These procedures return, respectively, the maximum number of bits 1980 necessary to represent a fixnum value in Guile, the minimum fixnum 1981 value, and the maximum fixnum value. 1982 1983 -- Scheme Procedure: fx=? fx1 fx2 fx3 ... 1984 -- Scheme Procedure: fx>? fx1 fx2 fx3 ... 1985 -- Scheme Procedure: fx<? fx1 fx2 fx3 ... 1986 -- Scheme Procedure: fx>=? fx1 fx2 fx3 ... 1987 -- Scheme Procedure: fx<=? fx1 fx2 fx3 ... 1988 These procedures return ‘#t’ if their fixnum arguments are 1989 (respectively): equal, monotonically increasing, monotonically 1990 decreasing, monotonically nondecreasing, or monotonically 1991 nonincreasing; ‘#f’ otherwise. 1992 1993 -- Scheme Procedure: fxzero? fx 1994 -- Scheme Procedure: fxpositive? fx 1995 -- Scheme Procedure: fxnegative? fx 1996 -- Scheme Procedure: fxodd? fx 1997 -- Scheme Procedure: fxeven? fx 1998 These numerical predicates return ‘#t’ if FX is, respectively, 1999 zero, greater than zero, less than zero, odd, or even; ‘#f’ 2000 otherwise. 2001 2002 -- Scheme Procedure: fxmax fx1 fx2 ... 2003 -- Scheme Procedure: fxmin fx1 fx2 ... 2004 These procedures return the maximum or minimum of their arguments. 2005 2006 -- Scheme Procedure: fx+ fx1 fx2 2007 -- Scheme Procedure: fx* fx1 fx2 2008 These procedures return the sum or product of their arguments. 2009 2010 -- Scheme Procedure: fx- fx1 fx2 2011 -- Scheme Procedure: fx- fx 2012 Returns the difference of FX1 and FX2, or the negation of FX, if 2013 called with a single argument. 2014 2015 An ‘&assertion’ condition is raised if the result is not itself a 2016 fixnum. 2017 2018 -- Scheme Procedure: fxdiv-and-mod fx1 fx2 2019 -- Scheme Procedure: fxdiv fx1 fx2 2020 -- Scheme Procedure: fxmod fx1 fx2 2021 -- Scheme Procedure: fxdiv0-and-mod0 fx1 fx2 2022 -- Scheme Procedure: fxdiv0 fx1 fx2 2023 -- Scheme Procedure: fxmod0 fx1 fx2 2024 These procedures implement number-theoretic division on fixnums; 2025 *Note (rnrs base)::, for a description of their semantics. 2026 2027 -- Scheme Procedure: fx+/carry fx1 fx2 fx3 2028 Returns the two fixnum results of the following computation: 2029 (let* ((s (+ fx1 fx2 fx3)) 2030 (s0 (mod0 s (expt 2 (fixnum-width)))) 2031 (s1 (div0 s (expt 2 (fixnum-width))))) 2032 (values s0 s1)) 2033 2034 -- Scheme Procedure: fx-/carry fx1 fx2 fx3 2035 Returns the two fixnum results of the following computation: 2036 (let* ((d (- fx1 fx2 fx3)) 2037 (d0 (mod0 d (expt 2 (fixnum-width)))) 2038 (d1 (div0 d (expt 2 (fixnum-width))))) 2039 (values d0 d1)) 2040 2041 -- Scheme Procedure: fx*/carry fx1 fx2 fx3 2042 Returns the two fixnum results of the following computation: 2043 (let* ((s (+ (* fx1 fx2) fx3)) 2044 (s0 (mod0 s (expt 2 (fixnum-width)))) 2045 (s1 (div0 s (expt 2 (fixnum-width))))) 2046 (values s0 s1)) 2047 2048 -- Scheme Procedure: fxnot fx 2049 -- Scheme Procedure: fxand fx1 ... 2050 -- Scheme Procedure: fxior fx1 ... 2051 -- Scheme Procedure: fxxor fx1 ... 2052 These procedures are identical to the ‘lognot’, ‘logand’, ‘logior’, 2053 and ‘logxor’ procedures provided by Guile’s core library. *Note 2054 Bitwise Operations::, for documentation. 2055 2056 -- Scheme Procedure: fxif fx1 fx2 fx3 2057 Returns the bitwise “if” of its fixnum arguments. The bit at 2058 position ‘i’ in the return value will be the ‘i’th bit from FX2 if 2059 the ‘i’th bit of FX1 is 1, the ‘i’th bit from FX3. 2060 2061 -- Scheme Procedure: fxbit-count fx 2062 Returns the number of 1 bits in the two’s complement representation 2063 of FX. 2064 2065 -- Scheme Procedure: fxlength fx 2066 Returns the number of bits necessary to represent FX. 2067 2068 -- Scheme Procedure: fxfirst-bit-set fx 2069 Returns the index of the least significant 1 bit in the two’s 2070 complement representation of FX. 2071 2072 -- Scheme Procedure: fxbit-set? fx1 fx2 2073 Returns ‘#t’ if the FX2th bit in the two’s complement 2074 representation of FX1 is 1, ‘#f’ otherwise. 2075 2076 -- Scheme Procedure: fxcopy-bit fx1 fx2 fx3 2077 Returns the result of setting the FX2th bit of FX1 to the FX2th bit 2078 of FX3. 2079 2080 -- Scheme Procedure: fxbit-field fx1 fx2 fx3 2081 Returns the integer representation of the contiguous sequence of 2082 bits in FX1 that starts at position FX2 (inclusive) and ends at 2083 position FX3 (exclusive). 2084 2085 -- Scheme Procedure: fxcopy-bit-field fx1 fx2 fx3 fx4 2086 Returns the result of replacing the bit field in FX1 with start and 2087 end positions FX2 and FX3 with the corresponding bit field from 2088 FX4. 2089 2090 -- Scheme Procedure: fxarithmetic-shift fx1 fx2 2091 -- Scheme Procedure: fxarithmetic-shift-left fx1 fx2 2092 -- Scheme Procedure: fxarithmetic-shift-right fx1 fx2 2093 Returns the result of shifting the bits of FX1 right or left by the 2094 FX2 positions. ‘fxarithmetic-shift’ is identical to 2095 ‘fxarithmetic-shift-left’. 2096 2097 -- Scheme Procedure: fxrotate-bit-field fx1 fx2 fx3 fx4 2098 Returns the result of cyclically permuting the bit field in FX1 2099 with start and end positions FX2 and FX3 by FX4 bits in the 2100 direction of more significant bits. 2101 2102 -- Scheme Procedure: fxreverse-bit-field fx1 fx2 fx3 2103 Returns the result of reversing the order of the bits of FX1 2104 between position FX2 (inclusive) and position FX3 (exclusive). 2105 2106 2107File: guile.info, Node: rnrs arithmetic flonums, Next: rnrs arithmetic bitwise, Prev: rnrs arithmetic fixnums, Up: R6RS Standard Libraries 2108 21097.6.2.22 rnrs arithmetic flonums 2110................................ 2111 2112The ‘(rnrs arithmetic flonums (6))’ library provides procedures for 2113performing arithmetic operations on inexact representations of real 2114numbers, which R6RS refers to as “flonums”. 2115 2116 Unless otherwise specified, all of the procedures below take flonums 2117as arguments, and will raise an ‘&assertion’ condition if passed a 2118non-flonum argument. 2119 2120 -- Scheme Procedure: flonum? obj 2121 Returns ‘#t’ if OBJ is a flonum, ‘#f’ otherwise. 2122 2123 -- Scheme Procedure: real->flonum x 2124 Returns the flonum that is numerically closest to the real number 2125 X. 2126 2127 -- Scheme Procedure: fl=? fl1 fl2 fl3 ... 2128 -- Scheme Procedure: fl<? fl1 fl2 fl3 ... 2129 -- Scheme Procedure: fl<=? fl1 fl2 fl3 ... 2130 -- Scheme Procedure: fl>? fl1 fl2 fl3 ... 2131 -- Scheme Procedure: fl>=? fl1 fl2 fl3 ... 2132 These procedures return ‘#t’ if their flonum arguments are 2133 (respectively): equal, monotonically increasing, monotonically 2134 decreasing, monotonically nondecreasing, or monotonically 2135 nonincreasing; ‘#f’ otherwise. 2136 2137 -- Scheme Procedure: flinteger? fl 2138 -- Scheme Procedure: flzero? fl 2139 -- Scheme Procedure: flpositive? fl 2140 -- Scheme Procedure: flnegative? fl 2141 -- Scheme Procedure: flodd? fl 2142 -- Scheme Procedure: fleven? fl 2143 These numerical predicates return ‘#t’ if FL is, respectively, an 2144 integer, zero, greater than zero, less than zero, odd, even, ‘#f’ 2145 otherwise. In the case of ‘flodd?’ and ‘fleven?’, FL must be an 2146 integer-valued flonum. 2147 2148 -- Scheme Procedure: flfinite? fl 2149 -- Scheme Procedure: flinfinite? fl 2150 -- Scheme Procedure: flnan? fl 2151 These numerical predicates return ‘#t’ if FL is, respectively, not 2152 infinite, infinite, or a ‘NaN’ value. 2153 2154 -- Scheme Procedure: flmax fl1 fl2 ... 2155 -- Scheme Procedure: flmin fl1 fl2 ... 2156 These procedures return the maximum or minimum of their arguments. 2157 2158 -- Scheme Procedure: fl+ fl1 ... 2159 -- Scheme Procedure: fl* fl ... 2160 These procedures return the sum or product of their arguments. 2161 2162 -- Scheme Procedure: fl- fl1 fl2 ... 2163 -- Scheme Procedure: fl- fl 2164 -- Scheme Procedure: fl/ fl1 fl2 ... 2165 -- Scheme Procedure: fl/ fl 2166 These procedures return, respectively, the difference or quotient 2167 of their arguments when called with two arguments; when called with 2168 a single argument, they return the additive or multiplicative 2169 inverse of FL. 2170 2171 -- Scheme Procedure: flabs fl 2172 Returns the absolute value of FL. 2173 2174 -- Scheme Procedure: fldiv-and-mod fl1 fl2 2175 -- Scheme Procedure: fldiv fl1 fl2 2176 -- Scheme Procedure: fldmod fl1 fl2 2177 -- Scheme Procedure: fldiv0-and-mod0 fl1 fl2 2178 -- Scheme Procedure: fldiv0 fl1 fl2 2179 -- Scheme Procedure: flmod0 fl1 fl2 2180 These procedures implement number-theoretic division on flonums; 2181 *Note (rnrs base)::, for a description for their semantics. 2182 2183 -- Scheme Procedure: flnumerator fl 2184 -- Scheme Procedure: fldenominator fl 2185 These procedures return the numerator or denominator of FL as a 2186 flonum. 2187 2188 -- Scheme Procedure: flfloor fl1 2189 -- Scheme Procedure: flceiling fl 2190 -- Scheme Procedure: fltruncate fl 2191 -- Scheme Procedure: flround fl 2192 These procedures are identical to the ‘floor’, ‘ceiling’, 2193 ‘truncate’, and ‘round’ procedures provided by Guile’s core 2194 library. *Note Arithmetic::, for documentation. 2195 2196 -- Scheme Procedure: flexp fl 2197 -- Scheme Procedure: fllog fl 2198 -- Scheme Procedure: fllog fl1 fl2 2199 -- Scheme Procedure: flsin fl 2200 -- Scheme Procedure: flcos fl 2201 -- Scheme Procedure: fltan fl 2202 -- Scheme Procedure: flasin fl 2203 -- Scheme Procedure: flacos fl 2204 -- Scheme Procedure: flatan fl 2205 -- Scheme Procedure: flatan fl1 fl2 2206 These procedures, which compute the usual transcendental functions, 2207 are the flonum variants of the procedures provided by the R6RS base 2208 library (*note (rnrs base)::). 2209 2210 -- Scheme Procedure: flsqrt fl 2211 Returns the square root of FL. If FL is ‘-0.0’, -0.0 is returned; 2212 for other negative values, a ‘NaN’ value is returned. 2213 2214 -- Scheme Procedure: flexpt fl1 fl2 2215 Returns the value of FL1 raised to the power of FL2. 2216 2217 The following condition types are provided to allow Scheme 2218implementations that do not support infinities or ‘NaN’ values to 2219indicate that a computation resulted in such a value. Guile supports 2220both of these, so these conditions will never be raised by Guile’s 2221standard libraries implementation. 2222 2223 -- Condition Type: &no-infinities 2224 -- Scheme Procedure: make-no-infinities-violation obj 2225 -- Scheme Procedure: no-infinities-violation? 2226 A condition type indicating that a computation resulted in an 2227 infinite value on a Scheme implementation incapable of representing 2228 infinities. 2229 2230 -- Condition Type: &no-nans 2231 -- Scheme Procedure: make-no-nans-violation obj 2232 -- Scheme Procedure: no-nans-violation? obj 2233 A condition type indicating that a computation resulted in a ‘NaN’ 2234 value on a Scheme implementation incapable of representing ‘NaN’s. 2235 2236 -- Scheme Procedure: fixnum->flonum fx 2237 Returns the flonum that is numerically closest to the fixnum FX. 2238 2239 2240File: guile.info, Node: rnrs arithmetic bitwise, Next: rnrs syntax-case, Prev: rnrs arithmetic flonums, Up: R6RS Standard Libraries 2241 22427.6.2.23 rnrs arithmetic bitwise 2243................................ 2244 2245The ‘(rnrs arithmetic bitwise (6))’ library provides procedures for 2246performing bitwise arithmetic operations on the two’s complement 2247representations of fixnums. 2248 2249 This library and the procedures it exports share functionality with 2250SRFI-60, which provides support for bitwise manipulation of integers 2251(*note SRFI-60::). 2252 2253 -- Scheme Procedure: bitwise-not ei 2254 -- Scheme Procedure: bitwise-and ei1 ... 2255 -- Scheme Procedure: bitwise-ior ei1 ... 2256 -- Scheme Procedure: bitwise-xor ei1 ... 2257 These procedures are identical to the ‘lognot’, ‘logand’, ‘logior’, 2258 and ‘logxor’ procedures provided by Guile’s core library. *Note 2259 Bitwise Operations::, for documentation. 2260 2261 -- Scheme Procedure: bitwise-if ei1 ei2 ei3 2262 Returns the bitwise “if” of its arguments. The bit at position ‘i’ 2263 in the return value will be the ‘i’th bit from EI2 if the ‘i’th bit 2264 of EI1 is 1, the ‘i’th bit from EI3. 2265 2266 -- Scheme Procedure: bitwise-bit-count ei 2267 Returns the number of 1 bits in the two’s complement representation 2268 of EI. 2269 2270 -- Scheme Procedure: bitwise-length ei 2271 Returns the number of bits necessary to represent EI. 2272 2273 -- Scheme Procedure: bitwise-first-bit-set ei 2274 Returns the index of the least significant 1 bit in the two’s 2275 complement representation of EI. 2276 2277 -- Scheme Procedure: bitwise-bit-set? ei1 ei2 2278 Returns ‘#t’ if the EI2th bit in the two’s complement 2279 representation of EI1 is 1, ‘#f’ otherwise. 2280 2281 -- Scheme Procedure: bitwise-copy-bit ei1 ei2 ei3 2282 Returns the result of setting the EI2th bit of EI1 to the EI2th bit 2283 of EI3. 2284 2285 -- Scheme Procedure: bitwise-bit-field ei1 ei2 ei3 2286 Returns the integer representation of the contiguous sequence of 2287 bits in EI1 that starts at position EI2 (inclusive) and ends at 2288 position EI3 (exclusive). 2289 2290 -- Scheme Procedure: bitwise-copy-bit-field ei1 ei2 ei3 ei4 2291 Returns the result of replacing the bit field in EI1 with start and 2292 end positions EI2 and EI3 with the corresponding bit field from 2293 EI4. 2294 2295 -- Scheme Procedure: bitwise-arithmetic-shift ei1 ei2 2296 -- Scheme Procedure: bitwise-arithmetic-shift-left ei1 ei2 2297 -- Scheme Procedure: bitwise-arithmetic-shift-right ei1 ei2 2298 Returns the result of shifting the bits of EI1 right or left by the 2299 EI2 positions. ‘bitwise-arithmetic-shift’ is identical to 2300 ‘bitwise-arithmetic-shift-left’. 2301 2302 -- Scheme Procedure: bitwise-rotate-bit-field ei1 ei2 ei3 ei4 2303 Returns the result of cyclically permuting the bit field in EI1 2304 with start and end positions EI2 and EI3 by EI4 bits in the 2305 direction of more significant bits. 2306 2307 -- Scheme Procedure: bitwise-reverse-bit-field ei1 ei2 ei3 2308 Returns the result of reversing the order of the bits of EI1 2309 between position EI2 (inclusive) and position EI3 (exclusive). 2310 2311 2312File: guile.info, Node: rnrs syntax-case, Next: rnrs hashtables, Prev: rnrs arithmetic bitwise, Up: R6RS Standard Libraries 2313 23147.6.2.24 rnrs syntax-case 2315......................... 2316 2317The ‘(rnrs syntax-case (6))’ library provides access to the 2318‘syntax-case’ system for writing hygienic macros. With one exception, 2319all of the forms and procedures exported by this library are 2320“re-exports” of Guile’s native support for ‘syntax-case’; *Note Syntax 2321Case::, for documentation, examples, and rationale. 2322 2323 -- Scheme Procedure: make-variable-transformer proc 2324 Creates a new variable transformer out of PROC, a procedure that 2325 takes a syntax object as input and returns a syntax object. If an 2326 identifier to which the result of this procedure is bound appears 2327 on the left-hand side of a ‘set!’ expression, PROC will be called 2328 with a syntax object representing the entire ‘set!’ expression, and 2329 its return value will replace that ‘set!’ expression. 2330 2331 -- Scheme Syntax: syntax-case expression (literal ...) clause ... 2332 The ‘syntax-case’ pattern matching form. 2333 2334 -- Scheme Syntax: syntax template 2335 -- Scheme Syntax: quasisyntax template 2336 -- Scheme Syntax: unsyntax template 2337 -- Scheme Syntax: unsyntax-splicing template 2338 These forms allow references to be made in the body of a 2339 syntax-case output expression subform to datum and non-datum 2340 values. They are identical to the forms provided by Guile’s core 2341 library; *Note Syntax Case::, for documentation. 2342 2343 -- Scheme Procedure: identifier? obj 2344 -- Scheme Procedure: bound-identifier=? id1 id2 2345 -- Scheme Procedure: free-identifier=? id1 id2 2346 These predicate procedures operate on syntax objects representing 2347 Scheme identifiers. ‘identifier?’ returns ‘#t’ if OBJ represents 2348 an identifier, ‘#f’ otherwise. ‘bound-identifier=?’ returns ‘#t’ 2349 if and only if a binding for ID1 would capture a reference to ID2 2350 in the transformer’s output, or vice-versa. ‘free-identifier=?’ 2351 returns ‘#t’ if and only ID1 and ID2 would refer to the same 2352 binding in the output of the transformer, independent of any 2353 bindings introduced by the transformer. 2354 2355 -- Scheme Procedure: generate-temporaries l 2356 Returns a list, of the same length as L, which must be a list or a 2357 syntax object representing a list, of globally unique symbols. 2358 2359 -- Scheme Procedure: syntax->datum syntax-object 2360 -- Scheme Procedure: datum->syntax template-id datum 2361 These procedures convert wrapped syntax objects to and from Scheme 2362 datum values. The syntax object returned by ‘datum->syntax’ shares 2363 contextual information with the syntax object TEMPLATE-ID. 2364 2365 -- Scheme Procedure: syntax-violation whom message form 2366 -- Scheme Procedure: syntax-violation whom message form subform 2367 Constructs a new compound condition that includes the following 2368 simple conditions: 2369 • If WHOM is not ‘#f’, a ‘&who’ condition with the WHOM as its 2370 field 2371 • A ‘&message’ condition with the specified MESSAGE 2372 • A ‘&syntax’ condition with the specified FORM and optional 2373 SUBFORM fields 2374 2375 2376File: guile.info, Node: rnrs hashtables, Next: rnrs enums, Prev: rnrs syntax-case, Up: R6RS Standard Libraries 2377 23787.6.2.25 rnrs hashtables 2379........................ 2380 2381The ‘(rnrs hashtables (6))’ library provides structures and procedures 2382for creating and accessing hash tables. The hash tables API defined by 2383R6RS is substantially similar to both Guile’s native hash tables 2384implementation as well as the one provided by SRFI-69; *Note Hash 2385Tables::, and *note SRFI-69::, respectively. Note that you can write 2386portable R6RS library code that manipulates SRFI-69 hash tables (by 2387importing the ‘(srfi :69)’ library); however, hash tables created by one 2388API cannot be used by another. 2389 2390 Like SRFI-69 hash tables—and unlike Guile’s native ones—R6RS hash 2391tables associate hash and equality functions with a hash table at the 2392time of its creation. Additionally, R6RS allows for the creation (via 2393‘hashtable-copy’; see below) of immutable hash tables. 2394 2395 -- Scheme Procedure: make-eq-hashtable 2396 -- Scheme Procedure: make-eq-hashtable k 2397 Returns a new hash table that uses ‘eq?’ to compare keys and 2398 Guile’s ‘hashq’ procedure as a hash function. If K is given, it 2399 specifies the initial capacity of the hash table. 2400 2401 -- Scheme Procedure: make-eqv-hashtable 2402 -- Scheme Procedure: make-eqv-hashtable k 2403 Returns a new hash table that uses ‘eqv?’ to compare keys and 2404 Guile’s ‘hashv’ procedure as a hash function. If K is given, it 2405 specifies the initial capacity of the hash table. 2406 2407 -- Scheme Procedure: make-hashtable hash-function equiv 2408 -- Scheme Procedure: make-hashtable hash-function equiv k 2409 Returns a new hash table that uses EQUIV to compare keys and 2410 HASH-FUNCTION as a hash function. EQUIV must be a procedure that 2411 accepts two arguments and returns a true value if they are 2412 equivalent, ‘#f’ otherwise; HASH-FUNCTION must be a procedure that 2413 accepts one argument and returns a non-negative integer. 2414 2415 If K is given, it specifies the initial capacity of the hash table. 2416 2417 -- Scheme Procedure: hashtable? obj 2418 Returns ‘#t’ if OBJ is an R6RS hash table, ‘#f’ otherwise. 2419 2420 -- Scheme Procedure: hashtable-size hashtable 2421 Returns the number of keys currently in the hash table HASHTABLE. 2422 2423 -- Scheme Procedure: hashtable-ref hashtable key default 2424 Returns the value associated with KEY in the hash table HASHTABLE, 2425 or DEFAULT if none is found. 2426 2427 -- Scheme Procedure: hashtable-set! hashtable key obj 2428 Associates the key KEY with the value OBJ in the hash table 2429 HASHTABLE, and returns an unspecified value. An ‘&assertion’ 2430 condition is raised if HASHTABLE is immutable. 2431 2432 -- Scheme Procedure: hashtable-delete! hashtable key 2433 Removes any association found for the key KEY in the hash table 2434 HASHTABLE, and returns an unspecified value. An ‘&assertion’ 2435 condition is raised if HASHTABLE is immutable. 2436 2437 -- Scheme Procedure: hashtable-contains? hashtable key 2438 Returns ‘#t’ if the hash table HASHTABLE contains an association 2439 for the key KEY, ‘#f’ otherwise. 2440 2441 -- Scheme Procedure: hashtable-update! hashtable key proc default 2442 Associates with KEY in the hash table HASHTABLE the result of 2443 calling PROC, which must be a procedure that takes one argument, on 2444 the value currently associated KEY in HASHTABLE—or on DEFAULT if no 2445 such association exists. An ‘&assertion’ condition is raised if 2446 HASHTABLE is immutable. 2447 2448 -- Scheme Procedure: hashtable-copy hashtable 2449 -- Scheme Procedure: hashtable-copy hashtable mutable 2450 Returns a copy of the hash table HASHTABLE. If the optional 2451 argument MUTABLE is provided and is a true value, the new hash 2452 table will be mutable. 2453 2454 -- Scheme Procedure: hashtable-clear! hashtable 2455 -- Scheme Procedure: hashtable-clear! hashtable k 2456 Removes all of the associations from the hash table HASHTABLE. The 2457 optional argument K, which specifies a new capacity for the hash 2458 table, is accepted by Guile’s ‘(rnrs hashtables)’ implementation, 2459 but is ignored. 2460 2461 -- Scheme Procedure: hashtable-keys hashtable 2462 Returns a vector of the keys with associations in the hash table 2463 HASHTABLE, in an unspecified order. 2464 2465 -- Scheme Procedure: hashtable-entries hashtable 2466 Return two values—a vector of the keys with associations in the 2467 hash table HASHTABLE, and a vector of the values to which these 2468 keys are mapped, in corresponding but unspecified order. 2469 2470 -- Scheme Procedure: hashtable-equivalence-function hashtable 2471 Returns the equivalence predicated use by HASHTABLE. This 2472 procedure returns ‘eq?’ and ‘eqv?’, respectively, for hash tables 2473 created by ‘make-eq-hashtable’ and ‘make-eqv-hashtable’. 2474 2475 -- Scheme Procedure: hashtable-hash-function hashtable 2476 Returns the hash function used by HASHTABLE. For hash tables 2477 created by ‘make-eq-hashtable’ or ‘make-eqv-hashtable’, ‘#f’ is 2478 returned. 2479 2480 -- Scheme Procedure: hashtable-mutable? hashtable 2481 Returns ‘#t’ if HASHTABLE is mutable, ‘#f’ otherwise. 2482 2483 A number of hash functions are provided for convenience: 2484 2485 -- Scheme Procedure: equal-hash obj 2486 Returns an integer hash value for OBJ, based on its structure and 2487 current contents. This hash function is suitable for use with 2488 ‘equal?’ as an equivalence function. 2489 2490 -- Scheme Procedure: string-hash string 2491 -- Scheme Procedure: symbol-hash symbol 2492 These procedures are identical to the ones provided by Guile’s core 2493 library. *Note Hash Table Reference::, for documentation. 2494 2495 -- Scheme Procedure: string-ci-hash string 2496 Returns an integer hash value for STRING based on its contents, 2497 ignoring case. This hash function is suitable for use with 2498 ‘string-ci=?’ as an equivalence function. 2499 2500 2501File: guile.info, Node: rnrs enums, Next: rnrs, Prev: rnrs hashtables, Up: R6RS Standard Libraries 2502 25037.6.2.26 rnrs enums 2504................... 2505 2506The ‘(rnrs enums (6))’ library provides structures and procedures for 2507working with enumerable sets of symbols. Guile’s implementation defines 2508an “enum-set” record type that encapsulates a finite set of distinct 2509symbols, the “universe”, and a subset of these symbols, which define the 2510enumeration set. 2511 2512 The SRFI-1 list library provides a number of procedures for 2513performing set operations on lists; Guile’s ‘(rnrs enums)’ 2514implementation makes use of several of them. *Note SRFI-1 Set 2515Operations::, for more information. 2516 2517 -- Scheme Procedure: make-enumeration symbol-list 2518 Returns a new enum-set whose universe and enumeration set are both 2519 equal to SYMBOL-LIST, a list of symbols. 2520 2521 -- Scheme Procedure: enum-set-universe enum-set 2522 Returns an enum-set representing the universe of ENUM-SET, an 2523 enum-set. 2524 2525 -- Scheme Procedure: enum-set-indexer enum-set 2526 Returns a procedure that takes a single argument and returns the 2527 zero-indexed position of that argument in the universe of ENUM-SET, 2528 or ‘#f’ if its argument is not a member of that universe. 2529 2530 -- Scheme Procedure: enum-set-constructor enum-set 2531 Returns a procedure that takes a single argument, a list of symbols 2532 from the universe of ENUM-SET, an enum-set, and returns a new 2533 enum-set with the same universe that represents a subset containing 2534 the specified symbols. 2535 2536 -- Scheme Procedure: enum-set->list enum-set 2537 Returns a list containing the symbols of the set represented by 2538 ENUM-SET, an enum-set, in the order that they appear in the 2539 universe of ENUM-SET. 2540 2541 -- Scheme Procedure: enum-set-member? symbol enum-set 2542 -- Scheme Procedure: enum-set-subset? enum-set1 enum-set2 2543 -- Scheme Procedure: enum-set=? enum-set1 enum-set2 2544 These procedures test for membership of symbols and enum-sets in 2545 other enum-sets. ‘enum-set-member?’ returns ‘#t’ if and only if 2546 SYMBOL is a member of the subset specified by ENUM-SET. 2547 ‘enum-set-subset?’ returns ‘#t’ if and only if the universe of 2548 ENUM-SET1 is a subset of the universe of ENUM-SET2 and every symbol 2549 in ENUM-SET1 is present in ENUM-SET2. ‘enum-set=?’ returns ‘#t’ if 2550 and only if ENUM-SET1 is a subset, as per ‘enum-set-subset?’ of 2551 ENUM-SET2 and vice versa. 2552 2553 -- Scheme Procedure: enum-set-union enum-set1 enum-set2 2554 -- Scheme Procedure: enum-set-intersection enum-set1 enum-set2 2555 -- Scheme Procedure: enum-set-difference enum-set1 enum-set2 2556 These procedures return, respectively, the union, intersection, and 2557 difference of their enum-set arguments. 2558 2559 -- Scheme Procedure: enum-set-complement enum-set 2560 Returns ENUM-SET’s complement (an enum-set), with regard to its 2561 universe. 2562 2563 -- Scheme Procedure: enum-set-projection enum-set1 enum-set2 2564 Returns the projection of the enum-set ENUM-SET1 onto the universe 2565 of the enum-set ENUM-SET2. 2566 2567 -- Scheme Syntax: define-enumeration type-name (symbol ...) 2568 constructor-syntax 2569 Evaluates to two new definitions: A constructor bound to 2570 CONSTRUCTOR-SYNTAX that behaves similarly to constructors created 2571 by ‘enum-set-constructor’, above, and creates new ENUM-SETs in the 2572 universe specified by ‘(symbol ...)’; and a “predicate macro” bound 2573 to TYPE-NAME, which has the following form: 2574 2575 (TYPE-NAME sym) 2576 2577 If SYM is a member of the universe specified by the SYMBOLs above, 2578 this form evaluates to SYM. Otherwise, a ‘&syntax’ condition is 2579 raised. 2580 2581 2582File: guile.info, Node: rnrs, Next: rnrs eval, Prev: rnrs enums, Up: R6RS Standard Libraries 2583 25847.6.2.27 rnrs 2585............. 2586 2587The ‘(rnrs (6))’ library is a composite of all of the other R6RS 2588standard libraries—it imports and re-exports all of their exported 2589procedures and syntactic forms—with the exception of the following 2590libraries: 2591 2592 • ‘(rnrs eval (6))’ 2593 • ‘(rnrs mutable-pairs (6))’ 2594 • ‘(rnrs mutable-strings (6))’ 2595 • ‘(rnrs r5rs (6))’ 2596 2597 2598File: guile.info, Node: rnrs eval, Next: rnrs mutable-pairs, Prev: rnrs, Up: R6RS Standard Libraries 2599 26007.6.2.28 rnrs eval 2601.................. 2602 2603The ‘(rnrs eval (6)’ library provides procedures for performing 2604“on-the-fly” evaluation of expressions. 2605 2606 -- Scheme Procedure: eval expression environment 2607 Evaluates EXPRESSION, which must be a datum representation of a 2608 valid Scheme expression, in the environment specified by 2609 ENVIRONMENT. This procedure is identical to the one provided by 2610 Guile’s code library; *Note Fly Evaluation::, for documentation. 2611 2612 -- Scheme Procedure: environment import-spec ... 2613 Constructs and returns a new environment based on the specified 2614 IMPORT-SPECs, which must be datum representations of the import 2615 specifications used with the ‘import’ form. *Note R6RS 2616 Libraries::, for documentation. 2617 2618 2619File: guile.info, Node: rnrs mutable-pairs, Next: rnrs mutable-strings, Prev: rnrs eval, Up: R6RS Standard Libraries 2620 26217.6.2.29 rnrs mutable-pairs 2622........................... 2623 2624The ‘(rnrs mutable-pairs (6))’ library provides the ‘set-car!’ and 2625‘set-cdr!’ procedures, which allow the ‘car’ and ‘cdr’ fields of a pair 2626to be modified. 2627 2628 These procedures are identical to the ones provide by Guile’s core 2629library. *Note Pairs::, for documentation. All pairs in Guile are 2630mutable; consequently, these procedures will never throw the 2631‘&assertion’ condition described in the R6RS libraries specification. 2632 2633 2634File: guile.info, Node: rnrs mutable-strings, Next: rnrs r5rs, Prev: rnrs mutable-pairs, Up: R6RS Standard Libraries 2635 26367.6.2.30 rnrs mutable-strings 2637............................. 2638 2639The ‘(rnrs mutable-strings (6))’ library provides the ‘string-set!’ and 2640‘string-fill!’ procedures, which allow the content of strings to be 2641modified “in-place.” 2642 2643 These procedures are identical to the ones provided by Guile’s core 2644library. *Note String Modification::, for documentation. All strings 2645in Guile are mutable; consequently, these procedures will never throw 2646the ‘&assertion’ condition described in the R6RS libraries 2647specification. 2648 2649 2650File: guile.info, Node: rnrs r5rs, Prev: rnrs mutable-strings, Up: R6RS Standard Libraries 2651 26527.6.2.31 rnrs r5rs 2653.................. 2654 2655The ‘(rnrs r5rs (6))’ library exports bindings for some procedures 2656present in R5RS but omitted from the R6RS base library specification. 2657 2658 -- Scheme Procedure: exact->inexact z 2659 -- Scheme Procedure: inexact->exact z 2660 These procedures are identical to the ones provided by Guile’s core 2661 library. *Note Exactness::, for documentation. 2662 2663 -- Scheme Procedure: quotient n1 n2 2664 -- Scheme Procedure: remainder n1 n2 2665 -- Scheme Procedure: modulo n1 n2 2666 These procedures are identical to the ones provided by Guile’s core 2667 library. *Note Integer Operations::, for documentation. 2668 2669 -- Scheme Syntax: delay expr 2670 -- Scheme Procedure: force promise 2671 The ‘delay’ form and the ‘force’ procedure are identical to their 2672 counterparts in Guile’s core library. *Note Delayed Evaluation::, 2673 for documentation. 2674 2675 -- Scheme Procedure: null-environment n 2676 -- Scheme Procedure: scheme-report-environment n 2677 These procedures are identical to the ones provided by the ‘(ice-9 2678 r5rs)’ Guile module. *Note Environments::, for documentation. 2679 2680 2681File: guile.info, Node: R7RS Support, Next: Pattern Matching, Prev: R6RS Support, Up: Guile Modules 2682 26837.7 R7RS Support 2684================ 2685 2686The R7RS standard is essentially R5RS (directly supported by Guile), 2687plus a module facility, plus an organization of bindings into a standard 2688set of modules. 2689 2690 Happily, the syntax for R7RS modules was chosen to be compatible with 2691R6RS, and so Guile’s documentation there applies. *Note R6RS 2692Libraries::, for more information on how to define R6RS libraries, and 2693their integration with Guile modules. *Note Library Usage::, also. 2694 2695* Menu: 2696 2697* R7RS Incompatibilities:: Guile mostly implements R7RS. 2698* R7RS Standard Libraries:: Modules defined by the R7RS. 2699 2700 2701File: guile.info, Node: R7RS Incompatibilities, Next: R7RS Standard Libraries, Up: R7RS Support 2702 27037.7.1 Incompatibilities with the R7RS 2704------------------------------------- 2705 2706As the R7RS is a much less ambitious standard than the R6RS (*note Guile 2707and Scheme::), it is very easy for Guile to support. As such, Guile is 2708a fully conforming implementation of R7RS, with the exception of the 2709occasional bug and a couple of unimplemented features: 2710 2711 • The R7RS specifies a syntax for reading circular data structures 2712 using “datum labels”, such as ‘#0=(1 2 3 . #0#)’. Guile’s reader 2713 does not support this syntax currently; 2714 <https://bugs.gnu.org/38236>. 2715 2716 • As with R6RS, a number of lexical features of R7RS conflict with 2717 Guile’s historical syntax. In addition to ‘r6rs-hex-escapes’ and 2718 ‘hungry-eol-escapes’ (*note R6RS Incompatibilities::), the 2719 ‘r7rs-symbols’ reader feature needs to be explicitly enabled. 2720 2721 Guile exposes a procedure in the root module to choose R7RS defaults 2722over Guile’s historical defaults. 2723 2724 -- Scheme Procedure: install-r7rs! 2725 Alter Guile’s default settings to better conform to the R7RS. 2726 2727 While Guile’s defaults may evolve over time, the current changes 2728 that this procedure imposes are to add ‘.sls’ and ‘.guile.sls’ to 2729 the set of supported ‘%load-extensions’, to better support R7RS 2730 conventions. *Note Load Paths::. ‘install-r7rs!’ will also enable 2731 the reader options mentioned above. 2732 2733 Finally, note that the ‘--r7rs’ command-line argument will call 2734‘install-r7rs!’ before calling user code. R7RS users probably want to 2735pass this argument to their Guile. 2736 2737 2738File: guile.info, Node: R7RS Standard Libraries, Prev: R7RS Incompatibilities, Up: R7RS Support 2739 27407.7.2 R7RS Standard Libraries 2741----------------------------- 2742 2743The R7RS organizes the definitions from R5RS into modules, and also adds 2744a few new definitions. 2745 2746 We do not attempt to document these libraries fully here, as unlike 2747R6RS, there are few new definitions in R7RS relative to R5RS. Most of 2748their functionality is already in Guile’s standard environment. Again, 2749the expectation is that most Guile users will use the well-known and 2750well-documented Guile modules; these R7RS libraries are mostly useful to 2751users who want to port their code to other R7RS systems. 2752 2753 As a brief overview, we note that the libraries defined by the R7RS 2754are as follows: 2755 2756‘(scheme base)’ 2757 The core functions, mostly corresponding to R5RS minus the elements 2758 listed separately below, but plus SRFI-34 error handling (*note 2759 SRFI-34::), bytevectors and bytevector ports (*note Bytevectors::), 2760 and some miscellaneous other new procedures. 2761‘(scheme case-lambda)’ 2762 ‘case-lambda’. 2763‘(scheme char)’ 2764 Converting strings and characters to upper or lower case, 2765 predicates for if a characer is numeric, and so on. 2766‘(scheme complex)’ 2767 Constructors and accessors for complex numbers. 2768‘(scheme cxr)’ 2769 ‘cddr’, ‘cadadr’, and all that. 2770‘(scheme eval)’ 2771 ‘eval’, but also an ‘environment’ routine allowing a user to 2772 specify an environment using a module import set. 2773‘(scheme file)’ 2774 ‘call-with-input-file’ and so on. 2775‘(scheme inexact)’ 2776 Routines that operate on inexact numbers: ‘sin’, ‘finite?’, and so 2777 on. 2778‘(scheme lazy)’ 2779 Promises. 2780‘(scheme load)’ 2781 The ‘load’ procedure. 2782‘(scheme process-context)’ 2783 Environment variables. *Note SRFI-98::. Also, ‘commmand-line’, 2784 ‘emergency-exit’ (like Guile’s ‘primitive-_exit’), and ‘exit’. 2785‘(scheme r5rs)’ 2786 The precise set of bindings exported by ‘r5rs’, but without 2787 ‘transcript-off’ / ‘transcript-on’, and also with the auxiliary 2788 syntax definitions like ‘_’ or ‘else’. *Note Syntax Rules::, for 2789 more on auxiliary syntax. 2790‘(scheme read)’ 2791 The ‘read’ procedure. 2792‘(scheme repl)’ 2793 The ‘interaction-environment’ procedure. 2794‘(scheme time)’ 2795 ‘current-second’, as well as ‘current-jiffy’ and 2796 ‘jiffies-per-second’. Guile uses the term “internal time unit” for 2797 what R7RS calls “jiffies”. 2798‘(scheme write)’ 2799 ‘display’, ‘write’, as well as ‘write-shared’ and ‘write-simple’. 2800 2801 For complete documentation, we advise the interested user to consult 2802the R7RS directly (*note (r7rs)R7RS::). 2803 2804 2805File: guile.info, Node: Pattern Matching, Next: Readline Support, Prev: R7RS Support, Up: Guile Modules 2806 28077.8 Pattern Matching 2808==================== 2809 2810The ‘(ice-9 match)’ module provides a “pattern matcher”, written by Alex 2811Shinn, and compatible with Andrew K. Wright’s pattern matcher found in 2812many Scheme implementations. 2813 2814 A pattern matcher can match an object against several patterns and 2815extract the elements that make it up. Patterns can represent any Scheme 2816object: lists, strings, symbols, records, etc. They can optionally 2817contain “pattern variables”. When a matching pattern is found, an 2818expression associated with the pattern is evaluated, optionally with all 2819pattern variables bound to the corresponding elements of the object: 2820 2821 (let ((l '(hello (world)))) 2822 (match l ;; <- the input object 2823 (('hello (who)) ;; <- the pattern 2824 who))) ;; <- the expression evaluated upon matching 2825 ⇒ world 2826 2827 In this example, list L matches the pattern ‘('hello (who))’, because 2828it is a two-element list whose first element is the symbol ‘hello’ and 2829whose second element is a one-element list. Here WHO is a pattern 2830variable. ‘match’, the pattern matcher, locally binds WHO to the value 2831contained in this one-element list—i.e., the symbol ‘world’. An error 2832would be raised if L did not match the pattern. 2833 2834 The same object can be matched against a simpler pattern: 2835 2836 (let ((l '(hello (world)))) 2837 (match l 2838 ((x y) 2839 (values x y)))) 2840 ⇒ hello 2841 ⇒ (world) 2842 2843 Here pattern ‘(x y)’ matches any two-element list, regardless of the 2844types of these elements. Pattern variables X and Y are bound to, 2845respectively, the first and second element of L. 2846 2847 Patterns can be composed, and nested. For instance, ‘...’ (ellipsis) 2848means that the previous pattern may be matched zero or more times in a 2849list: 2850 2851 (match lst 2852 (((heads tails ...) ...) 2853 heads)) 2854 2855This expression returns the first element of each list within LST. For 2856proper lists of proper lists, it is equivalent to ‘(map car lst)’. 2857However, it performs additional checks to make sure that LST and the 2858lists therein are proper lists, as prescribed by the pattern, raising an 2859error if they are not. 2860 2861 Compared to hand-written code, pattern matching noticeably improves 2862clarity and conciseness—no need to resort to series of ‘car’ and ‘cdr’ 2863calls when matching lists, for instance. It also improves robustness, 2864by making sure the input _completely_ matches the pattern—conversely, 2865hand-written code often trades robustness for conciseness. And of 2866course, ‘match’ is a macro, and the code it expands to is just as 2867efficient as equivalent hand-written code. 2868 2869 The pattern matcher is defined as follows: 2870 2871 -- Scheme Syntax: match exp clause1 clause2 ... 2872 Match object EXP against the patterns in CLAUSE1 CLAUSE2 ... in the 2873 order in which they appear. Return the value produced by the first 2874 matching clause. If no clause matches, throw an exception with key 2875 ‘match-error’. 2876 2877 Each clause has the form ‘(pattern body1 body2 ...)’. Each PATTERN 2878 must follow the syntax described below. Each body is an arbitrary 2879 Scheme expression, possibly referring to pattern variables of 2880 PATTERN. 2881 2882 The syntax and interpretation of patterns is as follows: 2883 2884 patterns: matches: 2885 2886pat ::= identifier anything, and binds identifier 2887 | _ anything 2888 | () the empty list 2889 | #t #t 2890 | #f #f 2891 | string a string 2892 | number a number 2893 | character a character 2894 | 'sexp an s-expression 2895 | 'symbol a symbol (special case of s-expr) 2896 | (pat_1 ... pat_n) list of n elements 2897 | (pat_1 ... pat_n . pat_{n+1}) list of n or more 2898 | (pat_1 ... pat_n pat_n+1 ooo) list of n or more, each element 2899 of remainder must match pat_n+1 2900 | #(pat_1 ... pat_n) vector of n elements 2901 | #(pat_1 ... pat_n pat_n+1 ooo) vector of n or more, each element 2902 of remainder must match pat_n+1 2903 | #&pat box 2904 | ($ record-name pat_1 ... pat_n) a record 2905 | (= field pat) a ``field'' of an object 2906 | (and pat_1 ... pat_n) if all of pat_1 thru pat_n match 2907 | (or pat_1 ... pat_n) if any of pat_1 thru pat_n match 2908 | (not pat_1 ... pat_n) if all pat_1 thru pat_n don't match 2909 | (? predicate pat_1 ... pat_n) if predicate true and all of 2910 pat_1 thru pat_n match 2911 | (set! identifier) anything, and binds setter 2912 | (get! identifier) anything, and binds getter 2913 | `qp a quasi-pattern 2914 | (identifier *** pat) matches pat in a tree and binds 2915 identifier to the path leading 2916 to the object that matches pat 2917 2918ooo ::= ... zero or more 2919 | ___ zero or more 2920 | ..1 1 or more 2921 2922 quasi-patterns: matches: 2923 2924qp ::= () the empty list 2925 | #t #t 2926 | #f #f 2927 | string a string 2928 | number a number 2929 | character a character 2930 | identifier a symbol 2931 | (qp_1 ... qp_n) list of n elements 2932 | (qp_1 ... qp_n . qp_{n+1}) list of n or more 2933 | (qp_1 ... qp_n qp_n+1 ooo) list of n or more, each element 2934 of remainder must match qp_n+1 2935 | #(qp_1 ... qp_n) vector of n elements 2936 | #(qp_1 ... qp_n qp_n+1 ooo) vector of n or more, each element 2937 of remainder must match qp_n+1 2938 | #&qp box 2939 | ,pat a pattern 2940 | ,@pat a pattern 2941 2942 The names ‘quote’, ‘quasiquote’, ‘unquote’, ‘unquote-splicing’, ‘?’, 2943‘_’, ‘$’, ‘and’, ‘or’, ‘not’, ‘set!’, ‘get!’, ‘...’, and ‘___’ cannot be 2944used as pattern variables. 2945 2946 Here is a more complex example: 2947 2948 (use-modules (srfi srfi-9)) 2949 2950 (let () 2951 (define-record-type person 2952 (make-person name friends) 2953 person? 2954 (name person-name) 2955 (friends person-friends)) 2956 2957 (letrec ((alice (make-person "Alice" (delay (list bob)))) 2958 (bob (make-person "Bob" (delay (list alice))))) 2959 (match alice 2960 (($ person name (= force (($ person "Bob")))) 2961 (list 'friend-of-bob name)) 2962 (_ #f)))) 2963 2964 ⇒ (friend-of-bob "Alice") 2965 2966Here the ‘$’ pattern is used to match a SRFI-9 record of type PERSON 2967containing two or more slots. The value of the first slot is bound to 2968NAME. The ‘=’ pattern is used to apply ‘force’ on the second slot, and 2969then checking that the result matches the given pattern. In other 2970words, the complete pattern matches any PERSON whose second slot is a 2971promise that evaluates to a one-element list containing a PERSON whose 2972first slot is ‘"Bob"’. 2973 2974 The ‘(ice-9 match)’ module also provides the following convenient 2975syntactic sugar macros wrapping around ‘match’. 2976 2977 -- Scheme Syntax: match-lambda clause1 clause2 ... 2978 Create a procedure of one argument that matches its argument 2979 against each clause, and returns the result of evaluating the 2980 corresponding expressions. 2981 2982 (match-lambda clause1 clause2 ...) 2983 ≡ 2984 (lambda (arg) (match arg clause1 clause2 ...)) 2985 2986 ((match-lambda 2987 (('hello (who)) 2988 who)) 2989 '(hello (world))) 2990 ⇒ world 2991 2992 -- Scheme Syntax: match-lambda* clause1 clause2 ... 2993 Create a procedure of any number of arguments that matches its 2994 argument list against each clause, and returns the result of 2995 evaluating the corresponding expressions. 2996 2997 (match-lambda* clause1 clause2 ...) 2998 ≡ 2999 (lambda args (match args clause1 clause2 ...)) 3000 3001 ((match-lambda* 3002 (('hello (who)) 3003 who)) 3004 'hello '(world)) 3005 ⇒ world 3006 3007 -- Scheme Syntax: match-let ((pattern expression) ...) body 3008 Match each pattern to the corresponding expression, and evaluate 3009 the body with all matched variables in scope. Raise an error if 3010 any of the expressions fail to match. ‘match-let’ is analogous to 3011 named let and can also be used for recursive functions which match 3012 on their arguments as in ‘match-lambda*’. 3013 3014 (match-let (((x y) (list 1 2)) 3015 ((a b) (list 3 4))) 3016 (list a b x y)) 3017 ⇒ 3018 (3 4 1 2) 3019 3020 -- Scheme Syntax: match-let variable ((pattern init) ...) body 3021 Similar to ‘match-let’, but analogously to “named let”, locally 3022 bind VARIABLE to a new procedure which accepts as many arguments as 3023 there are INIT expressions. The procedure is initially applied to 3024 the results of evaluating the INIT expressions. When called, the 3025 procedure matches each argument against the corresponding PATTERN, 3026 and returns the result(s) of evaluating the BODY expressions. 3027 *Note Iteration: while do, for more on “named let”. 3028 3029 -- Scheme Syntax: match-let* ((variable expression) ...) body 3030 Similar to ‘match-let’, but analogously to ‘let*’, match and bind 3031 the variables in sequence, with preceding match variables in scope. 3032 3033 (match-let* (((x y) (list 1 2)) 3034 ((a b) (list x 4))) 3035 (list a b x y)) 3036 ≡ 3037 (match-let (((x y) (list 1 2))) 3038 (match-let (((a b) (list x 4))) 3039 (list a b x y))) 3040 ⇒ 3041 (1 4 1 2) 3042 3043 -- Scheme Syntax: match-letrec ((variable expression) ...) body 3044 Similar to ‘match-let’, but analogously to ‘letrec’, match and bind 3045 the variables with all match variables in scope. 3046 3047 Guile also comes with a pattern matcher specifically tailored to SXML 3048trees, *Note sxml-match::. 3049 3050 3051File: guile.info, Node: Readline Support, Next: Pretty Printing, Prev: Pattern Matching, Up: Guile Modules 3052 30537.9 Readline Support 3054==================== 3055 3056Guile comes with an interface module to the readline library (*note 3057(readline)Top::). This makes interactive use much more convenient, 3058because of the command-line editing features of readline. Using ‘(ice-9 3059readline)’, you can navigate through the current input line with the 3060cursor keys, retrieve older command lines from the input history and 3061even search through the history entries. 3062 3063* Menu: 3064 3065* Loading Readline Support:: How to load readline support into Guile. 3066* Readline Options:: How to modify readline’s behaviour. 3067* Readline Functions:: Programming with readline. 3068 3069 3070File: guile.info, Node: Loading Readline Support, Next: Readline Options, Up: Readline Support 3071 30727.9.1 Loading Readline Support 3073------------------------------ 3074 3075The module is not loaded by default and so has to be loaded and 3076activated explicitly. This is done with two simple lines of code: 3077 3078 (use-modules (ice-9 readline)) 3079 (activate-readline) 3080 3081 The first line will load the necessary code, and the second will 3082activate readline’s features for the REPL. If you plan to use this 3083module often, you should save these to lines to your ‘.guile’ personal 3084startup file. 3085 3086 You will notice that the REPL’s behaviour changes a bit when you have 3087loaded the readline module. For example, when you press Enter before 3088typing in the closing parentheses of a list, you will see the 3089“continuation” prompt, three dots: ‘...’ This gives you a nice visual 3090feedback when trying to match parentheses. To make this even easier, 3091“bouncing parentheses” are implemented. That means that when you type 3092in a closing parentheses, the cursor will jump to the corresponding 3093opening parenthesis for a short time, making it trivial to make them 3094match. 3095 3096 Once the readline module is activated, all lines entered 3097interactively will be stored in a history and can be recalled later 3098using the cursor-up and -down keys. Readline also understands the Emacs 3099keys for navigating through the command line and history. 3100 3101 When you quit your Guile session by evaluating ‘(quit)’ or pressing 3102Ctrl-D, the history will be saved to the file ‘.guile_history’ and read 3103in when you start Guile for the next time. Thus you can start a new 3104Guile session and still have the (probably long-winded) definition 3105expressions available. 3106 3107 You can specify a different history file by setting the environment 3108variable ‘GUILE_HISTORY’. And you can make Guile specific 3109customizations to your ‘.inputrc’ by testing for application ‘Guile’ 3110(*note (readline)Conditional Init Constructs::). For instance to define 3111a key inserting a matched pair of parentheses, 3112 3113 $if Guile 3114 "\C-o": "()\C-b" 3115 $endif 3116 3117 3118File: guile.info, Node: Readline Options, Next: Readline Functions, Prev: Loading Readline Support, Up: Readline Support 3119 31207.9.2 Readline Options 3121---------------------- 3122 3123The readline interface module can be tweaked in a few ways to better 3124suit the user’s needs. Configuration is done via the readline module’s 3125options interface, in a similar way to the evaluator and debugging 3126options (*note Runtime Options::). 3127 3128 -- Scheme Procedure: readline-options 3129 -- Scheme Procedure: readline-enable option-name 3130 -- Scheme Procedure: readline-disable option-name 3131 -- Scheme Syntax: readline-set! option-name value 3132 Accessors for the readline options. Note that unlike the 3133 enable/disable procedures, ‘readline-set!’ is syntax, which expects 3134 an unquoted option name. 3135 3136 Here is the list of readline options generated by typing 3137‘(readline-options 'help)’ in Guile. You can also see the default 3138values. 3139 3140 history-file yes Use history file. 3141 history-length 200 History length. 3142 bounce-parens 500 Time (ms) to show matching opening parenthesis 3143 (0 = off). 3144 bracketed-paste yes Disable interpretation of control characters 3145 in pastes. 3146 3147 The readline options interface can only be used _after_ loading the 3148readline module, because it is defined in that module. 3149 3150 3151File: guile.info, Node: Readline Functions, Prev: Readline Options, Up: Readline Support 3152 31537.9.3 Readline Functions 3154------------------------ 3155 3156The following functions are provided by 3157 3158 (use-modules (ice-9 readline)) 3159 3160 There are two ways to use readline from Scheme code, either make 3161calls to ‘readline’ directly to get line by line input, or use the 3162readline port below with all the usual reading functions. 3163 3164 -- Function: readline [prompt] 3165 Read a line of input from the user and return it as a string 3166 (without a newline at the end). PROMPT is the prompt to show, or 3167 the default is the string set in ‘set-readline-prompt!’ below. 3168 3169 (readline "Type something: ") ⇒ "hello" 3170 3171 -- Function: set-readline-input-port! port 3172 -- Function: set-readline-output-port! port 3173 Set the input and output port the readline function should read 3174 from and write to. PORT must be a file port (*note File Ports::), 3175 and should usually be a terminal. 3176 3177 The default is the ‘current-input-port’ and ‘current-output-port’ 3178 (*note Default Ports::) when ‘(ice-9 readline)’ loads, which in an 3179 interactive user session means the Unix “standard input” and 3180 “standard output”. 3181 31827.9.3.1 Readline Port 3183..................... 3184 3185 -- Function: readline-port 3186 Return a buffered input port (*note Buffered Input::) which calls 3187 the ‘readline’ function above to get input. This port can be used 3188 with all the usual reading functions (‘read’, ‘read-char’, etc), 3189 and the user gets the interactive editing features of readline. 3190 3191 There’s only a single readline port created. ‘readline-port’ 3192 creates it when first called, and on subsequent calls just returns 3193 what it previously made. 3194 3195 -- Function: activate-readline 3196 If the ‘current-input-port’ is a terminal (*note ‘isatty?’: 3197 Terminals and Ptys.) then enable readline for all reading from 3198 ‘current-input-port’ (*note Default Ports::) and enable readline 3199 features in the interactive REPL (*note The REPL::). 3200 3201 (activate-readline) 3202 (read-char) 3203 3204 ‘activate-readline’ enables readline on ‘current-input-port’ simply 3205 by a ‘set-current-input-port’ to the ‘readline-port’ above. An 3206 application can do that directly if the extra REPL features that 3207 ‘activate-readline’ adds are not wanted. 3208 3209 -- Function: set-readline-prompt! prompt1 [prompt2] 3210 Set the prompt string to print when reading input. This is used 3211 when reading through ‘readline-port’, and is also the default 3212 prompt for the ‘readline’ function above. 3213 3214 PROMPT1 is the initial prompt shown. If a user might enter an 3215 expression across multiple lines, then PROMPT2 is a different 3216 prompt to show further input required. In the Guile REPL for 3217 instance this is an ellipsis (‘...’). 3218 3219 See ‘set-buffered-input-continuation?!’ (*note Buffered Input::) 3220 for an application to indicate the boundaries of logical 3221 expressions (assuming of course an application has such a notion). 3222 32237.9.3.2 Completion 3224.................. 3225 3226 -- Function: with-readline-completion-function completer thunk 3227 Call ‘(THUNK)’ with COMPLETER as the readline tab completion 3228 function to be used in any readline calls within that THUNK. 3229 COMPLETER can be ‘#f’ for no completion. 3230 3231 COMPLETER will be called as ‘(COMPLETER text state)’, as described 3232 in (*note (readline)How Completing Works::). TEXT is a partial 3233 word to be completed, and each COMPLETER call should return a 3234 possible completion string or ‘#f’ when no more. STATE is ‘#f’ for 3235 the first call asking about a new TEXT then ‘#t’ while getting 3236 further completions of that TEXT. 3237 3238 Here’s an example COMPLETER for user login names from the password 3239 file (*note User Information::), much like readline’s own 3240 ‘rl_username_completion_function’, 3241 3242 (define (username-completer-function text state) 3243 (if (not state) 3244 (setpwent)) ;; new, go to start of database 3245 (let more ((pw (getpwent))) 3246 (if pw 3247 (if (string-prefix? text (passwd:name pw)) 3248 (passwd:name pw) ;; this name matches, return it 3249 (more (getpwent))) ;; doesn't match, look at next 3250 (begin 3251 ;; end of database, close it and return #f 3252 (endpwent) 3253 #f)))) 3254 3255 -- Function: apropos-completion-function text state 3256 A completion function offering completions for Guile functions and 3257 variables (all ‘define’s). This is the default completion 3258 function. 3259 3260 -- Function: filename-completion-function text state 3261 A completion function offering filename completions. This is 3262 readline’s ‘rl_filename_completion_function’ (*note 3263 (readline)Completion Functions::). 3264 3265 -- Function: make-completion-function string-list 3266 Return a completion function which offers completions from the 3267 possibilities in STRING-LIST. Matching is case-sensitive. 3268 3269 3270File: guile.info, Node: Pretty Printing, Next: Formatted Output, Prev: Readline Support, Up: Guile Modules 3271 32727.10 Pretty Printing 3273==================== 3274 3275The module ‘(ice-9 pretty-print)’ provides the procedure ‘pretty-print’, 3276which provides nicely formatted output of Scheme objects. This is 3277especially useful for deeply nested or complex data structures, such as 3278lists and vectors. 3279 3280 The module is loaded by entering the following: 3281 3282 (use-modules (ice-9 pretty-print)) 3283 3284 This makes the procedure ‘pretty-print’ available. As an example how 3285‘pretty-print’ will format the output, see the following: 3286 3287 (pretty-print '(define (foo) (lambda (x) 3288 (cond ((zero? x) #t) ((negative? x) -x) (else 3289 (if (= x 1) 2 (* x x x))))))) 3290 ⊣ 3291 (define (foo) 3292 (lambda (x) 3293 (cond ((zero? x) #t) 3294 ((negative? x) -x) 3295 (else (if (= x 1) 2 (* x x x)))))) 3296 3297 -- Scheme Procedure: pretty-print obj [port] [keyword-options] 3298 Print the textual representation of the Scheme object OBJ to PORT. 3299 PORT defaults to the current output port, if not given. 3300 3301 The further KEYWORD-OPTIONS are keywords and parameters as follows, 3302 3303 #:display? FLAG 3304 If FLAG is true then print using ‘display’. The default is 3305 ‘#f’ which means use ‘write’ style. *Note Scheme Write::. 3306 3307 #:per-line-prefix STRING 3308 Print the given STRING as a prefix on each line. The default 3309 is no prefix. 3310 3311 #:width COLUMNS 3312 Print within the given COLUMNS. The default is 79. 3313 3314 #:max-expr-width COLUMNS 3315 The maximum width of an expression. The default is 50. 3316 3317 Also exported by the ‘(ice-9 pretty-print)’ module is 3318‘truncated-print’, a procedure to print Scheme datums, truncating the 3319output to a certain number of characters. This is useful when you need 3320to present an arbitrary datum to the user, but you only have one line in 3321which to do so. 3322 3323 (define exp '(a b #(c d e) f . g)) 3324 (truncated-print exp #:width 10) (newline) 3325 ⊣ (a b . #) 3326 (truncated-print exp #:width 15) (newline) 3327 ⊣ (a b # f . g) 3328 (truncated-print exp #:width 18) (newline) 3329 ⊣ (a b #(c ...) . #) 3330 (truncated-print exp #:width 20) (newline) 3331 ⊣ (a b #(c d e) f . g) 3332 (truncated-print "The quick brown fox" #:width 20) (newline) 3333 ⊣ "The quick brown..." 3334 (truncated-print (current-module) #:width 20) (newline) 3335 ⊣ #<directory (gui...> 3336 3337 ‘truncated-print’ will not output a trailing newline. If an 3338expression does not fit in the given width, it will be truncated – 3339possibly ellipsized(1), or in the worst case, displayed as #. 3340 3341 -- Scheme Procedure: truncated-print obj [port] [keyword-options] 3342 Print OBJ, truncating the output, if necessary, to make it fit into 3343 WIDTH characters. By default, OBJ will be printed using ‘write’, 3344 though that behavior can be overridden via the DISPLAY? keyword 3345 argument. 3346 3347 The default behaviour is to print depth-first, meaning that the 3348 entire remaining width will be available to each sub-expression of 3349 OBJ – e.g., if OBJ is a vector, each member of OBJ. One can 3350 attempt to “ration” the available width, trying to allocate it 3351 equally to each sub-expression, via the BREADTH-FIRST? keyword 3352 argument. 3353 3354 The further KEYWORD-OPTIONS are keywords and parameters as follows, 3355 3356 #:display? FLAG 3357 If FLAG is true then print using ‘display’. The default is 3358 ‘#f’ which means use ‘write’ style. *note Scheme Write::. 3359 3360 #:width COLUMNS 3361 Print within the given COLUMNS. The default is 79. 3362 3363 #:breadth-first? FLAG 3364 If FLAG is true, then allocate the available width 3365 breadth-first among elements of a compound data structure 3366 (list, vector, pair, etc.). The default is ‘#f’ which means 3367 that any element is allowed to consume all of the available 3368 width. 3369 3370 ---------- Footnotes ---------- 3371 3372 (1) On Unicode-capable ports, the ellipsis is represented by 3373character ‘HORIZONTAL ELLIPSIS’ (U+2026), otherwise it is represented by 3374three dots. 3375 3376 3377File: guile.info, Node: Formatted Output, Next: File Tree Walk, Prev: Pretty Printing, Up: Guile Modules 3378 33797.11 Formatted Output 3380===================== 3381 3382The ‘format’ function is a powerful way to print numbers, strings and 3383other objects together with literal text under the control of a format 3384string. This function is available from 3385 3386 (use-modules (ice-9 format)) 3387 3388 A format string is generally more compact and easier than using just 3389the standard procedures like ‘display’, ‘write’ and ‘newline’. 3390Parameters in the output string allow various output styles, and 3391parameters can be taken from the arguments for runtime flexibility. 3392 3393 ‘format’ is similar to the Common Lisp procedure of the same name, 3394but it’s not identical and doesn’t have quite all the features found in 3395Common Lisp. 3396 3397 C programmers will note the similarity between ‘format’ and ‘printf’, 3398though escape sequences are marked with ~ instead of %, and are more 3399powerful. 3400 3401 3402 -- Scheme Procedure: format dest fmt arg ... 3403 Write output specified by the FMT string to DEST. DEST can be an 3404 output port, ‘#t’ for ‘current-output-port’ (*note Default 3405 Ports::), or ‘#f’ to return the output as a string. 3406 3407 FMT can contain literal text to be output, and ~ escapes. Each 3408 escape has the form 3409 3410 ~ [param [, param...] [:] [@] code 3411 3412 code is a character determining the escape sequence. The : and @ 3413 characters are optional modifiers, one or both of which change the 3414 way various codes operate. Optional parameters are accepted by 3415 some codes too. Parameters have the following forms, 3416 3417 [+/-]number 3418 An integer, with optional + or -. 3419 ’ (apostrophe) 3420 The following character in the format string, for instance ’z 3421 for z. 3422 v 3423 The next function argument as the parameter. v stands for 3424 “variable”, a parameter can be calculated at runtime and 3425 included in the arguments. Upper case V can be used too. 3426 # 3427 The number of arguments remaining. (See ~* below for some 3428 usages.) 3429 3430 Parameters are separated by commas (,). A parameter can be left 3431 empty to keep its default value when supplying later parameters. 3432 3433 3434 The following escapes are available. The code letters are not 3435 case-sensitive, upper and lower case are the same. 3436 3437 ~a 3438 ~s 3439 Object output. Parameters: MINWIDTH, PADINC, MINPAD, PADCHAR. 3440 3441 ~a outputs an argument like ‘display’, ~s outputs an argument 3442 like ‘write’ (*note Scheme Write::). 3443 3444 (format #t "~a" "foo") ⊣ foo 3445 (format #t "~s" "foo") ⊣ "foo" 3446 3447 ~:a and ~:s put objects that don’t have an external 3448 representation in quotes like a string. 3449 3450 (format #t "~:a" car) ⊣ "#<primitive-procedure car>" 3451 3452 If the output is less than MINWIDTH characters (default 0), 3453 it’s padded on the right with PADCHAR (default space). ~@a 3454 and ~@s put the padding on the left instead. 3455 3456 (format #f "~5a" 'abc) ⇒ "abc " 3457 (format #f "~5,,,'-@a" 'abc) ⇒ "--abc" 3458 3459 MINPAD is a minimum for the padding then plus a multiple of 3460 PADINC. Ie. the padding is MINPAD + N * PADINC, where N is 3461 the smallest integer making the total object plus padding 3462 greater than or equal to MINWIDTH. The default MINPAD is 0 3463 and the default PADINC is 1 (imposing no minimum or multiple). 3464 3465 (format #f "~5,1,4a" 'abc) ⇒ "abc " 3466 3467 ~c 3468 Character. Parameter: CHARNUM. 3469 3470 Output a character. The default is to simply output, as per 3471 ‘write-char’ (*note Venerable Port Interfaces::). ~@c prints 3472 in ‘write’ style. ~:c prints control characters (ASCII 0 to 3473 31) in ^X form. 3474 3475 (format #t "~c" #\z) ⊣ z 3476 (format #t "~@c" #\z) ⊣ #\z 3477 (format #t "~:c" #\newline) ⊣ ^J 3478 3479 If the CHARNUM parameter is given then an argument is not 3480 taken but instead the character is ‘(integer->char CHARNUM)’ 3481 (*note Characters::). This can be used for instance to output 3482 characters given by their ASCII code. 3483 3484 (format #t "~65c") ⊣ A 3485 3486 ~d 3487 ~x 3488 ~o 3489 ~b 3490 Integer. Parameters: MINWIDTH, PADCHAR, COMMACHAR, 3491 COMMAWIDTH. 3492 3493 Output an integer argument as a decimal, hexadecimal, octal or 3494 binary integer (respectively), in a locale-independent way. 3495 3496 (format #t "~d" 123) ⊣ 123 3497 3498 ~@d etc shows a + sign is shown on positive numbers. 3499 3500 (format #t "~@b" 12) ⊣ +1100 3501 3502 If the output is less than the MINWIDTH parameter (default no 3503 minimum), it’s padded on the left with the PADCHAR parameter 3504 (default space). 3505 3506 (format #t "~5,'*d" 12) ⊣ ***12 3507 (format #t "~5,'0d" 12) ⊣ 00012 3508 (format #t "~3d" 1234) ⊣ 1234 3509 3510 ~:d adds commas (or the COMMACHAR parameter) every three 3511 digits (or the COMMAWIDTH parameter many). However, when your 3512 intent is to write numbers in a way that follows typographical 3513 conventions, using ~h is recommended. 3514 3515 (format #t "~:d" 1234567) ⊣ 1,234,567 3516 (format #t "~10,'*,'/,2:d" 12345) ⊣ ***1/23/45 3517 3518 Hexadecimal ~x output is in lower case, but the ~( and ~) case 3519 conversion directives described below can be used to get upper 3520 case. 3521 3522 (format #t "~x" 65261) ⊣ feed 3523 (format #t "~:@(~x~)" 65261) ⊣ FEED 3524 3525 ~r 3526 Integer in words, roman numerals, or a specified radix. 3527 Parameters: RADIX, MINWIDTH, PADCHAR, COMMACHAR, COMMAWIDTH. 3528 3529 With no parameters output is in words as a cardinal like 3530 “ten”, or ~:r prints an ordinal like “tenth”. 3531 3532 (format #t "~r" 9) ⊣ nine ;; cardinal 3533 (format #t "~r" -9) ⊣ minus nine ;; cardinal 3534 (format #t "~:r" 9) ⊣ ninth ;; ordinal 3535 3536 And also with no parameters, ~@r gives roman numerals and ~:@r 3537 gives old roman numerals. In old roman numerals there’s no 3538 “subtraction”, so 9 is VIIII instead of IX. In both cases only 3539 positive numbers can be output. 3540 3541 (format #t "~@r" 89) ⊣ LXXXIX ;; roman 3542 (format #t "~:@r" 89) ⊣ LXXXVIIII ;; old roman 3543 3544 When a parameter is given it means numeric output in the 3545 specified RADIX. The modifiers and parameters following the 3546 radix are the same as described for ~d etc above. 3547 3548 (format #f "~3r" 27) ⇒ "1000" ;; base 3 3549 (format #f "~3,5r" 26) ⇒ " 222" ;; base 3 width 5 3550 3551 ~f 3552 Fixed-point float. Parameters: WIDTH, DECIMALS, SCALE, 3553 OVERFLOWCHAR, PADCHAR. 3554 3555 Output a number or number string in fixed-point format, ie. 3556 with a decimal point. 3557 3558 (format #t "~f" 5) ⊣ 5.0 3559 (format #t "~f" "123") ⊣ 123.0 3560 (format #t "~f" "1e-1") ⊣ 0.1 3561 3562 ~@f prints a + sign on positive numbers (including zero). 3563 3564 (format #t "~@f" 0) ⊣ +0.0 3565 3566 If the output is less than WIDTH characters it’s padded on the 3567 left with PADCHAR (space by default). If the output equals or 3568 exceeds WIDTH then there’s no padding. The default for WIDTH 3569 is no padding. 3570 3571 (format #f "~6f" -1.5) ⇒ " -1.5" 3572 (format #f "~6,,,,'*f" 23) ⇒ "**23.0" 3573 (format #f "~6f" 1234567.0) ⇒ "1234567.0" 3574 3575 DECIMALS is how many digits to print after the decimal point, 3576 with the value rounded or padded with zeros as necessary. 3577 (The default is to output as many decimals as required.) 3578 3579 (format #t "~1,2f" 3.125) ⊣ 3.13 3580 (format #t "~1,2f" 1.5) ⊣ 1.50 3581 3582 SCALE is a power of 10 applied to the value, moving the 3583 decimal point that many places. A positive SCALE increases 3584 the value shown, a negative decreases it. 3585 3586 (format #t "~,,2f" 1234) ⊣ 123400.0 3587 (format #t "~,,-2f" 1234) ⊣ 12.34 3588 3589 If OVERFLOWCHAR and WIDTH are both given and if the output 3590 would exceed WIDTH, then that many OVERFLOWCHARs are printed 3591 instead of the value. 3592 3593 (format #t "~6,,,'xf" 12345) ⊣ 12345. 3594 (format #t "~5,,,'xf" 12345) ⊣ xxxxx 3595 3596 ~h 3597 Localized number(1). Parameters: WIDTH, DECIMALS, PADCHAR. 3598 3599 Like ~f, output an exact or floating point number, but do so 3600 according to the current locale, or according to the given 3601 locale object when the ‘:’ modifier is used (*note 3602 ‘number->locale-string’: Number Input and Output.). 3603 3604 (format #t "~h" 12345.5678) ; with "C" as the current locale 3605 ⊣ 12345.5678 3606 3607 (format #t "~14,,'*:h" 12345.5678 3608 (make-locale LC_ALL "en_US")) 3609 ⊣ ***12,345.5678 3610 3611 (format #t "~,2:h" 12345.5678 3612 (make-locale LC_NUMERIC "fr_FR")) 3613 ⊣ 12 345,56 3614 3615 ~e 3616 Exponential float. Parameters: WIDTH, MANTDIGITS, EXPDIGITS, 3617 INTDIGITS, OVERFLOWCHAR, PADCHAR, EXPCHAR. 3618 3619 Output a number or number string in exponential notation. 3620 3621 (format #t "~e" 5000.25) ⊣ 5.00025E+3 3622 (format #t "~e" "123.4") ⊣ 1.234E+2 3623 (format #t "~e" "1e4") ⊣ 1.0E+4 3624 3625 ~@e prints a + sign on positive numbers (including zero). 3626 (This is for the mantissa, a + or - sign is always shown on 3627 the exponent.) 3628 3629 (format #t "~@e" 5000.0) ⊣ +5.0E+3 3630 3631 If the output is less than WIDTH characters it’s padded on the 3632 left with PADCHAR (space by default). The default for WIDTH 3633 is to output with no padding. 3634 3635 (format #f "~10e" 1234.0) ⇒ " 1.234E+3" 3636 (format #f "~10,,,,,'*e" 0.5) ⇒ "****5.0E-1" 3637 3638 MANTDIGITS is the number of digits shown in the mantissa after 3639 the decimal point. The value is rounded or trailing zeros are 3640 added as necessary. The default MANTDIGITS is to show as much 3641 as needed by the value. 3642 3643 (format #f "~,3e" 11111.0) ⇒ "1.111E+4" 3644 (format #f "~,8e" 123.0) ⇒ "1.23000000E+2" 3645 3646 EXPDIGITS is the minimum number of digits shown for the 3647 exponent, with leading zeros added if necessary. The default 3648 for EXPDIGITS is to show only as many digits as required. At 3649 least 1 digit is always shown. 3650 3651 (format #f "~,,1e" 1.0e99) ⇒ "1.0E+99" 3652 (format #f "~,,6e" 1.0e99) ⇒ "1.0E+000099" 3653 3654 INTDIGITS (default 1) is the number of digits to show before 3655 the decimal point in the mantissa. INTDIGITS can be zero, in 3656 which case the integer part is a single 0, or it can be 3657 negative, in which case leading zeros are shown after the 3658 decimal point. 3659 3660 (format #t "~,,,3e" 12345.0) ⊣ 123.45E+2 3661 (format #t "~,,,0e" 12345.0) ⊣ 0.12345E+5 3662 (format #t "~,,,-3e" 12345.0) ⊣ 0.00012345E+8 3663 3664 If OVERFLOWCHAR is given then WIDTH is a hard limit. If the 3665 output would exceed WIDTH then instead that many OVERFLOWCHARs 3666 are printed. 3667 3668 (format #f "~6,,,,'xe" 100.0) ⇒ "1.0E+2" 3669 (format #f "~3,,,,'xe" 100.0) ⇒ "xxx" 3670 3671 EXPCHAR is the exponent marker character (default E). 3672 3673 (format #t "~,,,,,,'ee" 100.0) ⊣ 1.0e+2 3674 3675 ~g 3676 General float. Parameters: WIDTH, MANTDIGITS, EXPDIGITS, 3677 INTDIGITS, OVERFLOWCHAR, PADCHAR, EXPCHAR. 3678 3679 Output a number or number string in either exponential format 3680 the same as ~e, or fixed-point format like ~f but aligned 3681 where the mantissa would have been and followed by padding 3682 where the exponent would have been. 3683 3684 Fixed-point is used when the absolute value is 0.1 or more and 3685 it takes no more space than the mantissa in exponential 3686 format, ie. basically up to MANTDIGITS digits. 3687 3688 (format #f "~12,4,2g" 999.0) ⇒ " 999.0 " 3689 (format #f "~12,4,2g" "100000") ⇒ " 1.0000E+05" 3690 3691 The parameters are interpreted as per ~e above. When 3692 fixed-point is used, the DECIMALS parameter to ~f is 3693 established from MANTDIGITS, so as to give a total 3694 MANTDIGITS+1 figures. 3695 3696 ~$ 3697 Monetary style fixed-point float. Parameters: DECIMALS, 3698 INTDIGITS, WIDTH, PADCHAR. 3699 3700 Output a number or number string in fixed-point format, ie. 3701 with a decimal point. DECIMALS is the number of decimal 3702 places to show, default 2. 3703 3704 (format #t "~$" 5) ⊣ 5.00 3705 (format #t "~4$" "2.25") ⊣ 2.2500 3706 (format #t "~4$" "1e-2") ⊣ 0.0100 3707 3708 ~@$ prints a + sign on positive numbers (including zero). 3709 3710 (format #t "~@$" 0) ⊣ +0.00 3711 3712 INTDIGITS is a minimum number of digits to show in the integer 3713 part of the value (default 1). 3714 3715 (format #t "~,3$" 9.5) ⊣ 009.50 3716 (format #t "~,0$" 0.125) ⊣ .13 3717 3718 If the output is less than WIDTH characters (default 0), it’s 3719 padded on the left with PADCHAR (default space). ~:$ puts the 3720 padding after the sign. 3721 3722 (format #f "~,,8$" -1.5) ⇒ " -1.50" 3723 (format #f "~,,8:$" -1.5) ⇒ "- 1.50" 3724 (format #f "~,,8,'.:@$" 3) ⇒ "+...3.00" 3725 3726 Note that floating point for dollar amounts is generally not a 3727 good idea, because a cent 0.01 cannot be represented exactly 3728 in the binary floating point Guile uses, which leads to slowly 3729 accumulating rounding errors. Keeping values as cents (or 3730 fractions of a cent) in integers then printing with the scale 3731 option in ~f may be a better approach. 3732 3733 ~i 3734 Complex fixed-point float. Parameters: WIDTH, DECIMALS, 3735 SCALE, OVERFLOWCHAR, PADCHAR. 3736 3737 Output the argument as a complex number, with both real and 3738 imaginary part shown (even if one or both are zero). 3739 3740 The parameters and modifiers are the same as for fixed-point 3741 ~f described above. The real and imaginary parts are both 3742 output with the same given parameters and modifiers, except 3743 that for the imaginary part the @ modifier is always enabled, 3744 so as to print a + sign between the real and imaginary parts. 3745 3746 (format #t "~i" 1) ⊣ 1.0+0.0i 3747 3748 ~p 3749 Plural. No parameters. 3750 3751 Output nothing if the argument is 1, or ‘s’ for any other 3752 value. 3753 3754 (format #t "enter name~p" 1) ⊣ enter name 3755 (format #t "enter name~p" 2) ⊣ enter names 3756 3757 ~@p prints ‘y’ for 1 or ‘ies’ otherwise. 3758 3759 (format #t "pupp~@p" 1) ⊣ puppy 3760 (format #t "pupp~@p" 2) ⊣ puppies 3761 3762 ~:p re-uses the preceding argument instead of taking a new 3763 one, which can be convenient when printing some sort of count. 3764 3765 (format #t "~d cat~:p" 9) ⊣ 9 cats 3766 (format #t "~d pupp~:@p" 5) ⊣ 5 puppies 3767 3768 ~p is designed for English plurals and there’s no attempt to 3769 support other languages. ~[ conditionals (below) may be able 3770 to help. When using ‘gettext’ to translate messages 3771 ‘ngettext’ is probably best though (*note 3772 Internationalization::). 3773 3774 ~y 3775 Structured printing. Parameters: WIDTH. 3776 3777 ~y outputs an argument using ‘pretty-print’ (*note Pretty 3778 Printing::). The result will be formatted to fit within WIDTH 3779 columns (79 by default), consuming multiple lines if 3780 necessary. 3781 3782 ~@y outputs an argument using ‘truncated-print’ (*note Pretty 3783 Printing::). The resulting code will be formatted to fit 3784 within WIDTH columns (79 by default), on a single line. The 3785 output will be truncated if necessary. 3786 3787 ~:@y is like ~@y, except the WIDTH parameter is interpreted to 3788 be the maximum column to which to output. That is to say, if 3789 you are at column 10, and ~60:@y is seen, the datum will be 3790 truncated to 50 columns. 3791 3792 ~? 3793 ~k 3794 Sub-format. No parameters. 3795 3796 Take a format string argument and a second argument which is a 3797 list of arguments for that string, and output the result. 3798 3799 (format #t "~?" "~d ~d" '(1 2)) ⊣ 1 2 3800 3801 ~@? takes arguments for the sub-format directly rather than 3802 in a list. 3803 3804 (format #t "~@? ~s" "~d ~d" 1 2 "foo") ⊣ 1 2 "foo" 3805 3806 ~? and ~k are the same, ~k is provided for T-Scheme 3807 compatibility. 3808 3809 ~* 3810 Argument jumping. Parameter: N. 3811 3812 Move forward N arguments (default 1) in the argument list. 3813 ~:* moves backwards. (N cannot be negative.) 3814 3815 (format #f "~d ~2*~d" 1 2 3 4) ⇒ "1 4" 3816 (format #f "~d ~:*~d" 6) ⇒ "6 6" 3817 3818 ~@* moves to argument number N. The first argument is number 3819 0 (and that’s the default for N). 3820 3821 (format #f "~d~d again ~@*~d~d" 1 2) ⇒ "12 again 12" 3822 (format #f "~d~d~d ~1@*~d~d" 1 2 3) ⇒ "123 23" 3823 3824 A # move to the end followed by a : modifier move back can be 3825 used for an absolute position relative to the end of the 3826 argument list, a reverse of what the @ modifier does. 3827 3828 (format #t "~#*~2:*~a" 'a 'b 'c 'd) ⊣ c 3829 3830 At the end of the format string the current argument position 3831 doesn’t matter, any further arguments are ignored. 3832 3833 ~t 3834 Advance to a column position. Parameters: COLNUM, COLINC, 3835 PADCHAR. 3836 3837 Output PADCHAR (space by default) to move to the given COLNUM 3838 column. The start of the line is column 0, the default for 3839 COLNUM is 1. 3840 3841 (format #f "~tX") ⇒ " X" 3842 (format #f "~3tX") ⇒ " X" 3843 3844 If the current column is already past COLNUM, then the move is 3845 to there plus a multiple of COLINC, ie. column COLNUM + N * 3846 COLINC for the smallest N which makes that value greater than 3847 or equal to the current column. The default COLINC is 1 3848 (which means no further move). 3849 3850 (format #f "abcd~2,5,'.tx") ⇒ "abcd...x" 3851 3852 ~@t takes COLNUM as an offset from the current column. COLNUM 3853 many pad characters are output, then further padding to make 3854 the current column a multiple of COLINC, if it isn’t already 3855 so. 3856 3857 (format #f "a~3,5'*@tx") ⇒ "a****x" 3858 3859 ~t is implemented using ‘port-column’ (*note Textual I/O::), 3860 so it works even there has been other output before ‘format’. 3861 3862 ~~ 3863 Tilde character. Parameter: N. 3864 3865 Output a tilde character ~, or N many if a parameter is given. 3866 Normally ~ introduces an escape sequence, ~~ is the way to 3867 output a literal tilde. 3868 3869 ~% 3870 Newline. Parameter: N. 3871 3872 Output a newline character, or N many if a parameter is given. 3873 A newline (or a few newlines) can of course be output just by 3874 including them in the format string. 3875 3876 ~& 3877 Start a new line. Parameter: N. 3878 3879 Output a newline if not already at the start of a line. With 3880 a parameter, output that many newlines, but with the first 3881 only if not already at the start of a line. So for instance 3 3882 would be a newline if not already at the start of a line, and 3883 2 further newlines. 3884 3885 ~_ 3886 Space character. Parameter: N. 3887 3888 Output a space character, or N many if a parameter is given. 3889 3890 With a variable parameter this is one way to insert runtime 3891 calculated padding (~t or the various field widths can do 3892 similar things). 3893 3894 (format #f "~v_foo" 4) ⇒ " foo" 3895 3896 ~/ 3897 Tab character. Parameter: N. 3898 3899 Output a tab character, or N many if a parameter is given. 3900 3901 ~| 3902 Formfeed character. Parameter: N. 3903 3904 Output a formfeed character, or N many if a parameter is 3905 given. 3906 3907 ~! 3908 Force output. No parameters. 3909 3910 At the end of output, call ‘force-output’ to flush any buffers 3911 on the destination (*note Buffering::). ~! can occur 3912 anywhere in the format string, but the force is done at the 3913 end of output. 3914 3915 When output is to a string (destination ‘#f’), ~! does 3916 nothing. 3917 3918 ~newline (ie. newline character) 3919 Continuation line. No parameters. 3920 3921 Skip this newline and any following whitespace in the format 3922 string, ie. don’t send it to the output. This can be used to 3923 break up a long format string for readability, but not print 3924 the extra whitespace. 3925 3926 (format #f "abc~ 3927 ~d def~ 3928 ~d" 1 2) ⇒ "abc1 def2" 3929 3930 ~:newline skips the newline but leaves any further whitespace 3931 to be printed normally. 3932 3933 ~@newline prints the newline then skips following whitespace. 3934 3935 ~( ~) 3936 Case conversion. No parameters. 3937 3938 Between ~( and ~) the case of all output is changed. The 3939 modifiers on ~( control the conversion. 3940 3941 ~( — lower case. 3942 ~:@( — upper case. 3943 3944 For example, 3945 3946 (format #t "~(Hello~)") ⊣ hello 3947 (format #t "~:@(Hello~)") ⊣ HELLO 3948 3949 In the future it’s intended the modifiers : and @ alone will 3950 capitalize the first letters of words, as per Common Lisp 3951 ‘format’, but the current implementation of this is flawed and 3952 not recommended for use. 3953 3954 Case conversions do not nest, currently. This might change in 3955 the future, but if it does then it will be to Common Lisp 3956 style where the outermost conversion has priority, overriding 3957 inner ones (making those fairly pointless). 3958 3959 ~{ ~} 3960 Iteration. Parameter: MAXREPS (for ~{). 3961 3962 The format between ~{ and ~} is iterated. The modifiers to ~{ 3963 determine how arguments are taken. The default is a list 3964 argument with each iteration successively consuming elements 3965 from it. This is a convenient way to output a whole list. 3966 3967 (format #t "~{~d~}" '(1 2 3)) ⊣ 123 3968 (format #t "~{~s=~d ~}" '("x" 1 "y" 2)) ⊣ "x"=1 "y"=2 3969 3970 ~:{ takes a single argument which is a list of lists, each of 3971 those contained lists gives the arguments for the iterated 3972 format. 3973 3974 (format #t "~:{~dx~d ~}" '((1 2) (3 4) (5 6))) 3975 ⊣ 1x2 3x4 5x6 3976 3977 ~@{ takes arguments directly, with each iteration successively 3978 consuming arguments. 3979 3980 (format #t "~@{~d~}" 1 2 3) ⊣ 123 3981 (format #t "~@{~s=~d ~}" "x" 1 "y" 2) ⊣ "x"=1 "y"=2 3982 3983 ~:@{ takes list arguments, one argument for each iteration, 3984 using that list for the format. 3985 3986 (format #t "~:@{~dx~d ~}" '(1 2) '(3 4) '(5 6)) 3987 ⊣ 1x2 3x4 5x6 3988 3989 Iterating stops when there are no more arguments or when the 3990 MAXREPS parameter to ~{ is reached (default no maximum). 3991 3992 (format #t "~2{~d~}" '(1 2 3 4)) ⊣ 12 3993 3994 If the format between ~{ and ~} is empty, then a format string 3995 argument is taken (before iteration argument(s)) and used 3996 instead. This allows a sub-format (like ~? above) to be 3997 iterated. 3998 3999 (format #t "~{~}" "~d" '(1 2 3)) ⊣ 123 4000 4001 Iterations can be nested, an inner iteration operates in the 4002 same way as described, but of course on the arguments the 4003 outer iteration provides it. This can be used to work into 4004 nested list structures. For example in the following the 4005 inner ~{~d~}x is applied to ‘(1 2)’ then ‘(3 4 5)’ etc. 4006 4007 (format #t "~{~{~d~}x~}" '((1 2) (3 4 5))) ⊣ 12x345x 4008 4009 See also ~^ below for escaping from iteration. 4010 4011 ~[ ~; ~] 4012 Conditional. Parameter: SELECTOR. 4013 4014 A conditional block is delimited by ~[ and ~], and ~; 4015 separates clauses within the block. ~[ takes an integer 4016 argument and that number clause is used. The first clause is 4017 number 0. 4018 4019 (format #f "~[peach~;banana~;mango~]" 1) ⇒ "banana" 4020 4021 The SELECTOR parameter can be used for the clause number, 4022 instead of taking an argument. 4023 4024 (format #f "~2[peach~;banana~;mango~]") ⇒ "mango" 4025 4026 If the clause number is out of range then nothing is output. 4027 Or the last clause can be ~:; to use that for a number out of 4028 range. 4029 4030 (format #f "~[banana~;mango~]" 99) ⇒ "" 4031 (format #f "~[banana~;mango~:;fruit~]" 99) ⇒ "fruit" 4032 4033 ~:[ treats the argument as a flag, and expects two clauses. 4034 The first is used if the argument is ‘#f’ or the second 4035 otherwise. 4036 4037 (format #f "~:[false~;not false~]" #f) ⇒ "false" 4038 (format #f "~:[false~;not false~]" 'abc) ⇒ "not false" 4039 4040 (let ((n 3)) 4041 (format #t "~d gnu~:[s are~; is~] here" n (= 1 n))) 4042 ⊣ 3 gnus are here 4043 4044 ~@[ also treats the argument as a flag, and expects one 4045 clause. If the argument is ‘#f’ then no output is produced 4046 and the argument is consumed, otherwise the clause is used and 4047 the argument is not consumed, it’s left for the clause. This 4048 can be used for instance to suppress output if ‘#f’ means 4049 something not available. 4050 4051 (format #f "~@[temperature=~d~]" 27) ⇒ "temperature=27" 4052 (format #f "~@[temperature=~d~]" #f) ⇒ "" 4053 4054 ~^ 4055 Escape. Parameters: VAL1, VAL2, VAL3. 4056 4057 Stop formatting if there are no more arguments. This can be 4058 used for instance to have a format string adapt to a variable 4059 number of arguments. 4060 4061 (format #t "~d~^ ~d" 1) ⊣ 1 4062 (format #t "~d~^ ~d" 1 2) ⊣ 1 2 4063 4064 Within a ~{ ~} iteration, ~^ stops the current iteration step 4065 if there are no more arguments to that step, but continuing 4066 with possible further steps and the rest of the format. This 4067 can be used for instance to avoid a separator on the last 4068 iteration, or to adapt to variable length argument lists. 4069 4070 (format #f "~{~d~^/~} go" '(1 2 3)) ⇒ "1/2/3 go" 4071 (format #f "~:{ ~d~^~d~} go" '((1) (2 3))) ⇒ " 1 23 go" 4072 4073 Within a ~? sub-format, ~^ operates just on that sub-format. 4074 If it terminates the sub-format then the originating format 4075 will still continue. 4076 4077 (format #t "~? items" "~d~^ ~d" '(1)) ⊣ 1 items 4078 (format #t "~? items" "~d~^ ~d" '(1 2)) ⊣ 1 2 items 4079 4080 The parameters to ~^ (which are numbers) change the condition 4081 used to terminate. For a single parameter, termination is 4082 when that value is zero (notice this makes plain ~^ equivalent 4083 to ~#^). For two parameters, termination is when those two 4084 are equal. For three parameters, termination is when VAL1 <= 4085 VAL2 and VAL2 <= VAL3. 4086 4087 ~q 4088 Inquiry message. Insert a copyright message into the output. 4089 4090 ~:q inserts the format implementation version. 4091 4092 4093 It’s an error if there are not enough arguments for the escapes in 4094 the format string, but any excess arguments are ignored. 4095 4096 Iterations ~{ ~} and conditionals ~[ ~; ~] can be nested, but must 4097 be properly nested, meaning the inner form must be entirely within 4098 the outer form. So it’s not possible, for instance, to try to 4099 conditionalize the endpoint of an iteration. 4100 4101 (format #t "~{ ~[ ... ~] ~}" ...) ;; good 4102 (format #t "~{ ~[ ... ~} ... ~]" ...) ;; bad 4103 4104 The same applies to case conversions ~( ~), they must properly nest 4105 with respect to iterations and conditionals (though currently a 4106 case conversion cannot nest within another case conversion). 4107 4108 When a sub-format (~?) is used, that sub-format string must be 4109 self-contained. It cannot for instance give a ~{ to begin an 4110 iteration form and have the ~} up in the originating format, or 4111 similar. 4112 4113 4114 Guile contains a ‘format’ procedure even when the module ‘(ice-9 4115format)’ is not loaded. The default ‘format’ is ‘simple-format’ (*note 4116Simple Output::), it doesn’t support all escape sequences documented in 4117this section, and will signal an error if you try to use one of them. 4118The reason for two versions is that the full ‘format’ is fairly large 4119and requires some time to load. ‘simple-format’ is often adequate too. 4120 4121 ---------- Footnotes ---------- 4122 4123 (1) The ~h format specifier first appeared in Guile version 2.0.6. 4124 4125 4126File: guile.info, Node: File Tree Walk, Next: Queues, Prev: Formatted Output, Up: Guile Modules 4127 41287.12 File Tree Walk 4129=================== 4130 4131The functions in this section traverse a tree of files and directories. 4132They come in two flavors: the first one is a high-level functional 4133interface, and the second one is similar to the C ‘ftw’ and ‘nftw’ 4134routines (*note (libc)Working with Directory Trees::). 4135 4136 (use-modules (ice-9 ftw)) 4137 4138 -- Scheme Procedure: file-system-tree file-name [enter? [stat]] 4139 Return a tree of the form ‘(FILE-NAME STAT CHILDREN ...)’ where 4140 STAT is the result of ‘(STAT FILE-NAME)’ and CHILDREN are similar 4141 structures for each file contained in FILE-NAME when it designates 4142 a directory. 4143 4144 The optional ENTER? predicate is invoked as ‘(ENTER? NAME STAT)’ 4145 and should return true to allow recursion into directory NAME; the 4146 default value is a procedure that always returns ‘#t’. When a 4147 directory does not match ENTER?, it nonetheless appears in the 4148 resulting tree, only with zero children. 4149 4150 The STAT argument is optional and defaults to ‘lstat’, as for 4151 ‘file-system-fold’ (see below.) 4152 4153 The example below shows how to obtain a hierarchical listing of the 4154 files under the ‘module/language’ directory in the Guile source 4155 tree, discarding their ‘stat’ info: 4156 4157 (use-modules (ice-9 match)) 4158 4159 (define remove-stat 4160 ;; Remove the `stat' object the `file-system-tree' provides 4161 ;; for each file in the tree. 4162 (match-lambda 4163 ((name stat) ; flat file 4164 name) 4165 ((name stat children ...) ; directory 4166 (list name (map remove-stat children))))) 4167 4168 (let ((dir (string-append (assq-ref %guile-build-info 'top_srcdir) 4169 "/module/language"))) 4170 (remove-stat (file-system-tree dir))) 4171 4172 ⇒ 4173 ("language" 4174 (("value" ("spec.go" "spec.scm")) 4175 ("scheme" 4176 ("spec.go" 4177 "spec.scm" 4178 "compile-tree-il.scm" 4179 "decompile-tree-il.scm" 4180 "decompile-tree-il.go" 4181 "compile-tree-il.go")) 4182 ("tree-il" 4183 ("spec.go" 4184 "fix-letrec.go" 4185 "inline.go" 4186 "fix-letrec.scm" 4187 "compile-glil.go" 4188 "spec.scm" 4189 "optimize.scm" 4190 "primitives.scm" 4191 ...)) 4192 ...)) 4193 4194 It is often desirable to process directories entries directly, rather 4195than building up a tree of entries in memory, like ‘file-system-tree’ 4196does. The following procedure, a “combinator”, is designed to allow 4197directory entries to be processed directly as a directory tree is 4198traversed; in fact, ‘file-system-tree’ is implemented in terms of it. 4199 4200 -- Scheme Procedure: file-system-fold enter? leaf down up skip error 4201 init file-name [stat] 4202 Traverse the directory at FILE-NAME, recursively, and return the 4203 result of the successive applications of the LEAF, DOWN, UP, and 4204 SKIP procedures as described below. 4205 4206 Enter sub-directories only when ‘(ENTER? PATH STAT RESULT)’ returns 4207 true. When a sub-directory is entered, call ‘(DOWN PATH STAT 4208 RESULT)’, where PATH is the path of the sub-directory and STAT the 4209 result of ‘(false-if-exception (STAT PATH))’; when it is left, call 4210 ‘(UP PATH STAT RESULT)’. 4211 4212 For each file in a directory, call ‘(LEAF PATH STAT RESULT)’. 4213 4214 When ENTER? returns ‘#f’, or when an unreadable directory is 4215 encountered, call ‘(SKIP PATH STAT RESULT)’. 4216 4217 When FILE-NAME names a flat file, ‘(LEAF PATH STAT INIT)’ is 4218 returned. 4219 4220 When an ‘opendir’ or STAT call fails, call ‘(ERROR PATH STAT ERRNO 4221 RESULT)’, with ERRNO being the operating system error number that 4222 was raised—e.g., ‘EACCES’—and STAT either ‘#f’ or the result of the 4223 STAT call for that entry, when available. 4224 4225 The special ‘.’ and ‘..’ entries are not passed to these 4226 procedures. The PATH argument to the procedures is a full file 4227 name—e.g., ‘"../foo/bar/gnu"’; if FILE-NAME is an absolute file 4228 name, then PATH is also an absolute file name. Files and 4229 directories, as identified by their device/inode number pair, are 4230 traversed only once. 4231 4232 The optional STAT argument defaults to ‘lstat’, which means that 4233 symbolic links are not followed; the ‘stat’ procedure can be used 4234 instead when symbolic links are to be followed (*note stat: File 4235 System.). 4236 4237 The example below illustrates the use of ‘file-system-fold’: 4238 4239 (define (total-file-size file-name) 4240 "Return the size in bytes of the files under FILE-NAME (similar 4241 to `du --apparent-size' with GNU Coreutils.)" 4242 4243 (define (enter? name stat result) 4244 ;; Skip version control directories. 4245 (not (member (basename name) '(".git" ".svn" "CVS")))) 4246 (define (leaf name stat result) 4247 ;; Return RESULT plus the size of the file at NAME. 4248 (+ result (stat:size stat))) 4249 4250 ;; Count zero bytes for directories. 4251 (define (down name stat result) result) 4252 (define (up name stat result) result) 4253 4254 ;; Likewise for skipped directories. 4255 (define (skip name stat result) result) 4256 4257 ;; Ignore unreadable files/directories but warn the user. 4258 (define (error name stat errno result) 4259 (format (current-error-port) "warning: ~a: ~a~%" 4260 name (strerror errno)) 4261 result) 4262 4263 (file-system-fold enter? leaf down up skip error 4264 0 ; initial counter is zero bytes 4265 file-name)) 4266 4267 (total-file-size ".") 4268 ⇒ 8217554 4269 4270 (total-file-size "/dev/null") 4271 ⇒ 0 4272 4273 The alternative C-like functions are described below. 4274 4275 -- Scheme Procedure: scandir name [select? [entry<?]] 4276 Return the list of the names of files contained in directory NAME 4277 that match predicate SELECT? (by default, all files). The returned 4278 list of file names is sorted according to ENTRY<?, which defaults 4279 to ‘string-locale<?’ such that file names are sorted in the 4280 locale’s alphabetical order (*note Text Collation::). Return ‘#f’ 4281 when NAME is unreadable or is not a directory. 4282 4283 This procedure is modeled after the C library function of the same 4284 name (*note (libc)Scanning Directory Content::). 4285 4286 -- Scheme Procedure: ftw startname proc ['hash-size n] 4287 Walk the file system tree descending from STARTNAME, calling PROC 4288 for each file and directory. 4289 4290 Hard links and symbolic links are followed. A file or directory is 4291 reported to PROC only once, and skipped if seen again in another 4292 place. One consequence of this is that ‘ftw’ is safe against 4293 circularly linked directory structures. 4294 4295 Each PROC call is ‘(PROC filename statinfo flag)’ and it should 4296 return ‘#t’ to continue, or any other value to stop. 4297 4298 FILENAME is the item visited, being STARTNAME plus a further path 4299 and the name of the item. STATINFO is the return from ‘stat’ 4300 (*note File System::) on FILENAME. FLAG is one of the following 4301 symbols, 4302 4303 ‘regular’ 4304 FILENAME is a file, this includes special files like devices, 4305 named pipes, etc. 4306 4307 ‘directory’ 4308 FILENAME is a directory. 4309 4310 ‘invalid-stat’ 4311 An error occurred when calling ‘stat’, so nothing is known. 4312 STATINFO is ‘#f’ in this case. 4313 4314 ‘directory-not-readable’ 4315 FILENAME is a directory, but one which cannot be read and 4316 hence won’t be recursed into. 4317 4318 ‘symlink’ 4319 FILENAME is a dangling symbolic link. Symbolic links are 4320 normally followed and their target reported, the link itself 4321 is reported if the target does not exist. 4322 4323 The return value from ‘ftw’ is ‘#t’ if it ran to completion, or 4324 otherwise the non-‘#t’ value from PROC which caused the stop. 4325 4326 Optional argument symbol ‘hash-size’ and an integer can be given to 4327 set the size of the hash table used to track items already visited. 4328 (*note Hash Table Reference::) 4329 4330 In the current implementation, returning non-‘#t’ from PROC is the 4331 only valid way to terminate ‘ftw’. PROC must not use ‘throw’ or 4332 similar to escape. 4333 4334 -- Scheme Procedure: nftw startname proc ['chdir] ['depth] ['hash-size 4335 n] ['mount] ['physical] 4336 Walk the file system tree starting at STARTNAME, calling PROC for 4337 each file and directory. ‘nftw’ has extra features over the basic 4338 ‘ftw’ described above. 4339 4340 Like ‘ftw’, hard links and symbolic links are followed. A file or 4341 directory is reported to PROC only once, and skipped if seen again 4342 in another place. One consequence of this is that ‘nftw’ is safe 4343 against circular linked directory structures. 4344 4345 Each PROC call is ‘(PROC filename statinfo flag base level)’ and it 4346 should return ‘#t’ to continue, or any other value to stop. 4347 4348 FILENAME is the item visited, being STARTNAME plus a further path 4349 and the name of the item. STATINFO is the return from ‘stat’ on 4350 FILENAME (*note File System::). BASE is an integer offset into 4351 FILENAME which is where the basename for this item begins. LEVEL 4352 is an integer giving the directory nesting level, starting from 0 4353 for the contents of STARTNAME (or that item itself if it’s a file). 4354 FLAG is one of the following symbols, 4355 4356 ‘regular’ 4357 FILENAME is a file, including special files like devices, 4358 named pipes, etc. 4359 4360 ‘directory’ 4361 FILENAME is a directory. 4362 4363 ‘directory-processed’ 4364 FILENAME is a directory, and its contents have all been 4365 visited. This flag is given instead of ‘directory’ when the 4366 ‘depth’ option below is used. 4367 4368 ‘invalid-stat’ 4369 An error occurred when applying ‘stat’ to FILENAME, so nothing 4370 is known about it. STATINFO is ‘#f’ in this case. 4371 4372 ‘directory-not-readable’ 4373 FILENAME is a directory, but one which cannot be read and 4374 hence won’t be recursed into. 4375 4376 ‘stale-symlink’ 4377 FILENAME is a dangling symbolic link. Links are normally 4378 followed and their target reported, the link itself is 4379 reported if its target does not exist. 4380 4381 ‘symlink’ 4382 When the ‘physical’ option described below is used, this 4383 indicates FILENAME is a symbolic link whose target exists (and 4384 is not being followed). 4385 4386 The following optional arguments can be given to modify the way 4387 ‘nftw’ works. Each is passed as a symbol (and ‘hash-size’ takes a 4388 following integer value). 4389 4390 ‘chdir’ 4391 Change to the directory containing the item before calling 4392 PROC. When ‘nftw’ returns the original current directory is 4393 restored. 4394 4395 Under this option, generally the BASE parameter to each PROC 4396 call should be used to pick out the base part of the FILENAME. 4397 The FILENAME is still a path but with a changed directory it 4398 won’t be valid (unless the STARTNAME directory was absolute). 4399 4400 ‘depth’ 4401 Visit files “depth first”, meaning PROC is called for the 4402 contents of each directory before it’s called for the 4403 directory itself. Normally a directory is reported first, 4404 then its contents. 4405 4406 Under this option, the FLAG to PROC for a directory is 4407 ‘directory-processed’ instead of ‘directory’. 4408 4409 ‘hash-size N’ 4410 Set the size of the hash table used to track items already 4411 visited. (*note Hash Table Reference::) 4412 4413 ‘mount’ 4414 Don’t cross a mount point, meaning only visit items on the 4415 same file system as STARTNAME (ie. the same ‘stat:dev’). 4416 4417 ‘physical’ 4418 Don’t follow symbolic links, instead report them to PROC as 4419 ‘symlink’. Dangling links (those whose target doesn’t exist) 4420 are still reported as ‘stale-symlink’. 4421 4422 The return value from ‘nftw’ is ‘#t’ if it ran to completion, or 4423 otherwise the non-‘#t’ value from PROC which caused the stop. 4424 4425 In the current implementation, returning non-‘#t’ from PROC is the 4426 only valid way to terminate ‘ftw’. PROC must not use ‘throw’ or 4427 similar to escape. 4428 4429 4430File: guile.info, Node: Queues, Next: Streams, Prev: File Tree Walk, Up: Guile Modules 4431 44327.13 Queues 4433=========== 4434 4435The functions in this section are provided by 4436 4437 (use-modules (ice-9 q)) 4438 4439 This module implements queues holding arbitrary scheme objects and 4440designed for efficient first-in / first-out operations. 4441 4442 ‘make-q’ creates a queue, and objects are entered and removed with 4443‘enq!’ and ‘deq!’. ‘q-push!’ and ‘q-pop!’ can be used too, treating the 4444front of the queue like a stack. 4445 4446 4447 -- Scheme Procedure: make-q 4448 Return a new queue. 4449 4450 -- Scheme Procedure: q? obj 4451 Return ‘#t’ if OBJ is a queue, or ‘#f’ if not. 4452 4453 Note that queues are not a distinct class of objects but are 4454 implemented with cons cells. For that reason certain list 4455 structures can get ‘#t’ from ‘q?’. 4456 4457 -- Scheme Procedure: enq! q obj 4458 Add OBJ to the rear of Q, and return Q. 4459 4460 -- Scheme Procedure: deq! q 4461 -- Scheme Procedure: q-pop! q 4462 Remove and return the front element from Q. If Q is empty, a 4463 ‘q-empty’ exception is thrown. 4464 4465 ‘deq!’ and ‘q-pop!’ are the same operation, the two names just let 4466 an application match ‘enq!’ with ‘deq!’, or ‘q-push!’ with 4467 ‘q-pop!’. 4468 4469 -- Scheme Procedure: q-push! q obj 4470 Add OBJ to the front of Q, and return Q. 4471 4472 -- Scheme Procedure: q-length q 4473 Return the number of elements in Q. 4474 4475 -- Scheme Procedure: q-empty? q 4476 Return true if Q is empty. 4477 4478 -- Scheme Procedure: q-empty-check q 4479 Throw a ‘q-empty’ exception if Q is empty. 4480 4481 -- Scheme Procedure: q-front q 4482 Return the first element of Q (without removing it). If Q is 4483 empty, a ‘q-empty’ exception is thrown. 4484 4485 -- Scheme Procedure: q-rear q 4486 Return the last element of Q (without removing it). If Q is empty, 4487 a ‘q-empty’ exception is thrown. 4488 4489 -- Scheme Procedure: q-remove! q obj 4490 Remove all occurrences of OBJ from Q, and return Q. OBJ is 4491 compared to queue elements using ‘eq?’. 4492 4493 4494 The ‘q-empty’ exceptions described above are thrown just as ‘(throw 4495'q-empty)’, there’s no message etc like an error throw. 4496 4497 A queue is implemented as a cons cell, the ‘car’ containing a list of 4498queued elements, and the ‘cdr’ being the last cell in that list (for 4499ease of enqueuing). 4500 4501 (LIST . LAST-CELL) 4502 4503If the queue is empty, LIST is the empty list and LAST-CELL is ‘#f’. 4504 4505 An application can directly access the queue list if desired, for 4506instance to search the elements or to insert at a specific point. 4507 4508 -- Scheme Procedure: sync-q! q 4509 Recompute the LAST-CELL field in Q. 4510 4511 All the operations above maintain LAST-CELL as described, so 4512 normally there’s no need for ‘sync-q!’. But if an application 4513 modifies the queue LIST then it must either maintain LAST-CELL 4514 similarly, or call ‘sync-q!’ to recompute it. 4515 4516 4517File: guile.info, Node: Streams, Next: Buffered Input, Prev: Queues, Up: Guile Modules 4518 45197.14 Streams 4520============ 4521 4522This section documents Guile’s legacy stream module. For a more 4523complete and portable stream library, *note SRFI-41::. 4524 4525 A stream represents a sequence of values, each of which is calculated 4526only when required. This allows large or even infinite sequences to be 4527represented and manipulated with familiar operations like “car”, “cdr”, 4528“map” or “fold”. In such manipulations only as much as needed is 4529actually held in memory at any one time. The functions in this section 4530are available from 4531 4532 (use-modules (ice-9 streams)) 4533 4534 Streams are implemented using promises (*note Delayed Evaluation::), 4535which is how the underlying calculation of values is made only when 4536needed, and the values then retained so the calculation is not repeated. 4537 4538Here is a simple example producing a stream of all odd numbers, 4539 4540 (define odds (make-stream (lambda (state) 4541 (cons state (+ state 2))) 4542 1)) 4543 (stream-car odds) ⇒ 1 4544 (stream-car (stream-cdr odds)) ⇒ 3 4545 4546‘stream-map’ could be used to derive a stream of odd squares, 4547 4548 (define (square n) (* n n)) 4549 (define oddsquares (stream-map square odds)) 4550 4551 These are infinite sequences, so it’s not possible to convert them to 4552a list, but they could be printed (infinitely) with for example 4553 4554 (stream-for-each (lambda (n sq) 4555 (format #t "~a squared is ~a\n" n sq)) 4556 odds oddsquares) 4557 ⊣ 4558 1 squared is 1 4559 3 squared is 9 4560 5 squared is 25 4561 7 squared is 49 4562 ... 4563 4564 4565 -- Scheme Procedure: make-stream proc initial-state 4566 Return a new stream, formed by calling PROC successively. 4567 4568 Each call is ‘(PROC STATE)’, it should return a pair, the ‘car’ 4569 being the value for the stream, and the ‘cdr’ being the new STATE 4570 for the next call. For the first call STATE is the given 4571 INITIAL-STATE. At the end of the stream, PROC should return some 4572 non-pair object. 4573 4574 -- Scheme Procedure: stream-car stream 4575 Return the first element from STREAM. STREAM must not be empty. 4576 4577 -- Scheme Procedure: stream-cdr stream 4578 Return a stream which is the second and subsequent elements of 4579 STREAM. STREAM must not be empty. 4580 4581 -- Scheme Procedure: stream-null? stream 4582 Return true if STREAM is empty. 4583 4584 -- Scheme Procedure: list->stream list 4585 -- Scheme Procedure: vector->stream vector 4586 Return a stream with the contents of LIST or VECTOR. 4587 4588 LIST or VECTOR should not be modified subsequently, since it’s 4589 unspecified whether changes there will be reflected in the stream 4590 returned. 4591 4592 -- Scheme Procedure: port->stream port readproc 4593 Return a stream which is the values obtained by reading from PORT 4594 using READPROC. Each read call is ‘(READPROC PORT)’, and it should 4595 return an EOF object (*note Binary I/O::) at the end of input. 4596 4597 For example a stream of characters from a file, 4598 4599 (port->stream (open-input-file "/foo/bar.txt") read-char) 4600 4601 -- Scheme Procedure: stream->list stream 4602 Return a list which is the entire contents of STREAM. 4603 4604 -- Scheme Procedure: stream->reversed-list stream 4605 Return a list which is the entire contents of STREAM, but in 4606 reverse order. 4607 4608 -- Scheme Procedure: stream->list&length stream 4609 Return two values (*note Multiple Values::), being firstly a list 4610 which is the entire contents of STREAM, and secondly the number of 4611 elements in that list. 4612 4613 -- Scheme Procedure: stream->reversed-list&length stream 4614 Return two values (*note Multiple Values::) being firstly a list 4615 which is the entire contents of STREAM, but in reverse order, and 4616 secondly the number of elements in that list. 4617 4618 -- Scheme Procedure: stream->vector stream 4619 Return a vector which is the entire contents of STREAM. 4620 4621 -- Function: stream-fold proc init stream1 stream2 ... 4622 Apply PROC successively over the elements of the given streams, 4623 from first to last until the end of the shortest stream is reached. 4624 Return the result from the last PROC call. 4625 4626 Each call is ‘(PROC elem1 elem2 ... prev)’, where each ELEM is from 4627 the corresponding STREAM. PREV is the return from the previous 4628 PROC call, or the given INIT for the first call. 4629 4630 -- Function: stream-for-each proc stream1 stream2 ... 4631 Call PROC on the elements from the given STREAMs. The return value 4632 is unspecified. 4633 4634 Each call is ‘(PROC elem1 elem2 ...)’, where each ELEM is from the 4635 corresponding STREAM. ‘stream-for-each’ stops when it reaches the 4636 end of the shortest STREAM. 4637 4638 -- Function: stream-map proc stream1 stream2 ... 4639 Return a new stream which is the results of applying PROC to the 4640 elements of the given STREAMs. 4641 4642 Each call is ‘(PROC elem1 elem2 ...)’, where each ELEM is from the 4643 corresponding STREAM. The new stream ends when the end of the 4644 shortest given STREAM is reached. 4645 4646 4647File: guile.info, Node: Buffered Input, Next: Expect, Prev: Streams, Up: Guile Modules 4648 46497.15 Buffered Input 4650=================== 4651 4652The following functions are provided by 4653 4654 (use-modules (ice-9 buffered-input)) 4655 4656 A buffered input port allows a reader function to return chunks of 4657characters which are to be handed out on reading the port. A notion of 4658further input for an application level logical expression is maintained 4659too, and passed through to the reader. 4660 4661 -- Scheme Procedure: make-buffered-input-port reader 4662 Create an input port which returns characters obtained from the 4663 given READER function. READER is called (READER cont), and should 4664 return a string or an EOF object. 4665 4666 The new port gives precisely the characters returned by READER, 4667 nothing is added, so if any newline characters or other separators 4668 are desired they must come from the reader function. 4669 4670 The CONT parameter to READER is ‘#f’ for initial input, or ‘#t’ 4671 when continuing an expression. This is an application level 4672 notion, set with ‘set-buffered-input-continuation?!’ below. If the 4673 user has entered a partial expression then it allows READER for 4674 instance to give a different prompt to show more is required. 4675 4676 -- Scheme Procedure: make-line-buffered-input-port reader 4677 Create an input port which returns characters obtained from the 4678 specified READER function, similar to ‘make-buffered-input-port’ 4679 above, but where READER is expected to be a line-oriented. 4680 4681 READER is called (READER cont), and should return a string or an 4682 EOF object as above. Each string is a line of input without a 4683 newline character, the port code inserts a newline after each 4684 string. 4685 4686 -- Scheme Procedure: set-buffered-input-continuation?! port cont 4687 Set the input continuation flag for a given buffered input PORT. 4688 4689 An application uses this by calling with a CONT flag of ‘#f’ when 4690 beginning to read a new logical expression. For example with the 4691 Scheme ‘read’ function (*note Scheme Read::), 4692 4693 (define my-port (make-buffered-input-port my-reader)) 4694 4695 (set-buffered-input-continuation?! my-port #f) 4696 (let ((obj (read my-port))) 4697 ... 4698 4699 4700File: guile.info, Node: Expect, Next: sxml-match, Prev: Buffered Input, Up: Guile Modules 4701 47027.16 Expect 4703=========== 4704 4705The macros in this section are made available with: 4706 4707 (use-modules (ice-9 expect)) 4708 4709 ‘expect’ is a macro for selecting actions based on the output from a 4710port. The name comes from a tool of similar functionality by Don Libes. 4711Actions can be taken when a particular string is matched, when a timeout 4712occurs, or when end-of-file is seen on the port. The ‘expect’ macro is 4713described below; ‘expect-strings’ is a front-end to ‘expect’ based on 4714regexec (see the regular expression documentation). 4715 4716 -- Macro: expect-strings clause ... 4717 By default, ‘expect-strings’ will read from the current input port. 4718 The first term in each clause consists of an expression evaluating 4719 to a string pattern (regular expression). As characters are read 4720 one-by-one from the port, they are accumulated in a buffer string 4721 which is matched against each of the patterns. When a pattern 4722 matches, the remaining expression(s) in the clause are evaluated 4723 and the value of the last is returned. For example: 4724 4725 (with-input-from-file "/etc/passwd" 4726 (lambda () 4727 (expect-strings 4728 ("^nobody" (display "Got a nobody user.\n") 4729 (display "That's no problem.\n")) 4730 ("^daemon" (display "Got a daemon user.\n"))))) 4731 4732 The regular expression is compiled with the ‘REG_NEWLINE’ flag, so 4733 that the ^ and $ anchors will match at any newline, not just at the 4734 start and end of the string. 4735 4736 There are two other ways to write a clause: 4737 4738 The expression(s) to evaluate can be omitted, in which case the 4739 result of the regular expression match (converted to strings, as 4740 obtained from regexec with match-pick set to "") will be returned 4741 if the pattern matches. 4742 4743 The symbol ‘=>’ can be used to indicate that the expression is a 4744 procedure which will accept the result of a successful regular 4745 expression match. E.g., 4746 4747 ("^daemon" => write) 4748 ("^d(aemon)" => (lambda args (for-each write args))) 4749 ("^da(em)on" => (lambda (all sub) 4750 (write all) (newline) 4751 (write sub) (newline))) 4752 4753 The order of the substrings corresponds to the order in which the 4754 opening brackets occur. 4755 4756 A number of variables can be used to control the behaviour of 4757 ‘expect’ (and ‘expect-strings’). Most have default top-level 4758 bindings to the value ‘#f’, which produces the default behaviour. 4759 They can be redefined at the top level or locally bound in a form 4760 enclosing the expect expression. 4761 4762 ‘expect-port’ 4763 A port to read characters from, instead of the current input 4764 port. 4765 ‘expect-timeout’ 4766 ‘expect’ will terminate after this number of seconds, 4767 returning ‘#f’ or the value returned by expect-timeout-proc. 4768 ‘expect-timeout-proc’ 4769 A procedure called if timeout occurs. The procedure takes a 4770 single argument: the accumulated string. 4771 ‘expect-eof-proc’ 4772 A procedure called if end-of-file is detected on the input 4773 port. The procedure takes a single argument: the accumulated 4774 string. 4775 ‘expect-char-proc’ 4776 A procedure to be called every time a character is read from 4777 the port. The procedure takes a single argument: the 4778 character which was read. 4779 ‘expect-strings-compile-flags’ 4780 Flags to be used when compiling a regular expression, which 4781 are passed to ‘make-regexp’ *Note Regexp Functions::. The 4782 default value is ‘regexp/newline’. 4783 ‘expect-strings-exec-flags’ 4784 Flags to be used when executing a regular expression, which 4785 are passed to regexp-exec *Note Regexp Functions::. The 4786 default value is ‘regexp/noteol’, which prevents ‘$’ from 4787 matching the end of the string while it is still accumulating, 4788 but still allows it to match after a line break or at the end 4789 of file. 4790 4791 Here’s an example using all of the variables: 4792 4793 (let ((expect-port (open-input-file "/etc/passwd")) 4794 (expect-timeout 1) 4795 (expect-timeout-proc 4796 (lambda (s) (display "Times up!\n"))) 4797 (expect-eof-proc 4798 (lambda (s) (display "Reached the end of the file!\n"))) 4799 (expect-char-proc display) 4800 (expect-strings-compile-flags (logior regexp/newline regexp/icase)) 4801 (expect-strings-exec-flags 0)) 4802 (expect-strings 4803 ("^nobody" (display "Got a nobody user\n")))) 4804 4805 -- Macro: expect clause ... 4806 ‘expect’ is used in the same way as ‘expect-strings’, but tests are 4807 specified not as patterns, but as procedures. The procedures are 4808 called in turn after each character is read from the port, with two 4809 arguments: the value of the accumulated string and a flag to 4810 indicate whether end-of-file has been reached. The flag will 4811 usually be ‘#f’, but if end-of-file is reached, the procedures are 4812 called an additional time with the final accumulated string and 4813 ‘#t’. 4814 4815 The test is successful if the procedure returns a non-false value. 4816 4817 If the ‘=>’ syntax is used, then if the test succeeds it must 4818 return a list containing the arguments to be provided to the 4819 corresponding expression. 4820 4821 In the following example, a string will only be matched at the 4822 beginning of the file: 4823 4824 (let ((expect-port (open-input-file "/etc/passwd"))) 4825 (expect 4826 ((lambda (s eof?) (string=? s "fnord!")) 4827 (display "Got a nobody user!\n")))) 4828 4829 The control variables described for ‘expect-strings’ also influence 4830 the behaviour of ‘expect’, with the exception of variables whose 4831 names begin with ‘expect-strings-’. 4832 4833 4834File: guile.info, Node: sxml-match, Next: The Scheme shell (scsh), Prev: Expect, Up: Guile Modules 4835 48367.17 ‘sxml-match’: Pattern Matching of SXML 4837=========================================== 4838 4839The ‘(sxml match)’ module provides syntactic forms for pattern matching 4840of SXML trees, in a “by example” style reminiscent of the pattern 4841matching of the ‘syntax-rules’ and ‘syntax-case’ macro systems. *Note 4842SXML::, for more information on SXML. 4843 4844 The following example(1) provides a brief illustration, transforming 4845a music album catalog language into HTML. 4846 4847 (define (album->html x) 4848 (sxml-match x 4849 ((album (@ (title ,t)) (catalog (num ,n) (fmt ,f)) ...) 4850 `(ul (li ,t) 4851 (li (b ,n) (i ,f)) ...)))) 4852 4853 Three macros are provided: ‘sxml-match’, ‘sxml-match-let’, and 4854‘sxml-match-let*’. 4855 4856 Compared to a standard s-expression pattern matcher (*note Pattern 4857Matching::), ‘sxml-match’ provides the following benefits: 4858 4859 • matching of SXML elements does not depend on any degree of 4860 normalization of the SXML; 4861 • matching of SXML attributes (within an element) is under-ordered; 4862 the order of the attributes specified within the pattern need not 4863 match the ordering with the element being matched; 4864 • all attributes specified in the pattern must be present in the 4865 element being matched; in the spirit that XML is ’extensible’, the 4866 element being matched may include additional attributes not 4867 specified in the pattern. 4868 4869 The present module is a descendant of WebIt!, and was inspired by an 4870s-expression pattern matcher developed by Erik Hilsdale, Dan Friedman, 4871and Kent Dybvig at Indiana University. 4872 4873Syntax 4874------ 4875 4876‘sxml-match’ provides ‘case’-like form for pattern matching of XML 4877nodes. 4878 4879 -- Scheme Syntax: sxml-match input-expression clause1 clause2 ... 4880 Match INPUT-EXPRESSION, an SXML tree, according to the given 4881 CLAUSEs (one or more), each consisting of a pattern and one or more 4882 expressions to be evaluated if the pattern match succeeds. 4883 Optionally, each CLAUSE within ‘sxml-match’ may include a “guard 4884 expression”. 4885 4886 The pattern notation is based on that of Scheme’s ‘syntax-rules’ and 4887‘syntax-case’ macro systems. The grammar for the ‘sxml-match’ syntax is 4888given below: 4889 4890match-form ::= (sxml-match input-expression 4891 clause+) 4892 4893clause ::= [node-pattern action-expression+] 4894 | [node-pattern (guard expression*) action-expression+] 4895 4896node-pattern ::= literal-pattern 4897 | pat-var-or-cata 4898 | element-pattern 4899 | list-pattern 4900 4901literal-pattern ::= string 4902 | character 4903 | number 4904 | #t 4905 | #f 4906 4907attr-list-pattern ::= (@ attribute-pattern*) 4908 | (@ attribute-pattern* . pat-var-or-cata) 4909 4910attribute-pattern ::= (tag-symbol attr-val-pattern) 4911 4912attr-val-pattern ::= literal-pattern 4913 | pat-var-or-cata 4914 | (pat-var-or-cata default-value-expr) 4915 4916element-pattern ::= (tag-symbol attr-list-pattern?) 4917 | (tag-symbol attr-list-pattern? nodeset-pattern) 4918 | (tag-symbol attr-list-pattern? 4919 nodeset-pattern? . pat-var-or-cata) 4920 4921list-pattern ::= (list nodeset-pattern) 4922 | (list nodeset-pattern? . pat-var-or-cata) 4923 | (list) 4924 4925nodeset-pattern ::= node-pattern 4926 | node-pattern ... 4927 | node-pattern nodeset-pattern 4928 | node-pattern ... nodeset-pattern 4929 4930pat-var-or-cata ::= (unquote var-symbol) 4931 | (unquote [var-symbol*]) 4932 | (unquote [cata-expression -> var-symbol*]) 4933 4934 Within a list or element body pattern, ellipses may appear only once, 4935but may be followed by zero or more node patterns. 4936 4937 Guard expressions cannot refer to the return values of catamorphisms. 4938 4939 Ellipses in the output expressions must appear only in an expression 4940context; ellipses are not allowed in a syntactic form. 4941 4942 The sections below illustrate specific aspects of the ‘sxml-match’ 4943pattern matcher. 4944 4945Matching XML Elements 4946--------------------- 4947 4948The example below illustrates the pattern matching of an XML element: 4949 4950 (sxml-match '(e (@ (i 1)) 3 4 5) 4951 ((e (@ (i ,d)) ,a ,b ,c) (list d a b c)) 4952 (,otherwise #f)) 4953 4954 Each clause in ‘sxml-match’ contains two parts: a pattern and one or 4955more expressions which are evaluated if the pattern is successfully 4956match. The example above matches an element ‘e’ with an attribute ‘i’ 4957and three children. 4958 4959 Pattern variables must be “unquoted” in the pattern. The above 4960expression binds D to ‘1’, A to ‘3’, B to ‘4’, and C to ‘5’. 4961 4962Ellipses in Patterns 4963-------------------- 4964 4965As in ‘syntax-rules’, ellipses may be used to specify a repeated 4966pattern. Note that the pattern ‘item ...’ specifies zero-or-more 4967matches of the pattern ‘item’. 4968 4969 The use of ellipses in a pattern is illustrated in the code fragment 4970below, where nested ellipses are used to match the children of repeated 4971instances of an ‘a’ element, within an element ‘d’. 4972 4973 (define x '(d (a 1 2 3) (a 4 5) (a 6 7 8) (a 9 10))) 4974 4975 (sxml-match x 4976 ((d (a ,b ...) ...) 4977 (list (list b ...) ...))) 4978 4979 The above expression returns a value of ‘((1 2 3) (4 5) (6 7 8) (9 498010))’. 4981 4982Ellipses in Quasiquote’d Output 4983------------------------------- 4984 4985Within the body of an ‘sxml-match’ form, a slightly extended version of 4986quasiquote is provided, which allows the use of ellipses. This is 4987illustrated in the example below. 4988 4989 (sxml-match '(e 3 4 5 6 7) 4990 ((e ,i ... 6 7) `("start" ,(list 'wrap i) ... "end")) 4991 (,otherwise #f)) 4992 4993 The general pattern is that ‘`(something ,i ...)’ is rewritten as 4994‘`(something ,@i)’. 4995 4996Matching Nodesets 4997----------------- 4998 4999A nodeset pattern is designated by a list in the pattern, beginning the 5000identifier list. The example below illustrates matching a nodeset. 5001 5002 (sxml-match '("i" "j" "k" "l" "m") 5003 ((list ,a ,b ,c ,d ,e) 5004 `((p ,a) (p ,b) (p ,c) (p ,d) (p ,e)))) 5005 5006 This example wraps each nodeset item in an HTML paragraph element. 5007This example can be rewritten and simplified through using ellipsis: 5008 5009 (sxml-match '("i" "j" "k" "l" "m") 5010 ((list ,i ...) 5011 `((p ,i) ...))) 5012 5013 This version will match nodesets of any length, and wrap each item in 5014the nodeset in an HTML paragraph element. 5015 5016Matching the “Rest” of a Nodeset 5017-------------------------------- 5018 5019Matching the “rest” of a nodeset is achieved by using a ‘. rest)’ 5020pattern at the end of an element or nodeset pattern. 5021 5022 This is illustrated in the example below: 5023 5024 (sxml-match '(e 3 (f 4 5 6) 7) 5025 ((e ,a (f . ,y) ,d) 5026 (list a y d))) 5027 5028 The above expression returns ‘(3 (4 5 6) 7)’. 5029 5030Matching the Unmatched Attributes 5031--------------------------------- 5032 5033Sometimes it is useful to bind a list of attributes present in the 5034element being matched, but which do not appear in the pattern. This is 5035achieved by using a ‘. rest)’ pattern at the end of the attribute list 5036pattern. This is illustrated in the example below: 5037 5038 (sxml-match '(a (@ (z 1) (y 2) (x 3)) 4 5 6) 5039 ((a (@ (y ,www) . ,qqq) ,t ,u ,v) 5040 (list www qqq t u v))) 5041 5042 The above expression matches the attribute ‘y’ and binds a list of 5043the remaining attributes to the variable QQQ. The result of the above 5044expression is ‘(2 ((z 1) (x 3)) 4 5 6)’. 5045 5046 This type of pattern also allows the binding of all attributes: 5047 5048 (sxml-match '(a (@ (z 1) (y 2) (x 3))) 5049 ((a (@ . ,qqq)) 5050 qqq)) 5051 5052Default Values in Attribute Patterns 5053------------------------------------ 5054 5055It is possible to specify a default value for an attribute which is used 5056if the attribute is not present in the element being matched. This is 5057illustrated in the following example: 5058 5059 (sxml-match '(e 3 4 5) 5060 ((e (@ (z (,d 1))) ,a ,b ,c) (list d a b c))) 5061 5062 The value ‘1’ is used when the attribute ‘z’ is absent from the 5063element ‘e’. 5064 5065Guards in Patterns 5066------------------ 5067 5068Guards may be added to a pattern clause via the ‘guard’ keyword. A 5069guard expression may include zero or more expressions which are 5070evaluated only if the pattern is matched. The body of the clause is 5071only evaluated if the guard expressions evaluate to ‘#t’. 5072 5073 The use of guard expressions is illustrated below: 5074 5075 (sxml-match '(a 2 3) 5076 ((a ,n) (guard (number? n)) n) 5077 ((a ,m ,n) (guard (number? m) (number? n)) (+ m n))) 5078 5079Catamorphisms 5080------------- 5081 5082The example below illustrates the use of explicit recursion within an 5083‘sxml-match’ form. This example implements a simple calculator for the 5084basic arithmetic operations, which are represented by the XML elements 5085‘plus’, ‘minus’, ‘times’, and ‘div’. 5086 5087 (define simple-eval 5088 (lambda (x) 5089 (sxml-match x 5090 (,i (guard (integer? i)) i) 5091 ((plus ,x ,y) (+ (simple-eval x) (simple-eval y))) 5092 ((times ,x ,y) (* (simple-eval x) (simple-eval y))) 5093 ((minus ,x ,y) (- (simple-eval x) (simple-eval y))) 5094 ((div ,x ,y) (/ (simple-eval x) (simple-eval y))) 5095 (,otherwise (error "simple-eval: invalid expression" x))))) 5096 5097 Using the catamorphism feature of ‘sxml-match’, a more concise 5098version of ‘simple-eval’ can be written. The pattern ‘,(x)’ recursively 5099invokes the pattern matcher on the value bound in this position. 5100 5101 (define simple-eval 5102 (lambda (x) 5103 (sxml-match x 5104 (,i (guard (integer? i)) i) 5105 ((plus ,(x) ,(y)) (+ x y)) 5106 ((times ,(x) ,(y)) (* x y)) 5107 ((minus ,(x) ,(y)) (- x y)) 5108 ((div ,(x) ,(y)) (/ x y)) 5109 (,otherwise (error "simple-eval: invalid expression" x))))) 5110 5111Named-Catamorphisms 5112------------------- 5113 5114It is also possible to explicitly name the operator in the “cata” 5115position. Where ‘,(id*)’ recurs to the top of the current ‘sxml-match’, 5116‘,(cata -> id*)’ recurs to ‘cata’. ‘cata’ must evaluate to a procedure 5117which takes one argument, and returns as many values as there are 5118identifiers following ‘->’. 5119 5120 Named catamorphism patterns allow processing to be split into 5121multiple, mutually recursive procedures. This is illustrated in the 5122example below: a transformation that formats a “TV Guide” into HTML. 5123 5124 (define (tv-guide->html g) 5125 (define (cast-list cl) 5126 (sxml-match cl 5127 ((CastList (CastMember (Character (Name ,ch)) (Actor (Name ,a))) ...) 5128 `(div (ul (li ,ch ": " ,a) ...))))) 5129 (define (prog p) 5130 (sxml-match p 5131 ((Program (Start ,start-time) (Duration ,dur) (Series ,series-title) 5132 (Description ,desc ...)) 5133 `(div (p ,start-time 5134 (br) ,series-title 5135 (br) ,desc ...))) 5136 ((Program (Start ,start-time) (Duration ,dur) (Series ,series-title) 5137 (Description ,desc ...) 5138 ,(cast-list -> cl)) 5139 `(div (p ,start-time 5140 (br) ,series-title 5141 (br) ,desc ...) 5142 ,cl)))) 5143 (sxml-match g 5144 ((TVGuide (@ (start ,start-date) 5145 (end ,end-date)) 5146 (Channel (Name ,nm) ,(prog -> p) ...) ...) 5147 `(html (head (title "TV Guide")) 5148 (body (h1 "TV Guide") 5149 (div (h2 ,nm) ,p ...) ...))))) 5150 5151‘sxml-match-let’ and ‘sxml-match-let*’ 5152-------------------------------------- 5153 5154 -- Scheme Syntax: sxml-match-let ((pat expr) ...) expression0 5155 expression ... 5156 -- Scheme Syntax: sxml-match-let* ((pat expr) ...) expression0 5157 expression ... 5158 These forms generalize the ‘let’ and ‘let*’ forms of Scheme to 5159 allow an XML pattern in the binding position, rather than a simple 5160 variable. 5161 5162 For example, the expression below: 5163 5164 (sxml-match-let (((a ,i ,j) '(a 1 2))) 5165 (+ i j)) 5166 5167 binds the variables I and J to ‘1’ and ‘2’ in the XML value given. 5168 5169 ---------- Footnotes ---------- 5170 5171 (1) This example is taken from a paper by Krishnamurthi et al. Their 5172paper was the first to show the usefulness of the ‘syntax-rules’ style 5173of pattern matching for transformation of XML, though the language 5174described, XT3D, is an XML language. 5175 5176 5177File: guile.info, Node: The Scheme shell (scsh), Next: Curried Definitions, Prev: sxml-match, Up: Guile Modules 5178 51797.18 The Scheme shell (scsh) 5180============================ 5181 5182An incomplete port of the Scheme shell (scsh) was once available for 5183Guile as a separate package. However this code has bitrotten somewhat. 5184The pieces are available in Guile’s legacy CVS repository, which may be 5185browsed at 5186<http://cvs.savannah.gnu.org/viewvc/guile/guile-scsh/?root=guile>. 5187 5188 For information about scsh see <http://www.scsh.net/>. 5189 5190 This bitrotting is a bit of a shame, as there is a good deal of 5191well-written Scheme code in scsh. Adopting this code and porting it to 5192current Guile should be an educational experience, in addition to 5193providing something of value to Guile folks. 5194 5195 5196File: guile.info, Node: Curried Definitions, Next: Statprof, Prev: The Scheme shell (scsh), Up: Guile Modules 5197 51987.19 Curried Definitions 5199======================== 5200 5201The macros in this section are provided by 5202 (use-modules (ice-9 curried-definitions)) 5203and replace those provided by default. 5204 5205 Prior to Guile 2.0, Guile provided a type of definition known 5206colloquially as a “curried definition”. The idea is to extend the 5207syntax of ‘define’ so that you can conveniently define procedures that 5208return procedures, up to any desired depth. 5209 5210 For example, 5211 (define ((foo x) y) 5212 (list x y)) 5213 is a convenience form of 5214 (define foo 5215 (lambda (x) 5216 (lambda (y) 5217 (list x y)))) 5218 5219 -- Scheme Syntax: define (... (name args ...) ...) body ... 5220 -- Scheme Syntax: define* (... (name args ...) ...) body ... 5221 -- Scheme Syntax: define-public (... (name args ...) ...) body ... 5222 5223 Create a top level variable NAME bound to the procedure with 5224 parameter list ARGS. If NAME is itself a formal parameter list, 5225 then a higher order procedure is created using that 5226 formal-parameter list, and returning a procedure that has parameter 5227 list ARGS. This nesting may occur to arbitrary depth. 5228 5229 ‘define*’ is similar but the formal parameter lists take additional 5230 options as described in *note lambda* and define*::. For example, 5231 (define* ((foo #:keys (bar 'baz) (quux 'zot)) frotz #:rest rest) 5232 (list bar quux frotz rest)) 5233 5234 ((foo #:quux 'foo) 1 2 3 4 5) 5235 ⇒ (baz foo 1 (2 3 4 5)) 5236 5237 ‘define-public’ is similar to ‘define’ but it also adds NAME to the 5238 list of exported bindings of the current module. 5239 5240 5241File: guile.info, Node: Statprof, Next: SXML, Prev: Curried Definitions, Up: Guile Modules 5242 52437.20 Statprof 5244============= 5245 5246Statprof is a statistical profiler for Guile. 5247 5248 A simple use of statprof would look like this: 5249 5250 (use-modules (statprof)) 5251 (statprof (lambda () 5252 (map 1+ (iota 1000000)) 5253 #f)) 5254 5255 This would run the thunk with statistical profiling, finally 5256displaying a flat table of statistics which could look something like 5257this: 5258 5259 % cumulative self 5260 time seconds seconds procedure 5261 57.14 39769.73 0.07 ice-9/boot-9.scm:249:5:map1 5262 28.57 0.04 0.04 ice-9/boot-9.scm:1165:0:iota 5263 14.29 0.02 0.02 1+ 5264 0.00 0.12 0.00 <current input>:2:10 5265 --- 5266 Sample count: 7 5267 Total time: 0.123490713 seconds (0.201983993 seconds in GC) 5268 5269 All of the numerical data with the exception of the calls column is 5270statistically approximate. In the following column descriptions, and in 5271all of statprof, “time” refers to execution time (both user and system), 5272not wall clock time. 5273 5274 The ‘% time’ column indicates the percentage of the run-time time 5275spent inside the procedure itself (not counting children). It is 5276calculated as ‘self seconds’, measuring the amount of time spent in the 5277procedure, divided by the total run-time. 5278 5279 ‘cumulative seconds’ also counts time spent in children of a 5280function. For recursive functions, this can exceed the total time, as 5281in our example above, because each activation on the stack adds to the 5282cumulative time. 5283 5284 Finally, the GC time measures the time spent in the garbage 5285collector. On systems with multiple cores, this time can be larger than 5286the run time, because it counts time spent in all threads, and will run 5287the “marking” phase of GC in parallel. If GC time is a significant 5288fraction of the run time, that means that most time in your program is 5289spent allocating objects and cleaning up after those allocations. To 5290speed up your program, one good place to start would be to look at how 5291to reduce the allocation rate. 5292 5293 Statprof’s main mode of operation is as a statistical profiler. 5294However statprof can also run in a “precise” mode as well. Pass the 5295‘#:count-calls? #t’ keyword argument to ‘statprof’ to record all calls: 5296 5297 (use-modules (statprof)) 5298 (statprof (lambda () 5299 (map 1+ (iota 1000000)) 5300 #f) 5301 #:count-calls? #t) 5302 5303 The result has an additional ‘calls’ column: 5304 5305 % cumulative self 5306 time seconds seconds calls procedure 5307 82.26 0.73 0.73 1000000 1+ 5308 11.29 420925.80 0.10 1000001 ice-9/boot-9.scm:249:5:map1 5309 4.84 0.06 0.04 1 ice-9/boot-9.scm:1165:0:iota 5310 [...] 5311 --- 5312 Sample count: 62 5313 Total time: 0.893098065 seconds (1.222796536 seconds in GC) 5314 5315 As you can see, the profile is perturbed: ‘1+’ ends up on top, 5316whereas it was not marked as hot in the earlier profile. This is 5317because the overhead of call-counting unfairly penalizes calls. Still, 5318this precise mode can be useful at times to do algorithmic optimizations 5319based on the precise call counts. 5320 5321Implementation notes 5322==================== 5323 5324The profiler works by setting the unix profiling signal ‘ITIMER_PROF’ to 5325go off after the interval you define in the call to ‘statprof-reset’. 5326When the signal fires, a sampling routine runs which crawls up the 5327stack, recording all instruction pointers into a buffer. After the 5328sample is complete, the profiler resets profiling timer to fire again 5329after the appropriate interval. 5330 5331 Later, when profiling stops, that log buffer is analyzed to produce 5332the “self seconds” and “cumulative seconds” statistics. A procedure at 5333the top of the stack counts toward “self” samples, and everything on the 5334stack counts towards “cumulative” samples. 5335 5336 While the profiler is running it measures how much CPU time (system 5337and user – which is also what ‘ITIMER_PROF’ tracks) has elapsed while 5338code has been executing within the profiler. Only run time counts 5339towards the profile, not wall-clock time. For example, sleeping and 5340waiting for input or output do not cause the timer clock to advance. 5341 5342Usage 5343===== 5344 5345 -- Scheme Procedure: statprof thunk [#:loop loop=1] [#:hz hz=100] 5346 [#:port port=(current-output-port)] [#:count-calls? 5347 count-calls?=#f] [#:display-style display-style='flat] 5348 Profile the execution of THUNK, and return its return values. 5349 5350 The stack will be sampled HZ times per second, and the thunk itself 5351 will be called LOOP times. 5352 5353 If COUNT-CALLS? is true, all procedure calls will be recorded. 5354 This operation is somewhat expensive. 5355 5356 After the THUNK has been profiled, print out a profile to PORT. If 5357 DISPLAY-STYLE is ‘flat’, the results will be printed as a flat 5358 profile. Otherwise if DISPLAY-STYLE is ‘tree’, print the results 5359 as a tree profile. 5360 5361 Note that ‘statprof’ requires a working profiling timer. Some 5362 platforms do not support profiling timers. ‘(provided? 5363 'ITIMER_PROF)’ can be used to check for support of profiling 5364 timers. 5365 5366 Profiling can also be enabled and disabled manually. 5367 5368 -- Scheme Procedure: statprof-active? 5369 Returns ‘#t’ if ‘statprof-start’ has been called more times than 5370 ‘statprof-stop’, ‘#f’ otherwise. 5371 5372 -- Scheme Procedure: statprof-start 5373 -- Scheme Procedure: statprof-stop 5374 Start or stop the profiler. 5375 5376 -- Scheme Procedure: statprof-reset sample-seconds sample-microseconds 5377 count-calls? 5378 Reset the profiling sample interval to SAMPLE-SECONDS and 5379 SAMPLE-MICROSECONDS. If COUNT-CALLS? is true, arrange to 5380 instrument procedure calls as well as collecting statistical 5381 profiling data. 5382 5383 If you use the manual ‘statprof-start’/‘statprof-stop’ interface, an 5384implicit statprof state will persist starting from the last call to 5385‘statprof-reset’, or the first call to ‘statprof-start’. There are a 5386number of accessors to fetch statistics from this implicit state. 5387 5388 -- Scheme Procedure: statprof-accumulated-time 5389 Returns the time accumulated during the last statprof run. 5390 5391 -- Scheme Procedure: statprof-sample-count 5392 Returns the number of samples taken during the last statprof run. 5393 5394 -- Scheme Procedure: statprof-fold-call-data proc init 5395 Fold PROC over the call-data accumulated by statprof. This 5396 procedure cannot be called while statprof is active. 5397 5398 PROC will be called with arguments, CALL-DATA and PRIOR-RESULT. 5399 5400 -- Scheme Procedure: statprof-proc-call-data proc 5401 Returns the call-data associated with PROC, or ‘#f’ if none is 5402 available. 5403 5404 -- Scheme Procedure: statprof-call-data-name cd 5405 -- Scheme Procedure: statprof-call-data-calls cd 5406 -- Scheme Procedure: statprof-call-data-cum-samples cd 5407 -- Scheme Procedure: statprof-call-data-self-samples cd 5408 Accessors for the fields in a statprof call-data object. 5409 5410 -- Scheme Procedure: statprof-call-data->stats call-data 5411 Returns an object of type ‘statprof-stats’. 5412 5413 -- Scheme Procedure: statprof-stats-proc-name stats 5414 -- Scheme Procedure: statprof-stats-%-time-in-proc stats 5415 -- Scheme Procedure: statprof-stats-cum-secs-in-proc stats 5416 -- Scheme Procedure: statprof-stats-self-secs-in-proc stats 5417 -- Scheme Procedure: statprof-stats-calls stats 5418 -- Scheme Procedure: statprof-stats-self-secs-per-call stats 5419 -- Scheme Procedure: statprof-stats-cum-secs-per-call stats 5420 Accessors for the fields in a ‘statprof-stats’ object. 5421 5422 -- Scheme Procedure: statprof-display [port=(current-output-port)] 5423 [#:style style=flat] 5424 Displays a summary of the statistics collected. Possible values 5425 for STYLE include: 5426 5427 ‘flat’ 5428 Display a traditional gprof-style flat profile. 5429 ‘anomalies’ 5430 Find statistical anomalies in the data. 5431 ‘tree’ 5432 Display a tree profile. 5433 5434 -- Scheme Procedure: statprof-fetch-stacks 5435 Returns a list of stacks, as they were captured since the last call 5436 to ‘statprof-reset’. 5437 5438 -- Scheme Procedure: statprof-fetch-call-tree [#:precise precise?=#f] 5439 Return a call tree for the previous statprof run. 5440 5441 The return value is a list of nodes. A node is a list of the form: 5442 @code 5443 node ::= (@var{proc} @var{count} . @var{nodes}) 5444 @end code 5445 5446 The @var{proc} is a printable representation of a procedure, as a 5447 string. If @var{precise?} is false, which is the default, then a node 5448 corresponds to a procedure invocation. If it is true, then a node 5449 corresponds to a return point in a procedure. Passing @code{#:precise? 5450 #t} allows a user to distinguish different source lines in a procedure, 5451 but usually it is too much detail, so it is off by default. 5452 5453 -- Scheme Procedure: gcprof thunk [#:loop] 5454 Like the ‘statprof’ procedure, but instead of profiling CPU time, 5455 we profile garbage collection. 5456 5457 The stack will be sampled soon after every garbage collection 5458 during the evaluation of THUNK, yielding an approximate idea of 5459 what is causing allocation in your program. 5460 5461 Since GC does not occur very frequently, you may need to use the 5462 LOOP parameter, to cause THUNK to be called LOOP times. 5463 5464 5465File: guile.info, Node: SXML, Next: Texinfo Processing, Prev: Statprof, Up: Guile Modules 5466 54677.21 SXML 5468========= 5469 5470SXML is a native representation of XML in terms of standard Scheme data 5471types: lists, symbols, and strings. For example, the simple XML 5472fragment: 5473 5474 <parrot type="African Grey"><name>Alfie</name></parrot> 5475 5476 may be represented with the following SXML: 5477 5478 (parrot (@ (type "African Grey")) (name "Alfie")) 5479 5480 SXML is very general, and is capable of representing all of XML. 5481Formally, this means that SXML is a conforming implementation of the 5482http://www.w3.org/TR/xml-infoset/ (XML Information Set) standard. 5483 5484 Guile includes several facilities for working with XML and SXML: 5485parsers, serializers, and transformers. 5486 5487* Menu: 5488 5489* SXML Overview:: XML, as it was meant to be 5490* Reading and Writing XML:: Convenient XML parsing and serializing 5491* SSAX:: Custom functional-style XML parsers 5492* Transforming SXML:: Munging SXML with ‘pre-post-order’ 5493* SXML Tree Fold:: Fold-based SXML transformations 5494* SXPath:: XPath for SXML 5495* sxml ssax input-parse:: The SSAX tokenizer, optimized for Guile 5496* sxml apply-templates:: A more XSLT-like approach to SXML transformations 5497 5498 5499File: guile.info, Node: SXML Overview, Next: Reading and Writing XML, Up: SXML 5500 55017.21.1 SXML Overview 5502-------------------- 5503 5504(This section needs to be written; volunteers welcome.) 5505 5506 5507File: guile.info, Node: Reading and Writing XML, Next: SSAX, Prev: SXML Overview, Up: SXML 5508 55097.21.2 Reading and Writing XML 5510------------------------------ 5511 5512The ‘(sxml simple)’ module presents a basic interface for parsing XML 5513from a port into the Scheme SXML format, and for serializing it back to 5514text. 5515 5516 (use-modules (sxml simple)) 5517 5518 -- Scheme Procedure: xml->sxml [string-or-port] [#:namespaces='()] 5519 [#:declare-namespaces?=#t] [#:trim-whitespace?=#f] 5520 [#:entities='()] [#:default-entity-handler=#f] 5521 [#:doctype-handler=#f] 5522 Use SSAX to parse an XML document into SXML. Takes one optional 5523 argument, STRING-OR-PORT, which defaults to the current input port. 5524 Returns the resulting SXML document. If STRING-OR-PORT is a port, 5525 it will be left pointing at the next available character in the 5526 port. 5527 5528 As is normal in SXML, XML elements parse as tagged lists. 5529Attributes, if any, are placed after the tag, within an ‘@’ element. 5530The root of the resulting XML will be contained in a special tag, 5531‘*TOP*’. This tag will contain the root element of the XML, but also 5532any prior processing instructions. 5533 5534 (xml->sxml "<foo/>") 5535 ⇒ (*TOP* (foo)) 5536 (xml->sxml "<foo>text</foo>") 5537 ⇒ (*TOP* (foo "text")) 5538 (xml->sxml "<foo kind=\"bar\">text</foo>") 5539 ⇒ (*TOP* (foo (@ (kind "bar")) "text")) 5540 (xml->sxml "<?xml version=\"1.0\"?><foo/>") 5541 ⇒ (*TOP* (*PI* xml "version=\"1.0\"") (foo)) 5542 5543 All namespaces in the XML document must be declared, via ‘xmlns’ 5544attributes. SXML elements built from non-default namespaces will have 5545their tags prefixed with their URI. Users can specify custom prefixes 5546for certain namespaces with the ‘#:namespaces’ keyword argument to 5547‘xml->sxml’. 5548 5549 (xml->sxml "<foo xmlns=\"http://example.org/ns1\">text</foo>") 5550 ⇒ (*TOP* (http://example.org/ns1:foo "text")) 5551 (xml->sxml "<foo xmlns=\"http://example.org/ns1\">text</foo>" 5552 #:namespaces '((ns1 . "http://example.org/ns1"))) 5553 ⇒ (*TOP* (ns1:foo "text")) 5554 (xml->sxml "<foo xmlns:bar=\"http://example.org/ns2\"><bar:baz/></foo>" 5555 #:namespaces '((ns2 . "http://example.org/ns2"))) 5556 ⇒ (*TOP* (foo (ns2:baz))) 5557 5558 By default, namespaces passed to ‘xml->sxml’ are treated as if they 5559were declared on the root element. Passing a false 5560‘#:declare-namespaces?’ argument will disable this behavior, requiring 5561in-document declarations of namespaces before use.. 5562 5563 (xml->sxml "<foo><ns2:baz/></foo>" 5564 #:namespaces '((ns2 . "http://example.org/ns2"))) 5565 ⇒ (*TOP* (foo (ns2:baz))) 5566 (xml->sxml "<foo><ns2:baz/></foo>" 5567 #:namespaces '((ns2 . "http://example.org/ns2")) 5568 #:declare-namespaces? #f) 5569 ⇒ error: undeclared namespace: `bar' 5570 5571 By default, all whitespace in XML is significant. Passing the 5572‘#:trim-whitespace?’ keyword argument to ‘xml->sxml’ will trim 5573whitespace in front, behind and between elements, treating it as 5574“unsignificant”. Whitespace in text fragments is left alone. 5575 5576 (xml->sxml "<foo>\n<bar> Alfie the parrot! </bar>\n</foo>") 5577 ⇒ (*TOP* (foo "\n" (bar " Alfie the parrot! ") "\n")) 5578 (xml->sxml "<foo>\n<bar> Alfie the parrot! </bar>\n</foo>" 5579 #:trim-whitespace? #t) 5580 ⇒ (*TOP* (foo (bar " Alfie the parrot! "))) 5581 5582 Parsed entities may be declared with the ‘#:entities’ keyword 5583argument, or handled with the ‘#:default-entity-handler’. By default, 5584only the standard ‘<’, ‘>’, ‘&’, ‘'’ and ‘"’ 5585entities are defined, as well as the ‘&#N;’ and ‘&#xN;’ (decimal and 5586hexadecimal) numeric character entities. 5587 5588 (xml->sxml "<foo>&</foo>") 5589 ⇒ (*TOP* (foo "&")) 5590 (xml->sxml "<foo> </foo>") 5591 ⇒ error: undefined entity: nbsp 5592 (xml->sxml "<foo> </foo>") 5593 ⇒ (*TOP* (foo "\xa0")) 5594 (xml->sxml "<foo> </foo>" 5595 #:entities '((nbsp . "\xa0"))) 5596 ⇒ (*TOP* (foo "\xa0")) 5597 (xml->sxml "<foo> &foo;</foo>" 5598 #:default-entity-handler 5599 (lambda (port name) 5600 (case name 5601 ((nbsp) "\xa0") 5602 (else 5603 (format (current-warning-port) 5604 "~a:~a:~a: undefined entitity: ~a\n" 5605 (or (port-filename port) "<unknown file>") 5606 (port-line port) (port-column port) 5607 name) 5608 (symbol->string name))))) 5609 ⊣ <unknown file>:0:17: undefined entitity: foo 5610 ⇒ (*TOP* (foo "\xa0 foo")) 5611 5612 By default, ‘xml->sxml’ skips over the ‘<!DOCTYPE>’ declaration, if 5613any. This behavior can be overridden with the ‘#:doctype-handler’ 5614argument, which should be a procedure of three arguments: the “docname” 5615(a symbol), “systemid” (a string), and the internal doctype subset (as a 5616string or ‘#f’ if not present). 5617 5618 The handler should return keyword arguments as multiple values, as if 5619it were calling its continuation with keyword arguments. The 5620continuation accepts the ‘#:entities’ and ‘#:namespaces’ keyword 5621arguments, in the same format that ‘xml->sxml’ itself takes. These 5622entities and namespaces will be prepended to those given to the 5623‘xml->sxml’ invocation. 5624 5625 (define (handle-foo docname systemid internal-subset) 5626 (case docname 5627 ((foo) 5628 (values #:entities '((greets . "<i>Hello, world!</i>")))) 5629 (else 5630 (values)))) 5631 5632 (xml->sxml "<!DOCTYPE foo><p>&greets;</p>" 5633 #:doctype-handler handle-foo) 5634 ⇒ (*TOP* (p (i "Hello, world!"))) 5635 5636 If the document has no doctype declaration, the DOCTYPE-HANDLER is 5637invoked with ‘#f’ for the three arguments. 5638 5639 In the future, the continuation may accept other keyword arguments, 5640for example to validate the parsed SXML against the doctype. 5641 5642 -- Scheme Procedure: sxml->xml tree [port] 5643 Serialize the SXML tree TREE as XML. The output will be written to 5644 the current output port, unless the optional argument PORT is 5645 present. 5646 5647 -- Scheme Procedure: sxml->string sxml 5648 Detag an sxml tree SXML into a string. Does not perform any 5649 formatting. 5650 5651 5652File: guile.info, Node: SSAX, Next: Transforming SXML, Prev: Reading and Writing XML, Up: SXML 5653 56547.21.3 SSAX: A Functional XML Parsing Toolkit 5655--------------------------------------------- 5656 5657Guile’s XML parser is based on Oleg Kiselyov’s powerful XML parsing 5658toolkit, SSAX. 5659 56607.21.3.1 History 5661................ 5662 5663Back in the 1990s, when the world was young again and XML was the 5664solution to all of its problems, there were basically two kinds of XML 5665parsers out there: DOM parsers and SAX parsers. 5666 5667 A DOM parser reads through an entire XML document, building up a tree 5668of “DOM objects” representing the document structure. They are very 5669easy to use, but sometimes you don’t actually want all of the 5670information in a document; building an object tree is not necessary if 5671all you want to do is to count word frequencies in a document, for 5672example. 5673 5674 SAX parsers were created to give the programmer more control on the 5675parsing process. A programmer gives the SAX parser a number of 5676“callbacks”: functions that will be called on various features of the 5677XML stream as they are encountered. SAX parsers are more efficient, but 5678much harder to use, as users typically have to manually maintain a stack 5679of open elements. 5680 5681 Kiselyov realized that the SAX programming model could be made much 5682simpler if the callbacks were formulated not as a linear fold across the 5683features of the XML stream, but as a _tree fold_ over the structure 5684implicit in the XML. In this way, the user has a very convenient, 5685functional-style interface that can still generate optimal parsers. 5686 5687 The ‘xml->sxml’ interface from the ‘(sxml simple)’ module is a 5688DOM-style parser built using SSAX, though it returns SXML instead of DOM 5689objects. 5690 56917.21.3.2 Implementation 5692....................... 5693 5694‘(sxml ssax)’ is a package of low-to-high level lexing and parsing 5695procedures that can be combined to yield a SAX, a DOM, a validating 5696parser, or a parser intended for a particular document type. The 5697procedures in the package can be used separately to tokenize or parse 5698various pieces of XML documents. The package supports XML Namespaces, 5699internal and external parsed entities, user-controlled handling of 5700whitespace, and validation. This module therefore is intended to be a 5701framework, a set of “Lego blocks” you can use to build a parser 5702following any discipline and performing validation to any degree. As an 5703example of the parser construction, the source file includes a 5704semi-validating SXML parser. 5705 5706 SSAX has a “sequential” feel of SAX yet a “functional style” of DOM. 5707Like a SAX parser, the framework scans the document only once and 5708permits incremental processing. An application that handles document 5709elements in order can run as efficiently as possible. _Unlike_ a SAX 5710parser, the framework does not require an application register stateful 5711callbacks and surrender control to the parser. Rather, it is the 5712application that can drive the framework – calling its functions to get 5713the current lexical or syntax element. These functions do not maintain 5714or mutate any state save the input port. Therefore, the framework 5715permits parsing of XML in a pure functional style, with the input port 5716being a monad (or a linear, read-once parameter). 5717 5718 Besides the PORT, there is another monad – SEED. Most of the middle- 5719and high-level parsers are single-threaded through the SEED. The 5720functions of this framework do not process or affect the SEED in any 5721way: they simply pass it around as an instance of an opaque datatype. 5722User functions, on the other hand, can use the seed to maintain user’s 5723state, to accumulate parsing results, etc. A user can freely mix their 5724own functions with those of the framework. On the other hand, the user 5725may wish to instantiate a high-level parser: ‘SSAX:make-elem-parser’ or 5726‘SSAX:make-parser’. In the latter case, the user must provide functions 5727of specific signatures, which are called at predictable moments during 5728the parsing: to handle character data, element data, or processing 5729instructions (PI). The functions are always given the SEED, among other 5730parameters, and must return the new SEED. 5731 5732 From a functional point of view, XML parsing is a combined 5733pre-post-order traversal of a “tree” that is the XML document itself. 5734This down-and-up traversal tells the user about an element when its 5735start tag is encountered. The user is notified about the element once 5736more, after all element’s children have been handled. The process of 5737XML parsing therefore is a fold over the raw XML document. Unlike a 5738fold over trees defined in [1], the parser is necessarily 5739single-threaded – obviously as elements in a text XML document are laid 5740down sequentially. The parser therefore is a tree fold that has been 5741transformed to accept an accumulating parameter [1,2]. 5742 5743 Formally, the denotational semantics of the parser can be expressed 5744as 5745 5746 parser:: (Start-tag -> Seed -> Seed) -> 5747 (Start-tag -> Seed -> Seed -> Seed) -> 5748 (Char-Data -> Seed -> Seed) -> 5749 XML-text-fragment -> Seed -> Seed 5750 parser fdown fup fchar "<elem attrs> content </elem>" seed 5751 = fup "<elem attrs>" seed 5752 (parser fdown fup fchar "content" (fdown "<elem attrs>" seed)) 5753 5754 parser fdown fup fchar "char-data content" seed 5755 = parser fdown fup fchar "content" (fchar "char-data" seed) 5756 5757 parser fdown fup fchar "elem-content content" seed 5758 = parser fdown fup fchar "content" ( 5759 parser fdown fup fchar "elem-content" seed) 5760 5761 Compare the last two equations with the left fold 5762 5763 fold-left kons elem:list seed = fold-left kons list (kons elem seed) 5764 5765 The real parser created by ‘SSAX:make-parser’ is slightly more 5766complicated, to account for processing instructions, entity references, 5767namespaces, processing of document type declaration, etc. 5768 5769 The XML standard document referred to in this module is 5770<http://www.w3.org/TR/1998/REC-xml-19980210.html> 5771 5772 The present file also defines a procedure that parses the text of an 5773XML document or of a separate element into SXML, an S-expression-based 5774model of an XML Information Set. SXML is also an Abstract Syntax Tree 5775of an XML document. SXML is similar but not identical to DOM; SXML is 5776particularly suitable for Scheme-based XML/HTML authoring, SXPath 5777queries, and tree transformations. See SXML.html for more details. 5778SXML is a term implementation of evaluation of the XML document [3]. 5779The other implementation is context-passing. 5780 5781 The present frameworks fully supports the XML Namespaces 5782Recommendation: <http://www.w3.org/TR/REC-xml-names/>. 5783 5784 Other links: 5785 5786[1] 5787 Jeremy Gibbons, Geraint Jones, "The Under-appreciated Unfold," 5788 Proc. ICFP’98, 1998, pp. 273-279. 5789 5790[2] 5791 Richard S. Bird, The promotion and accumulation strategies in 5792 transformational programming, ACM Trans. Progr. Lang. Systems, 5793 6(4):487-504, October 1984. 5794 5795[3] 5796 Ralf Hinze, "Deriving Backtracking Monad Transformers," Functional 5797 Pearl. Proc ICFP’00, pp. 186-197. 5798 57997.21.3.3 Usage 5800.............. 5801 5802 -- Scheme Procedure: current-ssax-error-port 5803 5804 -- Scheme Procedure: with-ssax-error-to-port port thunk 5805 5806 -- Scheme Procedure: xml-token? _ 5807 -- Scheme Procedure: pair? x 5808 Return `#t' if X is a pair; otherwise return `#f'. 5809 5810 5811 5812 -- Scheme Syntax: xml-token-kind token 5813 5814 -- Scheme Syntax: xml-token-head token 5815 5816 -- Scheme Procedure: make-empty-attlist 5817 5818 -- Scheme Procedure: attlist-add attlist name-value 5819 5820 -- Scheme Procedure: attlist-null? x 5821 Return ‘#t’ if X is the empty list, else ‘#f’. 5822 5823 -- Scheme Procedure: attlist-remove-top attlist 5824 5825 -- Scheme Procedure: attlist->alist attlist 5826 5827 -- Scheme Procedure: attlist-fold kons knil lis1 5828 5829 -- Scheme Procedure: define-parsed-entity! entity str 5830 Define a new parsed entity. ENTITY should be a symbol. 5831 5832 Instances of &ENTITY; in XML text will be replaced with the string 5833 STR, which will then be parsed. 5834 5835 -- Scheme Procedure: reset-parsed-entity-definitions! 5836 Restore the set of parsed entity definitions to its initial state. 5837 5838 -- Scheme Procedure: ssax:uri-string->symbol uri-str 5839 5840 -- Scheme Procedure: ssax:skip-internal-dtd port 5841 5842 -- Scheme Procedure: ssax:read-pi-body-as-string port 5843 5844 -- Scheme Procedure: ssax:reverse-collect-str-drop-ws fragments 5845 5846 -- Scheme Procedure: ssax:read-markup-token port 5847 5848 -- Scheme Procedure: ssax:read-cdata-body port str-handler seed 5849 5850 -- Scheme Procedure: ssax:read-char-ref port 5851 5852 -- Scheme Procedure: ssax:read-attributes port entities 5853 5854 -- Scheme Procedure: ssax:complete-start-tag tag-head port elems 5855 entities namespaces 5856 5857 -- Scheme Procedure: ssax:read-external-id port 5858 5859 -- Scheme Procedure: ssax:read-char-data port expect-eof? str-handler 5860 seed 5861 5862 -- Scheme Procedure: ssax:xml->sxml port namespace-prefix-assig 5863 5864 -- Scheme Syntax: ssax:make-parser . kw-val-pairs 5865 5866 -- Scheme Syntax: ssax:make-pi-parser orig-handlers 5867 5868 -- Scheme Syntax: ssax:make-elem-parser my-new-level-seed 5869 my-finish-element my-char-data-handler my-pi-handlers 5870 5871 5872File: guile.info, Node: Transforming SXML, Next: SXML Tree Fold, Prev: SSAX, Up: SXML 5873 58747.21.4 Transforming SXML 5875------------------------ 5876 58777.21.4.1 Overview 5878................. 5879 5880SXML expression tree transformers 5881================================= 5882 5883Pre-Post-order traversal of a tree and creation of a new tree 5884------------------------------------------------------------- 5885 5886 pre-post-order:: <tree> x <bindings> -> <new-tree> 5887 5888 where 5889 5890 <bindings> ::= (<binding> ...) 5891 <binding> ::= (<trigger-symbol> *preorder* . <handler>) | 5892 (<trigger-symbol> *macro* . <handler>) | 5893 (<trigger-symbol> <new-bindings> . <handler>) | 5894 (<trigger-symbol> . <handler>) 5895 <trigger-symbol> ::= XMLname | *text* | *default* 5896 <handler> :: <trigger-symbol> x [<tree>] -> <new-tree> 5897 5898 The pre-post-order function visits the nodes and nodelists 5899pre-post-order (depth-first). For each ‘<Node>’ of the form ‘(NAME 5900<Node> ...)’, it looks up an association with the given NAME among its 5901<BINDINGS>. If failed, ‘pre-post-order’ tries to locate a ‘*default*’ 5902binding. It’s an error if the latter attempt fails as well. Having 5903found a binding, the ‘pre-post-order’ function first checks to see if 5904the binding is of the form 5905 5906 (<trigger-symbol> *preorder* . <handler>) 5907 5908 If it is, the handler is ’applied’ to the current node. Otherwise, 5909the pre-post-order function first calls itself recursively for each 5910child of the current node, with <NEW-BINDINGS> prepended to the 5911<BINDINGS> in effect. The result of these calls is passed to the 5912<HANDLER> (along with the head of the current <NODE>). To be more 5913precise, the handler is _applied_ to the head of the current node and 5914its processed children. The result of the handler, which should also be 5915a ‘<tree>’, replaces the current <NODE>. If the current <NODE> is a 5916text string or other atom, a special binding with a symbol ‘*text*’ is 5917looked up. 5918 5919 A binding can also be of a form 5920 5921 (<trigger-symbol> *macro* . <handler>) 5922 5923 This is equivalent to ‘*preorder*’ described above. However, the 5924result is re-processed again, with the current stylesheet. 5925 59267.21.4.2 Usage 5927.............. 5928 5929 -- Scheme Procedure: SRV:send-reply . fragments 5930 Output the FRAGMENTS to the current output port. 5931 5932 The fragments are a list of strings, characters, numbers, thunks, 5933 ‘#f’, ‘#t’ – and other fragments. The function traverses the tree 5934 depth-first, writes out strings and characters, executes thunks, 5935 and ignores ‘#f’ and ‘'()’. The function returns ‘#t’ if anything 5936 was written at all; otherwise the result is ‘#f’ If ‘#t’ occurs 5937 among the fragments, it is not written out but causes the result of 5938 ‘SRV:send-reply’ to be ‘#t’. 5939 5940 -- Scheme Procedure: foldts fdown fup fhere seed tree 5941 5942 -- Scheme Procedure: post-order tree bindings 5943 5944 -- Scheme Procedure: pre-post-order tree bindings 5945 5946 -- Scheme Procedure: replace-range beg-pred end-pred forest 5947 5948 5949File: guile.info, Node: SXML Tree Fold, Next: SXPath, Prev: Transforming SXML, Up: SXML 5950 59517.21.5 SXML Tree Fold 5952--------------------- 5953 59547.21.5.1 Overview 5955................. 5956 5957‘(sxml fold)’ defines a number of variants of the “fold” algorithm for 5958use in transforming SXML trees. Additionally it defines the layout 5959operator, ‘fold-layout’, which might be described as a context-passing 5960variant of SSAX’s ‘pre-post-order’. 5961 59627.21.5.2 Usage 5963.............. 5964 5965 -- Scheme Procedure: foldt fup fhere tree 5966 The standard multithreaded tree fold. 5967 5968 FUP is of type [a] -> a. FHERE is of type object -> a. 5969 5970 -- Scheme Procedure: foldts fdown fup fhere seed tree 5971 The single-threaded tree fold originally defined in SSAX. *Note 5972 SSAX::, for more information. 5973 5974 -- Scheme Procedure: foldts* fdown fup fhere seed tree 5975 A variant of ‘foldts’ that allows pre-order tree rewrites. 5976 Originally defined in Andy Wingo’s 2007 paper, _Applications of 5977 fold to XML transformation_. 5978 5979 -- Scheme Procedure: fold-values proc list . seeds 5980 A variant of ‘fold’ that allows multi-valued seeds. Note that the 5981 order of the arguments differs from that of ‘fold’. *Note SRFI-1 5982 Fold and Map::. 5983 5984 -- Scheme Procedure: foldts*-values fdown fup fhere tree . seeds 5985 A variant of ‘foldts*’ that allows multi-valued seeds. Originally 5986 defined in Andy Wingo’s 2007 paper, _Applications of fold to XML 5987 transformation_. 5988 5989 -- Scheme Procedure: fold-layout tree bindings params layout stylesheet 5990 A traversal combinator in the spirit of ‘pre-post-order’. *Note 5991 Transforming SXML::. 5992 5993 ‘fold-layout’ was originally presented in Andy Wingo’s 2007 paper, 5994 _Applications of fold to XML transformation_. 5995 5996 bindings := (<binding>...) 5997 binding := (<tag> <handler-pair>...) 5998 | (*default* . <post-handler>) 5999 | (*text* . <text-handler>) 6000 tag := <symbol> 6001 handler-pair := (pre-layout . <pre-layout-handler>) 6002 | (post . <post-handler>) 6003 | (bindings . <bindings>) 6004 | (pre . <pre-handler>) 6005 | (macro . <macro-handler>) 6006 6007 PRE-LAYOUT-HANDLER 6008 A function of three arguments: 6009 6010 KIDS 6011 the kids of the current node, before traversal 6012 6013 PARAMS 6014 the params of the current node 6015 6016 LAYOUT 6017 the layout coming into this node 6018 6019 PRE-LAYOUT-HANDLER is expected to use this information to 6020 return a layout to pass to the kids. The default 6021 implementation returns the layout given in the arguments. 6022 6023 POST-HANDLER 6024 A function of five arguments: 6025 6026 TAG 6027 the current tag being processed 6028 6029 PARAMS 6030 the params of the current node 6031 6032 LAYOUT 6033 the layout coming into the current node, before any kids 6034 were processed 6035 6036 KLAYOUT 6037 the layout after processing all of the children 6038 6039 KIDS 6040 the already-processed child nodes 6041 6042 POST-HANDLER should return two values, the layout to pass to 6043 the next node and the final tree. 6044 6045 TEXT-HANDLER 6046 TEXT-HANDLER is a function of three arguments: 6047 6048 TEXT 6049 the string 6050 6051 PARAMS 6052 the current params 6053 6054 LAYOUT 6055 the current layout 6056 6057 TEXT-HANDLER should return two values, the layout to pass to 6058 the next node and the value to which the string should 6059 transform. 6060 6061 6062File: guile.info, Node: SXPath, Next: sxml ssax input-parse, Prev: SXML Tree Fold, Up: SXML 6063 60647.21.6 SXPath 6065------------- 6066 60677.21.6.1 Overview 6068................. 6069 6070SXPath: SXML Query Language 6071=========================== 6072 6073SXPath is a query language for SXML, an instance of XML Information set 6074(Infoset) in the form of s-expressions. See ‘(sxml ssax)’ for the 6075definition of SXML and more details. SXPath is also a translation into 6076Scheme of an XML Path Language, XPath (http://www.w3.org/TR/xpath). 6077XPath and SXPath describe means of selecting a set of Infoset’s items or 6078their properties. 6079 6080 To facilitate queries, XPath maps the XML Infoset into an explicit 6081tree, and introduces important notions of a location path and a current, 6082context node. A location path denotes a selection of a set of nodes 6083relative to a context node. Any XPath tree has a distinguished, root 6084node – which serves as the context node for absolute location paths. 6085Location path is recursively defined as a location step joined with a 6086location path. A location step is a simple query of the database 6087relative to a context node. A step may include expressions that further 6088filter the selected set. Each node in the resulting set is used as a 6089context node for the adjoining location path. The result of the step is 6090a union of the sets returned by the latter location paths. 6091 6092 The SXML representation of the XML Infoset (see SSAX.scm) is rather 6093suitable for querying as it is. Bowing to the XPath specification, we 6094will refer to SXML information items as ’Nodes’: 6095 6096 <Node> ::= <Element> | <attributes-coll> | <attrib> 6097 | "text string" | <PI> 6098 6099 This production can also be described as 6100 6101 <Node> ::= (name . <Nodeset>) | "text string" 6102 6103 An (ordered) set of nodes is just a list of the constituent nodes: 6104 6105 <Nodeset> ::= (<Node> ...) 6106 6107 Nodesets, and Nodes other than text strings are both lists. A 6108<Nodeset> however is either an empty list, or a list whose head is not a 6109symbol. A symbol at the head of a node is either an XML name (in which 6110case it’s a tag of an XML element), or an administrative name such as 6111’@’. This uniform list representation makes processing rather simple 6112and elegant, while avoiding confusion. The multi-branch tree structure 6113formed by the mutually-recursive datatypes <Node> and <Nodeset> lends 6114itself well to processing by functional languages. 6115 6116 A location path is in fact a composite query over an XPath tree or 6117its branch. A singe step is a combination of a projection, selection or 6118a transitive closure. Multiple steps are combined via join and union 6119operations. This insight allows us to _elegantly_ implement XPath as a 6120sequence of projection and filtering primitives – converters – joined by 6121“combinators”. Each converter takes a node and returns a nodeset which 6122is the result of the corresponding query relative to that node. A 6123converter can also be called on a set of nodes. In that case it returns 6124a union of the corresponding queries over each node in the set. The 6125union is easily implemented as a list append operation as all nodes in a 6126SXML tree are considered distinct, by XPath conventions. We also 6127preserve the order of the members in the union. Query combinators are 6128high-order functions: they take converter(s) (which is a Node|Nodeset -> 6129Nodeset function) and compose or otherwise combine them. We will be 6130concerned with only relative location paths [XPath]: an absolute 6131location path is a relative path applied to the root node. 6132 6133 Similarly to XPath, SXPath defines full and abbreviated notations for 6134location paths. In both cases, the abbreviated notation can be 6135mechanically expanded into the full form by simple rewriting rules. In 6136the case of SXPath the corresponding rules are given in the 6137documentation of the ‘sxpath’ procedure. *Note SXPath procedure 6138documentation: sxpath-procedure-docs. 6139 6140 The regression test suite at the end of the file ‘SXPATH-old.scm’ 6141shows a representative sample of SXPaths in both notations, juxtaposed 6142with the corresponding XPath expressions. Most of the samples are 6143borrowed literally from the XPath specification. 6144 6145 Much of the following material is taken from the SXPath sources by 6146Oleg Kiselyov et al. 6147 61487.21.6.2 Basic Converters and Applicators 6149......................................... 6150 6151A converter is a function mapping a nodeset (or a single node) to 6152another nodeset. Its type can be represented like this: 6153 6154 type Converter = Node|Nodeset -> Nodeset 6155 6156 A converter can also play the role of a predicate: in that case, if a 6157converter, applied to a node or a nodeset, yields a non-empty nodeset, 6158the converter-predicate is deemed satisfied. Likewise, an empty nodeset 6159is equivalent to ‘#f’ in denoting failure. 6160 6161 -- Scheme Procedure: nodeset? x 6162 Return ‘#t’ if X is a nodeset. 6163 6164 -- Scheme Procedure: node-typeof? crit 6165 This function implements a ’Node test’ as defined in Sec. 2.3 of 6166 the XPath document. A node test is one of the components of a 6167 location step. It is also a converter-predicate in SXPath. 6168 6169 The function ‘node-typeof?’ takes a type criterion and returns a 6170 function, which, when applied to a node, will tell if the node 6171 satisfies the test. 6172 6173 The criterion CRIT is a symbol, one of the following: 6174 6175 ‘id’ 6176 tests if the node has the right name (id) 6177 6178 ‘@’ 6179 tests if the node is an <attributes-coll> 6180 6181 ‘*’ 6182 tests if the node is an <Element> 6183 6184 ‘*text*’ 6185 tests if the node is a text node 6186 6187 ‘*PI*’ 6188 tests if the node is a PI (processing instruction) node 6189 6190 ‘*any*’ 6191 ‘#t’ for any type of node 6192 6193 -- Scheme Procedure: node-eq? other 6194 A curried equivalence converter predicate that takes a node OTHER 6195 and returns a function that takes another node. The two nodes are 6196 compared using ‘eq?’. 6197 6198 -- Scheme Procedure: node-equal? other 6199 A curried equivalence converter predicate that takes a node OTHER 6200 and returns a function that takes another node. The two nodes are 6201 compared using ‘equal?’. 6202 6203 -- Scheme Procedure: node-pos n 6204 Select the N’th element of a nodeset and return as a singular 6205 nodeset. If the N’th element does not exist, return an empty 6206 nodeset. If N is a negative number the node is picked from the 6207 tail of the list. 6208 6209 ((node-pos 1) nodeset) ; return the the head of the nodeset (if exists) 6210 ((node-pos 2) nodeset) ; return the node after that (if exists) 6211 ((node-pos -1) nodeset) ; selects the last node of a non-empty nodeset 6212 ((node-pos -2) nodeset) ; selects the last but one node, if exists. 6213 6214 -- Scheme Procedure: filter pred? 6215 A filter applicator, which introduces a filtering context. The 6216 argument converter PRED? is considered a predicate, with either 6217 ‘#f’ or ‘nil’ meaning failure. 6218 6219 -- Scheme Procedure: take-until pred? 6220 take-until:: Converter -> Converter, or 6221 take-until:: Pred -> Node|Nodeset -> Nodeset 6222 6223 Given a converter-predicate PRED? and a nodeset, apply the 6224 predicate to each element of the nodeset, until the predicate 6225 yields anything but ‘#f’ or ‘nil’. Return the elements of the 6226 input nodeset that have been processed until that moment (that is, 6227 which fail the predicate). 6228 6229 ‘take-until’ is a variation of the ‘filter’ above: ‘take-until’ 6230 passes elements of an ordered input set up to (but not including) 6231 the first element that satisfies the predicate. The nodeset 6232 returned by ‘((take-until (not pred)) nset)’ is a subset – to be 6233 more precise, a prefix – of the nodeset returned by ‘((filter pred) 6234 nset)’. 6235 6236 -- Scheme Procedure: take-after pred? 6237 take-after:: Converter -> Converter, or 6238 take-after:: Pred -> Node|Nodeset -> Nodeset 6239 6240 Given a converter-predicate PRED? and a nodeset, apply the 6241 predicate to each element of the nodeset, until the predicate 6242 yields anything but ‘#f’ or ‘nil’. Return the elements of the 6243 input nodeset that have not been processed: that is, return the 6244 elements of the input nodeset that follow the first element that 6245 satisfied the predicate. 6246 6247 ‘take-after’ along with ‘take-until’ partition an input nodeset 6248 into three parts: the first element that satisfies a predicate, all 6249 preceding elements and all following elements. 6250 6251 -- Scheme Procedure: map-union proc lst 6252 Apply PROC to each element of LST and return the list of results. 6253 If PROC returns a nodeset, splice it into the result 6254 6255 From another point of view, ‘map-union’ is a function 6256 ‘Converter->Converter’, which places an argument-converter in a 6257 joining context. 6258 6259 -- Scheme Procedure: node-reverse node-or-nodeset 6260 node-reverse :: Converter, or 6261 node-reverse:: Node|Nodeset -> Nodeset 6262 6263 Reverses the order of nodes in the nodeset. This basic converter 6264 is needed to implement a reverse document order (see the XPath 6265 Recommendation). 6266 6267 -- Scheme Procedure: node-trace title 6268 node-trace:: String -> Converter 6269 6270 ‘(node-trace title)’ is an identity converter. In addition it 6271 prints out the node or nodeset it is applied to, prefixed with the 6272 TITLE. This converter is very useful for debugging. 6273 62747.21.6.3 Converter Combinators 6275.............................. 6276 6277Combinators are higher-order functions that transmogrify a converter or 6278glue a sequence of converters into a single, non-trivial converter. The 6279goal is to arrive at converters that correspond to XPath location paths. 6280 6281 From a different point of view, a combinator is a fixed, named 6282“pattern” of applying converters. Given below is a complete set of such 6283patterns that together implement XPath location path specification. As 6284it turns out, all these combinators can be built from a small number of 6285basic blocks: regular functional composition, ‘map-union’ and ‘filter’ 6286applicators, and the nodeset union. 6287 6288 -- Scheme Procedure: select-kids test-pred? 6289 ‘select-kids’ takes a converter (or a predicate) as an argument and 6290 returns another converter. The resulting converter applied to a 6291 nodeset returns an ordered subset of its children that satisfy the 6292 predicate TEST-PRED?. 6293 6294 -- Scheme Procedure: node-self pred? 6295 Similar to ‘select-kids’ except that the predicate PRED? is applied 6296 to the node itself rather than to its children. The resulting 6297 nodeset will contain either one component, or will be empty if the 6298 node failed the predicate. 6299 6300 -- Scheme Procedure: node-join . selectors 6301 node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or 6302 node-join:: [Converter] -> Converter 6303 6304 Join the sequence of location steps or paths as described above. 6305 6306 -- Scheme Procedure: node-reduce . converters 6307 node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or 6308 node-reduce:: [Converter] -> Converter 6309 6310 A regular functional composition of converters. From a different 6311 point of view, ‘((apply node-reduce converters) nodeset)’ is 6312 equivalent to ‘(foldl apply nodeset converters)’, i.e., folding, or 6313 reducing, a list of converters with the nodeset as a seed. 6314 6315 -- Scheme Procedure: node-or . converters 6316 node-or:: [Converter] -> Converter 6317 6318 This combinator applies all converters to a given node and produces 6319 the union of their results. This combinator corresponds to a union 6320 (‘|’ operation) for XPath location paths. 6321 6322 -- Scheme Procedure: node-closure test-pred? 6323 node-closure:: Converter -> Converter 6324 6325 Select all _descendants_ of a node that satisfy a 6326 converter-predicate TEST-PRED?. This combinator is similar to 6327 ‘select-kids’ but applies to grand... children as well. This 6328 combinator implements the ‘descendant::’ XPath axis. Conceptually, 6329 this combinator can be expressed as 6330 6331 (define (node-closure f) 6332 (node-or 6333 (select-kids f) 6334 (node-reduce (select-kids (node-typeof? '*)) (node-closure f)))) 6335 6336 This definition, as written, looks somewhat like a fixpoint, and it 6337 will run forever. It is obvious however that sooner or later 6338 ‘(select-kids (node-typeof? '*))’ will return an empty nodeset. At 6339 this point further iterations will no longer affect the result and 6340 can be stopped. 6341 6342 -- Scheme Procedure: node-parent rootnode 6343 node-parent:: RootNode -> Converter 6344 6345 ‘(node-parent rootnode)’ yields a converter that returns a parent 6346 of a node it is applied to. If applied to a nodeset, it returns 6347 the list of parents of nodes in the nodeset. The ROOTNODE does not 6348 have to be the root node of the whole SXML tree – it may be a root 6349 node of a branch of interest. 6350 6351 Given the notation of Philip Wadler’s paper on semantics of XSLT, 6352 6353 parent(x) = { y | y=subnode*(root), x=subnode(y) } 6354 6355 Therefore, ‘node-parent’ is not the fundamental converter: it can 6356 be expressed through the existing ones. Yet ‘node-parent’ is a 6357 rather convenient converter. It corresponds to a ‘parent::’ axis 6358 of SXPath. Note that the ‘parent::’ axis can be used with an 6359 attribute node as well. 6360 6361 -- Scheme Procedure: sxpath path 6362 Evaluate an abbreviated SXPath. 6363 6364 sxpath:: AbbrPath -> Converter, or 6365 sxpath:: AbbrPath -> Node|Nodeset -> Nodeset 6366 6367 PATH is a list. It is translated to the full SXPath according to 6368 the following rewriting rules: 6369 6370 (sxpath '()) 6371 ⇒ (node-join) 6372 6373 (sxpath '(path-component ...)) 6374 ⇒ (node-join (sxpath1 path-component) (sxpath '(...))) 6375 6376 (sxpath1 '//) 6377 ⇒ (node-or 6378 (node-self (node-typeof? '*any*)) 6379 (node-closure (node-typeof? '*any*))) 6380 6381 (sxpath1 '(equal? x)) 6382 ⇒ (select-kids (node-equal? x)) 6383 6384 (sxpath1 '(eq? x)) 6385 ⇒ (select-kids (node-eq? x)) 6386 6387 (sxpath1 ?symbol) 6388 ⇒ (select-kids (node-typeof? ?symbol) 6389 6390 (sxpath1 procedure) 6391 ⇒ procedure 6392 6393 (sxpath1 '(?symbol ...)) 6394 ⇒ (sxpath1 '((?symbol) ...)) 6395 6396 (sxpath1 '(path reducer ...)) 6397 ⇒ (node-reduce (sxpath path) (sxpathr reducer) ...) 6398 6399 (sxpathr number) 6400 ⇒ (node-pos number) 6401 6402 (sxpathr path-filter) 6403 ⇒ (filter (sxpath path-filter)) 6404 6405 6406File: guile.info, Node: sxml ssax input-parse, Next: sxml apply-templates, Prev: SXPath, Up: SXML 6407 64087.21.7 (sxml ssax input-parse) 6409------------------------------ 6410 64117.21.7.1 Overview 6412................. 6413 6414A simple lexer. 6415 6416 The procedures in this module surprisingly often suffice to parse an 6417input stream. They either skip, or build and return tokens, according 6418to inclusion or delimiting semantics. The list of characters to expect, 6419include, or to break at may vary from one invocation of a function to 6420another. This allows the functions to easily parse even 6421context-sensitive languages. 6422 6423 EOF is generally frowned on, and thrown up upon if encountered. 6424Exceptions are mentioned specifically. The list of expected characters 6425(characters to skip until, or break-characters) may include an EOF 6426"character", which is to be coded as the symbol, ‘*eof*’. 6427 6428 The input stream to parse is specified as a “port”, which is usually 6429the last (and optional) argument. It defaults to the current input port 6430if omitted. 6431 6432 If the parser encounters an error, it will throw an exception to the 6433key ‘parser-error’. The arguments will be of the form ‘(PORT MESSAGE 6434SPECIALISING-MSG*)’. 6435 6436 The first argument is a port, which typically points to the offending 6437character or its neighborhood. You can then use ‘port-column’ and 6438‘port-line’ to query the current position. MESSAGE is the description 6439of the error. Other arguments supply more details about the problem. 6440 64417.21.7.2 Usage 6442.............. 6443 6444 -- Scheme Procedure: peek-next-char [port] 6445 6446 -- Scheme Procedure: assert-curr-char expected-chars comment [port] 6447 6448 -- Scheme Procedure: skip-until arg [port] 6449 6450 -- Scheme Procedure: skip-while skip-chars [port] 6451 6452 -- Scheme Procedure: next-token prefix-skipped-chars break-chars 6453 [comment] [port] 6454 6455 -- Scheme Procedure: next-token-of incl-list/pred [port] 6456 6457 -- Scheme Procedure: read-text-line [port] 6458 6459 -- Scheme Procedure: read-string n [port] 6460 6461 -- Scheme Procedure: find-string-from-port? _ _ . _ 6462 Looks for STR in <INPUT-PORT>, optionally within the first 6463 MAX-NO-CHAR characters. 6464 6465 6466File: guile.info, Node: sxml apply-templates, Prev: sxml ssax input-parse, Up: SXML 6467 64687.21.8 (sxml apply-templates) 6469----------------------------- 6470 64717.21.8.1 Overview 6472................. 6473 6474Pre-order traversal of a tree and creation of a new tree: 6475 6476 apply-templates:: tree x <templates> -> <new-tree> 6477 6478 where 6479 6480 <templates> ::= (<template> ...) 6481 <template> ::= (<node-test> <node-test> ... <node-test> . <handler>) 6482 <node-test> ::= an argument to node-typeof? above 6483 <handler> ::= <tree> -> <new-tree> 6484 6485 This procedure does a _normal_, pre-order traversal of an SXML tree. 6486It walks the tree, checking at each node against the list of matching 6487templates. 6488 6489 If the match is found (which must be unique, i.e., unambiguous), the 6490corresponding handler is invoked and given the current node as an 6491argument. The result from the handler, which must be a ‘<tree>’, takes 6492place of the current node in the resulting tree. The name of the 6493function is not accidental: it resembles rather closely an 6494‘apply-templates’ function of XSLT. 6495 64967.21.8.2 Usage 6497.............. 6498 6499 -- Scheme Procedure: apply-templates tree templates 6500 6501 6502File: guile.info, Node: Texinfo Processing, Prev: SXML, Up: Guile Modules 6503 65047.22 Texinfo Processing 6505======================= 6506 6507* Menu: 6508 6509* texinfo:: Parse texinfo files or fragments into ‘stexi’, a scheme representation 6510* texinfo docbook:: Transform a subset of docbook into ‘stexi’ 6511* texinfo html:: Transform ‘stexi’ into HTML 6512* texinfo indexing:: Extract an index from a piece of ‘stexi’ 6513* texinfo string-utils:: String utility functions used by the texinfo processor 6514* texinfo plain-text:: Render ‘stexi’ as plain text 6515* texinfo serialize:: Render ‘stexi’ as texinfo 6516* texinfo reflection:: Enable texinfo across Guile’s help system 6517 6518 6519File: guile.info, Node: texinfo, Next: texinfo docbook, Up: Texinfo Processing 6520 65217.22.1 (texinfo) 6522---------------- 6523 65247.22.1.1 Overview 6525................. 6526 6527Texinfo processing in scheme 6528---------------------------- 6529 6530This module parses texinfo into SXML. TeX will always be the processor 6531of choice for print output, of course. However, although ‘makeinfo’ 6532works well for info, its output in other formats is not very 6533customizable, and the program is not extensible as a whole. This module 6534aims to provide an extensible framework for texinfo processing that 6535integrates texinfo into the constellation of SXML processing tools. 6536 6537Notes on the SXML vocabulary 6538---------------------------- 6539 6540Consider the following texinfo fragment: 6541 6542 @deffn Primitive set-car! pair value 6543 This function... 6544 @end deffn 6545 6546 Logically, the category (Primitive), name (set-car!), and arguments 6547(pair value) are “attributes” of the deffn, with the description as the 6548content. However, texinfo allows for @-commands within the arguments to 6549an environment, like ‘@deffn’, which means that texinfo “attributes” are 6550PCDATA. XML attributes, on the other hand, are CDATA. For this reason, 6551“attributes” of texinfo @-commands are called “arguments”, and are 6552grouped under the special element, ‘%’. 6553 6554 Because ‘%’ is not a valid NCName, stexinfo is a superset of SXML. In 6555the interests of interoperability, this module provides a conversion 6556function to replace the ‘%’ with ‘texinfo-arguments’. 6557 65587.22.1.2 Usage 6559.............. 6560 6561 -- Function: call-with-file-and-dir filename proc 6562 Call the one-argument procedure PROC with an input port that reads 6563 from FILENAME. During the dynamic extent of PROC’s execution, the 6564 current directory will be ‘(dirname FILENAME)’. This is useful for 6565 parsing documents that can include files by relative path name. 6566 6567 -- Variable: texi-command-specs 6568 6569 -- Function: texi-command-depth command max-depth 6570 Given the texinfo command COMMAND, return its nesting level, or 6571 ‘#f’ if it nests too deep for MAX-DEPTH. 6572 6573 Examples: 6574 6575 (texi-command-depth 'chapter 4) ⇒ 1 6576 (texi-command-depth 'top 4) ⇒ 0 6577 (texi-command-depth 'subsection 4) ⇒ 3 6578 (texi-command-depth 'appendixsubsec 4) ⇒ 3 6579 (texi-command-depth 'subsection 2) ⇒ #f 6580 6581 -- Function: texi-fragment->stexi string-or-port 6582 Parse the texinfo commands in STRING-OR-PORT, and return the 6583 resultant stexi tree. The head of the tree will be the special 6584 command, ‘*fragment*’. 6585 6586 -- Function: texi->stexi port 6587 Read a full texinfo document from PORT and return the parsed stexi 6588 tree. The parsing will start at the ‘@settitle’ and end at ‘@bye’ 6589 or EOF. 6590 6591 -- Function: stexi->sxml tree 6592 Transform the stexi tree TREE into sxml. This involves replacing 6593 the ‘%’ element that keeps the texinfo arguments with an element 6594 for each argument. 6595 6596 FIXME: right now it just changes % to ‘texinfo-arguments’ – that 6597 doesn’t hang with the idea of making a dtd at some point 6598 6599 6600File: guile.info, Node: texinfo docbook, Next: texinfo html, Prev: texinfo, Up: Texinfo Processing 6601 66027.22.2 (texinfo docbook) 6603------------------------ 6604 66057.22.2.1 Overview 6606................. 6607 6608This module exports procedures for transforming a limited subset of the 6609SXML representation of docbook into stexi. It is not complete by any 6610means. The intention is to gather a number of routines and stylesheets 6611so that external modules can parse specific subsets of docbook, for 6612example that set generated by certain tools. 6613 66147.22.2.2 Usage 6615.............. 6616 6617 -- Variable: *sdocbook->stexi-rules* 6618 6619 -- Variable: *sdocbook-block-commands* 6620 6621 -- Function: sdocbook-flatten sdocbook 6622 "Flatten" a fragment of sdocbook so that block elements do not nest 6623 inside each other. 6624 6625 Docbook is a nested format, where e.g. a ‘refsect2’ normally 6626 appears inside a ‘refsect1’. Logical divisions in the document are 6627 represented via the tree topology; a ‘refsect2’ element _contains_ 6628 all of the elements in its section. 6629 6630 On the contrary, texinfo is a flat format, in which sections are 6631 marked off by standalone section headers like ‘@subsection’, and 6632 block elements do not nest inside each other. 6633 6634 This function takes a nested sdocbook fragment SDOCBOOK and 6635 flattens all of the sections, such that e.g. 6636 6637 (refsect1 (refsect2 (para "Hello"))) 6638 6639 becomes 6640 6641 ((refsect1) (refsect2) (para "Hello")) 6642 6643 Oftentimes (always?) sectioning elements have ‘<title>’ as their 6644 first element child; users interested in processing the ‘refsect*’ 6645 elements into proper sectioning elements like ‘chapter’ might be 6646 interested in ‘replace-titles’ and ‘filter-empty-elements’. *Note 6647 replace-titles: texinfo docbook replace-titles, and *note 6648 filter-empty-elements: texinfo docbook filter-empty-elements. 6649 6650 Returns a nodeset; that is to say, an untagged list of stexi 6651 elements. *Note SXPath::, for the definition of a nodeset. 6652 6653 -- Function: filter-empty-elements sdocbook 6654 Filters out empty elements in an sdocbook nodeset. Mostly useful 6655 after running ‘sdocbook-flatten’. 6656 6657 -- Function: replace-titles sdocbook-fragment 6658 Iterate over the sdocbook nodeset SDOCBOOK-FRAGMENT, transforming 6659 contiguous ‘refsect’ and ‘title’ elements into the appropriate 6660 texinfo sectioning command. Most useful after having run 6661 ‘sdocbook-flatten’. 6662 6663 For example: 6664 6665 (replace-titles '((refsect1) (title "Foo") (para "Bar."))) 6666 ⇒ '((chapter "Foo") (para "Bar.")) 6667 6668 6669File: guile.info, Node: texinfo html, Next: texinfo indexing, Prev: texinfo docbook, Up: Texinfo Processing 6670 66717.22.3 (texinfo html) 6672--------------------- 6673 66747.22.3.1 Overview 6675................. 6676 6677This module implements transformation from ‘stexi’ to HTML. Note that 6678the output of ‘stexi->shtml’ is actually SXML with the HTML vocabulary. 6679This means that the output can be further processed, and that it must 6680eventually be serialized by ‘sxml->xml’. *Note Reading and Writing 6681XML::. 6682 6683 References (i.e., the ‘@ref’ family of commands) are resolved by a 6684“ref-resolver”. *Note add-ref-resolver!: texinfo html 6685add-ref-resolver!. 6686 66877.22.3.2 Usage 6688.............. 6689 6690 -- Function: add-ref-resolver! proc 6691 Add PROC to the head of the list of ref-resolvers. PROC will be 6692 expected to take the name of a node and the name of a manual and 6693 return the URL of the referent, or ‘#f’ to pass control to the next 6694 ref-resolver in the list. 6695 6696 The default ref-resolver will return the concatenation of the 6697 manual name, ‘#’, and the node name. 6698 6699 -- Function: stexi->shtml tree 6700 Transform the stexi TREE into shtml, resolving references via 6701 ref-resolvers. See the module commentary for more details. 6702 6703 -- Function: urlify str 6704 6705 6706File: guile.info, Node: texinfo indexing, Next: texinfo string-utils, Prev: texinfo html, Up: Texinfo Processing 6707 67087.22.4 (texinfo indexing) 6709------------------------- 6710 67117.22.4.1 Overview 6712................. 6713 6714Given a piece of stexi, return an index of a specified variety. 6715 6716 Note that currently, ‘stexi-extract-index’ doesn’t differentiate 6717between different kinds of index entries. That’s a bug ;) 6718 67197.22.4.2 Usage 6720.............. 6721 6722 -- Function: stexi-extract-index tree manual-name kind 6723 Given an stexi tree TREE, index all of the entries of type KIND. 6724 KIND can be one of the predefined texinfo indices (‘concept’, 6725 ‘variable’, ‘function’, ‘key’, ‘program’, ‘type’) or one of the 6726 special symbols ‘auto’ or ‘all’. ‘auto’ will scan the stext for a 6727 ‘(printindex)’ statement, and ‘all’ will generate an index from all 6728 entries, regardless of type. 6729 6730 The returned index is a list of pairs, the CAR of which is the 6731 entry (a string) and the CDR of which is a node name (a string). 6732 6733 6734File: guile.info, Node: texinfo string-utils, Next: texinfo plain-text, Prev: texinfo indexing, Up: Texinfo Processing 6735 67367.22.5 (texinfo string-utils) 6737----------------------------- 6738 67397.22.5.1 Overview 6740................. 6741 6742Module ‘(texinfo string-utils)’ provides various string-related 6743functions useful to Guile’s texinfo support. 6744 67457.22.5.2 Usage 6746.............. 6747 6748 -- Function: escape-special-chars str special-chars escape-char 6749 Returns a copy of STR with all given special characters preceded by 6750 the given ESCAPE-CHAR. 6751 6752 SPECIAL-CHARS can either be a single character, or a string 6753 consisting of all the special characters. 6754 6755 ;; make a string regexp-safe... 6756 (escape-special-chars "***(Example String)***" 6757 "[]()/*." 6758 #\\) 6759 => "\\*\\*\\*\\(Example String\\)\\*\\*\\*" 6760 6761 ;; also can escape a singe char... 6762 (escape-special-chars "richardt@vzavenue.net" 6763 #\@ 6764 #\@) 6765 => "richardt@@vzavenue.net" 6766 6767 -- Function: transform-string str match? replace [start] [end] 6768 Uses MATCH? against each character in STR, and performs a 6769 replacement on each character for which matches are found. 6770 6771 MATCH? may either be a function, a character, a string, or ‘#t’. 6772 If MATCH? is a function, then it takes a single character as input, 6773 and should return ‘#t’ for matches. MATCH? is a character, it is 6774 compared to each string character using ‘char=?’. If MATCH? is a 6775 string, then any character in that string will be considered a 6776 match. ‘#t’ will cause every character to be a match. 6777 6778 If REPLACE is a function, it is called with the matched character 6779 as an argument, and the returned value is sent to the output string 6780 via ‘display’. If REPLACE is anything else, it is sent through the 6781 output string via ‘display’. 6782 6783 Note that the replacement for the matched characters does not need 6784 to be a single character. That is what differentiates this 6785 function from ‘string-map’, and what makes it useful for 6786 applications such as converting ‘#\&’ to ‘"&"’ in web page 6787 text. Some other functions in this module are just wrappers around 6788 common uses of ‘transform-string’. Transformations not possible 6789 with this function should probably be done with regular 6790 expressions. 6791 6792 If START and END are given, they control which portion of the 6793 string undergoes transformation. The entire input string is still 6794 output, though. So, if START is ‘5’, then the first five 6795 characters of STR will still appear in the returned string. 6796 6797 ; these two are equivalent... 6798 (transform-string str #\space #\-) ; change all spaces to -'s 6799 (transform-string str (lambda (c) (char=? #\space c)) #\-) 6800 6801 -- Function: expand-tabs str [tab-size] 6802 Returns a copy of STR with all tabs expanded to spaces. TAB-SIZE 6803 defaults to 8. 6804 6805 Assuming tab size of 8, this is equivalent to: 6806 6807 (transform-string str #\tab " ") 6808 6809 -- Function: center-string str [width] [chr] [rchr] 6810 Returns a copy of STR centered in a field of WIDTH characters. Any 6811 needed padding is done by character CHR, which defaults to 6812 ‘#\space’. If RCHR is provided, then the padding to the right will 6813 use it instead. See the examples below. left and RCHR on the 6814 right. The default WIDTH is 80. The default CHR and RCHR is 6815 ‘#\space’. The string is never truncated. 6816 6817 (center-string "Richard Todd" 24) 6818 => " Richard Todd " 6819 6820 (center-string " Richard Todd " 24 #\=) 6821 => "===== Richard Todd =====" 6822 6823 (center-string " Richard Todd " 24 #\< #\>) 6824 => "<<<<< Richard Todd >>>>>" 6825 6826 -- Function: left-justify-string str [width] [chr] 6827 ‘left-justify-string str [width chr]’. Returns a copy of STR 6828 padded with CHR such that it is left justified in a field of WIDTH 6829 characters. The default WIDTH is 80. Unlike ‘string-pad’ from 6830 srfi-13, the string is never truncated. 6831 6832 -- Function: right-justify-string str [width] [chr] 6833 Returns a copy of STR padded with CHR such that it is right 6834 justified in a field of WIDTH characters. The default WIDTH is 80. 6835 The default CHR is ‘#\space’. Unlike ‘string-pad’ from srfi-13, 6836 the string is never truncated. 6837 6838 -- Function: collapse-repeated-chars str [chr] [num] 6839 Returns a copy of STR with all repeated instances of CHR collapsed 6840 down to at most NUM instances. The default value for CHR is 6841 ‘#\space’, and the default value for NUM is 1. 6842 6843 (collapse-repeated-chars "H e l l o") 6844 => "H e l l o" 6845 (collapse-repeated-chars "H--e--l--l--o" #\-) 6846 => "H-e-l-l-o" 6847 (collapse-repeated-chars "H-e--l---l----o" #\- 2) 6848 => "H-e--l--l--o" 6849 6850 -- Function: make-text-wrapper [#:line-width] [#:expand-tabs?] 6851 [#:tab-width] [#:collapse-whitespace?] [#:subsequent-indent] 6852 [#:initial-indent] [#:break-long-words?] 6853 Returns a procedure that will split a string into lines according 6854 to the given parameters. 6855 6856 ‘#:line-width’ 6857 This is the target length used when deciding where to wrap 6858 lines. Default is 80. 6859 6860 ‘#:expand-tabs?’ 6861 Boolean describing whether tabs in the input should be 6862 expanded. Default is #t. 6863 6864 ‘#:tab-width’ 6865 If tabs are expanded, this will be the number of spaces to 6866 which they expand. Default is 8. 6867 6868 ‘#:collapse-whitespace?’ 6869 Boolean describing whether the whitespace inside the existing 6870 text should be removed or not. Default is #t. 6871 6872 If text is already well-formatted, and is just being wrapped 6873 to fit in a different width, then set this to ‘#f’. This way, 6874 many common text conventions (such as two spaces between 6875 sentences) can be preserved if in the original text. If the 6876 input text spacing cannot be trusted, then leave this setting 6877 at the default, and all repeated whitespace will be collapsed 6878 down to a single space. 6879 6880 ‘#:initial-indent’ 6881 Defines a string that will be put in front of the first line 6882 of wrapped text. Default is the empty string, “”. 6883 6884 ‘#:subsequent-indent’ 6885 Defines a string that will be put in front of all lines of 6886 wrapped text, except the first one. Default is the empty 6887 string, “”. 6888 6889 ‘#:break-long-words?’ 6890 If a single word is too big to fit on a line, this setting 6891 tells the wrapper what to do. Defaults to #t, which will 6892 break up long words. When set to #f, the line will be 6893 allowed, even though it is longer than the defined 6894 ‘#:line-width’. 6895 6896 The return value is a procedure of one argument, the input string, 6897 which returns a list of strings, where each element of the list is 6898 one line. 6899 6900 -- Function: fill-string str . kwargs 6901 Wraps the text given in string STR according to the parameters 6902 provided in KWARGS, or the default setting if they are not given. 6903 Returns a single string with the wrapped text. Valid keyword 6904 arguments are discussed in ‘make-text-wrapper’. 6905 6906 -- Function: string->wrapped-lines str . kwargs 6907 ‘string->wrapped-lines str keywds ...’. Wraps the text given in 6908 string STR according to the parameters provided in KEYWDS, or the 6909 default setting if they are not given. Returns a list of strings 6910 representing the formatted lines. Valid keyword arguments are 6911 discussed in ‘make-text-wrapper’. 6912 6913 6914File: guile.info, Node: texinfo plain-text, Next: texinfo serialize, Prev: texinfo string-utils, Up: Texinfo Processing 6915 69167.22.6 (texinfo plain-text) 6917--------------------------- 6918 69197.22.6.1 Overview 6920................. 6921 6922Transformation from stexi to plain-text. Strives to re-create the 6923output from ‘info’; comes pretty damn close. 6924 69257.22.6.2 Usage 6926.............. 6927 6928 -- Function: stexi->plain-text tree 6929 Transform TREE into plain text. Returns a string. 6930 6931 -- Scheme Variable: *line-width* 6932 This fluid (*note Fluids and Dynamic States::) specifies the length 6933 of line for the purposes of line wrapping in the 6934 ‘stexi->plain-text’ conversion. 6935 6936 6937File: guile.info, Node: texinfo serialize, Next: texinfo reflection, Prev: texinfo plain-text, Up: Texinfo Processing 6938 69397.22.7 (texinfo serialize) 6940-------------------------- 6941 69427.22.7.1 Overview 6943................. 6944 6945Serialization of ‘stexi’ to plain texinfo. 6946 69477.22.7.2 Usage 6948.............. 6949 6950 -- Function: stexi->texi tree 6951 Serialize the stexi TREE into plain texinfo. 6952 6953 6954File: guile.info, Node: texinfo reflection, Prev: texinfo serialize, Up: Texinfo Processing 6955 69567.22.8 (texinfo reflection) 6957--------------------------- 6958 69597.22.8.1 Overview 6960................. 6961 6962Routines to generare ‘stexi’ documentation for objects and modules. 6963 6964 Note that in this context, an “object” is just a value associated 6965with a location. It has nothing to do with GOOPS. 6966 69677.22.8.2 Usage 6968.............. 6969 6970 -- Function: module-stexi-documentation sym-name [%docs-resolver] 6971 [#:docs-resolver] 6972 Return documentation for the module named SYM-NAME. The 6973 documentation will be formatted as ‘stexi’ (*note texinfo: 6974 texinfo.). 6975 6976 -- Function: script-stexi-documentation scriptpath 6977 Return documentation for given script. The documentation will be 6978 taken from the script’s commentary, and will be returned in the 6979 ‘stexi’ format (*note texinfo: texinfo.). 6980 6981 -- Function: object-stexi-documentation _ [_] [#:force] 6982 6983 -- Function: package-stexi-standard-copying name version updated years 6984 copyright-holder permissions 6985 Create a standard texinfo ‘copying’ section. 6986 6987 YEARS is a list of years (as integers) in which the modules being 6988 documented were released. All other arguments are strings. 6989 6990 -- Function: package-stexi-standard-titlepage name version updated 6991 authors 6992 Create a standard GNU title page. 6993 6994 AUTHORS is a list of ‘(NAME . EMAIL)’ pairs. All other arguments 6995 are strings. 6996 6997 Here is an example of the usage of this procedure: 6998 6999 (package-stexi-standard-titlepage 7000 "Foolib" 7001 "3.2" 7002 "26 September 2006" 7003 '(("Alyssa P Hacker" . "alyssa@example.com")) 7004 '(2004 2005 2006) 7005 "Free Software Foundation, Inc." 7006 "Standard GPL permissions blurb goes here") 7007 7008 -- Function: package-stexi-generic-menu name entries 7009 Create a menu from a generic alist of entries, the car of which 7010 should be the node name, and the cdr the description. As an 7011 exception, an entry of ‘#f’ will produce a separator. 7012 7013 -- Function: package-stexi-standard-menu name modules 7014 module-descriptions extra-entries 7015 Create a standard top node and menu, suitable for processing by 7016 makeinfo. 7017 7018 -- Function: package-stexi-extended-menu name module-pairs script-pairs 7019 extra-entries 7020 Create an "extended" menu, like the standard menu but with a 7021 section for scripts. 7022 7023 -- Function: package-stexi-standard-prologue name filename category 7024 description copying titlepage menu 7025 Create a standard prologue, suitable for later serialization to 7026 texinfo and .info creation with makeinfo. 7027 7028 Returns a list of stexinfo forms suitable for passing to 7029 ‘package-stexi-documentation’ as the prologue. *Note texinfo 7030 reflection package-stexi-documentation::, *note 7031 package-stexi-standard-titlepage: texinfo reflection 7032 package-stexi-standard-titlepage, *note 7033 package-stexi-standard-copying: texinfo reflection 7034 package-stexi-standard-copying, and *note 7035 package-stexi-standard-menu: texinfo reflection 7036 package-stexi-standard-menu. 7037 7038 -- Function: package-stexi-documentation modules name filename prologue 7039 epilogue [#:module-stexi-documentation-args] [#:scripts] 7040 Create stexi documentation for a “package”, where a package is a 7041 set of modules that is released together. 7042 7043 MODULES is expected to be a list of module names, where a module 7044 name is a list of symbols. The stexi that is returned will be 7045 titled NAME and a texinfo filename of FILENAME. 7046 7047 PROLOGUE and EPILOGUE are lists of stexi forms that will be spliced 7048 into the output document before and after the generated modules 7049 documentation, respectively. *Note texinfo reflection 7050 package-stexi-standard-prologue::, to create a conventional GNU 7051 texinfo prologue. 7052 7053 MODULE-STEXI-DOCUMENTATION-ARGS is an optional argument that, if 7054 given, will be added to the argument list when 7055 ‘module-texi-documentation’ is called. For example, it might be 7056 useful to define a ‘#:docs-resolver’ argument. 7057 7058 -- Function: package-stexi-documentation-for-include modules 7059 module-descriptions [#:module-stexi-documentation-args] 7060 Create stexi documentation for a “package”, where a package is a 7061 set of modules that is released together. 7062 7063 MODULES is expected to be a list of module names, where a module 7064 name is a list of symbols. Returns an stexinfo fragment. 7065 7066 Unlike ‘package-stexi-documentation’, this function simply produces 7067 a menu and the module documentations instead of producing a full 7068 texinfo document. This can be useful if you write part of your 7069 manual by hand, and just use ‘@include’ to pull in the 7070 automatically generated parts. 7071 7072 MODULE-STEXI-DOCUMENTATION-ARGS is an optional argument that, if 7073 given, will be added to the argument list when 7074 ‘module-texi-documentation’ is called. For example, it might be 7075 useful to define a ‘#:docs-resolver’ argument. 7076 7077 7078File: guile.info, Node: GOOPS, Next: Guile Implementation, Prev: Guile Modules, Up: Top 7079 70808 GOOPS 7081******* 7082 7083GOOPS is the object oriented extension to Guile. Its implementation is 7084derived from STk-3.99.3 by Erick Gallesio and version 1.3 of Gregor 7085Kiczales’ ‘Tiny-Clos’. It is very close in spirit to CLOS, the Common 7086Lisp Object System, but is adapted for the Scheme language. 7087 7088 GOOPS is a full object oriented system, with classes, objects, 7089multiple inheritance, and generic functions with multi-method dispatch. 7090Furthermore its implementation relies on a meta object protocol — which 7091means that GOOPS’s core operations are themselves defined as methods on 7092relevant classes, and can be customised by overriding or redefining 7093those methods. 7094 7095 To start using GOOPS you first need to import the ‘(oop goops)’ 7096module. You can do this at the Guile REPL by evaluating: 7097 7098 (use-modules (oop goops)) 7099 7100* Menu: 7101 7102* Copyright Notice:: 7103* Class Definition:: 7104* Instance Creation:: 7105* Slot Options:: 7106* Slot Description Example:: 7107* Methods and Generic Functions:: 7108* Inheritance:: 7109* Introspection:: 7110* GOOPS Error Handling:: 7111* GOOPS Object Miscellany:: 7112* The Metaobject Protocol:: 7113* Redefining a Class:: 7114* Changing the Class of an Instance:: 7115 7116