s7

s7 is a Scheme implementation intended as an extension language for other applications, primarily Snd, Radium, and Common Music. It exists as just two files, s7.c and s7.h, that want only to disappear into someone else's source tree. There are no libraries, no run-time init files, and no configuration scripts. It can be built as a stand-alone interpreter (see below). s7test.scm is a regression test for s7. A tarball is available: s7 tarball. There is an svn repository at sourceforge (the Snd project): Snd, and a git repository (just s7): git@cm-gitlab.stanford.edu:bil/s7.git s7.git. Please ignore all other "s7" github sites. Christos Vagias created a web-assembly site with a repl: https://github.com/actonDev/s7-playground/.

s7 is the default extension language of Snd and sndlib (snd), Rick Taube's Common Music (commonmusic at sourceforge), and Kjetil Matheussen's Radium music editor. There are X, Motif, and openGL bindings in libxm in the Snd tarball, or at ftp://ccrma-ftp.stanford.edu/pub/Lisp/libxm.tar.gz. If you're running s7 in a context that has getenv, file-exists?, and system, you can use s7-slib-init.scm to gain easy access to slib. This init file is named "s7.init" in the slib distribution.

Although it is a descendant of tinyScheme, s7 is closest as a Scheme dialect to Guile 1.8. I believe it is compatible with r5rs and r7rs: you can just ignore all the additions discussed in this file. It has continuations, ratios, complex numbers, macros, keywords, hash-tables, multiprecision arithmetic, generalized set!, unicode, and so on. It does not have syntax-rules or any of its friends, and it does not think there is any such thing as an inexact integer.

This file assumes you know about Scheme and all its problems, and want a quick tour of where s7 is different. (Well, it was quick once upon a time). The main difference: if it's in s7, it's a first-class citizen of s7, and that includes macros, environments, and syntactic values.

I originally used a small font for scholia, but now I have to squint to read that tiny text, so less-than-vital commentaries are shown in the normal font, but indented and on a sort of brownish background.

multiprecision arithmetic

All numeric types, integers, ratios, reals, and complex numbers are supported. The basic integer and real types are defined in s7.h, defaulting to int64_t and double. A ratio consists of two integers, a complex number two reals. pi is predefined. s7 can be built with multiprecision support for all types, using the gmp, mpfr, and mpc libraries (set WITH_GMP to 1 in s7.c). If multiprecision arithmetic is enabled, the following functions are included: bignum, and bignum?, and the variable (*s7* 'bignum-precision). (*s7* 'bignum-precision) defaults to 128; it sets the number of bits each float takes. pi automatically reflects the current (*s7* 'bignum-precision):

> pi 3.141592653589793238462643383279502884195E0 > (*s7* 'bignum-precision) 128 > (set! (*s7* 'bignum-precision) 256) 256 > pi 3.141592653589793238462643383279502884197169399375105820974944592307816406286198E0

bignum? returns #t if its argument is a big number of some type; I use "bignum" for any big number, not just integers. To create a big number, either include enough digits to overflow the default types, or use the bignum function. Its argument is either a number which it casts to a bignum, or a string representing the desired number:

> (bignum "123456789123456789") 123456789123456789 > (bignum "1.123123123123123123123123123") 1.12312312312312312312312312300000000009E0

For read-time bignums:

(set! *#readers* (cons (cons #\B (lambda (str) (bignum (string->number (substring str 1))))) *#readers*))

and now #B123 is the reader equivalent of (bignum 123).

In the non-gmp case, if s7 is built using doubles (s7_double in s7.h), the float "epsilon" is around (expt 2 -53), or about 1e-16. In the gmp case, it is around (expt 2 (- (*s7* 'bignum-precision))). So in the default case (precision = 128), using gmp: > (= 1.0 (+ 1.0 (expt 2.0 -128))) #t > (= 1.0 (+ 1.0 (expt 2.0 -127))) #f and in the non-gmp case: > (= 1.0 (+ 1.0 (expt 2 -53))) #t > (= 1.0 (+ 1.0 (expt 2 -52))) #f In the gmp case, integers and ratios are limited only by the size of memory, but reals are limited by (*s7* 'bignum-precision). This means, for example, that > (floor 1e56) ; (*s7* 'bignum-precision) is 128 99999999999999999999999999999999999999927942405962072064 > (set! (*s7* 'bignum-precision) 256) 256 > (floor 1e56) 100000000000000000000000000000000000000000000000000000000 The non-gmp case is similar, but it's easy to find the edge cases: > (floor (+ 0.9999999995 (expt 2.0 23))) 8388609

math functions

s7 includes:

sinh, cosh, tanh, asinh, acosh, atanh

logior, logxor, logand, lognot, logbit?, ash, integer-decode-float

random

nan?, infinite?

The random function can take any numeric argument, including 0. Other math-related differences between s7 and r5rs:

rational? and exact mean integer or ratio (i.e. not floating point), inexact means not exact.

floor, ceiling, truncate, and round return (exact) integer results.

"#" does not stand for an unknown digit.

the "@" complex number notation is not supported ("@" is an exponent marker in s7).

"+i" is not considered a number; include the real part.

modulo, remainder, and quotient take integer, ratio, or real arguments.

lcm and gcd can take integer or ratio arguments.

log takes an optional second argument, the base.

'.' and an exponent can occur in a number in any base.

rationalize returns a ratio!

case is significant in numbers, as elsewhere: #b0 is 0, but #B0 is an error.

> (exact? 1.0) #f > (rational? 1.5) #f > (floor 1.4) 1 > (remainder 2.4 1) 0.4 > (modulo 1.4 1.0) 0.4 > (lcm 3/4 1/6) 3/2 > (log 8 2) 3 > (number->string 0.5 2) "0.1" > (string->number "0.1" 2) 0.5 > (rationalize 1.5) 3/2 > (complex 1/2 0) 1/2 > (logbit? 6 1) ; argument order, (logbit? int index), follows gmp, not CL #t

See cload and libgsl.scm for easy access to GSL, and similarly libm.scm for the C math library.

The exponent itself is always in base 10; this follows gmp usage. Scheme normally uses "@" for its useless polar notation, but that means (string->number "1e1" 16) is ambiguous — is the "e" a digit or an exponent marker? In s7, "@" is an exponent marker. > (string->number "1e9" 2) ; (expt 2 9) 512.0 > (string->number "1e1" 12) ; "e" is not a digit in base 12 #f > (string->number "1e1" 16) ; (+ (* 1 16 16) (* 14 16) 1) 481 > (string->number "1.2e1" 3); (* 3 (+ 1 2/3)) 5.0 What is (/ 1.0 0.0) ? s7 gives a "division by zero" error here, and also in (/ 1 0) . Guile returns +inf.0 in the first case, which seems reasonable, but a "numerical overflow" error in the second. Slightly weirder is (expt 0.0 0+i) . Currently s7 returns 0.0, Guile returns +nan.0+nan.0i, Clisp and sbcl throw an error. Everybody agrees that (expt 0 0) is 1, and Guile thinks that (expt 0.0 0.0) is 1.0. But (expt 0 0.0) and (expt 0.0 0) return different results in Guile (1 and 1.0), both are 0.0 in s7, the first is an error in Clisp, but the second returns 1, and so on — what a mess! This mess was made a lot worse than it needs to be when the IEEE decreed that 0.0 equals -0.0, so we can't tell them apart, but that they produce different results in nearly every use! scheme@(guile-user)> (= -0.0 0.0) #t scheme@(guile-user)> (negative? -0.0) #f scheme@(guile-user)> (= (/ 1.0 0.0) (/ 1.0 -0.0)) #f scheme@(guile-user)> (< (/ 1.0 -0.0) -1e100 1e100 (/ 1.0 0.0)) #t How can they be equal? In s7, the sign of -0.0 is ignored, and they really are equal. One other oddity: two floats can satisfy eq? and yet not be eqv?: (eq? +nan.0 +nan.0) might be #t (it is unspecified), but (eqv? +nan.0 +nan.0) is #f. The same problem afflicts memq and assq. The random function takes a range and an optional state, and returns a number between zero and the range, of the same type as the range. It is perfectly reasonable to use a range of 0, in which case random returns 0. random-state creates a new random state from a seed. If no state is passed, random uses some default state initialized from the current time. random-state? returns #t if passed a random state object. > (random 0) 0 > (random 1.0) 0.86331198514245 > (random 3/4) 654/1129 > (random 1+i) 0.86300308872748+0.83601002730848i > (random -1.0) -0.037691127513267 > (define r0 (random-state 1234)) r0 > (random 100 r0) 94 > (random 100 r0) 19 > (define r1 (random-state 1234)) r1 > (random 100 r1) 94 > (random 100 r1) 19 copy the random-state to save a spot in a random number sequence, or save the random-state as a list via random-state->list, then to restart from that point, apply random-state to that list. I can't find the right tone for this section; this is the 400-th revision; I wish I were a better writer! In some Schemes, "rational" means "could possibly be expressed equally well as a ratio: floats are approximations". In s7 it's: "is actually expressed (at the scheme level) as a ratio (or an integer of course)"; otherwise "rational?" is the same as "real?": (not-s7)> (rational? (sqrt 2)) #t That 1.0 is represented at the IEEE-float level as a sort of ratio does not mean it has to be a scheme ratio; the two notions are independent. But that confusion is trivial compared to the completely nutty "inexact integer". As I understand it, "inexact" originally meant "floating point", and "exact" meant integer or ratio of integers. But words have a life of their own. 0.0 somehow became an "inexact" integer (although it can be represented exactly in floating point). +inf.0 must be an integer — its fractional part is explicitly zero! But +nan.0... And then there's: (not-s7)> (integer? 9007199254740993.1) #t When does this matter? I often need to index into a vector, but the index is a float (a "real" in Scheme-speak: its fractional part can be non-zero). In one Scheme: (not-s7)> (vector-ref #(0) (floor 0.1)) ERROR: Wrong type (expecting exact integer): 0.0 ; [why? "it's probably a programmer mistake"!] Not to worry, I'll use inexact->exact: (not-s7)> (inexact->exact 0.1) 3602879701896397/36028797018963968 ; [why? "floats are ratios"!] So I end up using the verbose (floor (inexact->exact ...)) everywhere, and even then I have no guarantee that I'll get a legal vector index. I have never seen any use made of the exact/inexact distinction — just wild flailing to try get around it. I think the whole idea is confused and useless, and leads to verbose and buggy code. If we discard it, we can maintain backwards compatibility via: (define exact? rational?) (define (inexact? x) (not (rational? x))) (define inexact->exact rationalize) ; or floor (define (exact->inexact x) (* x 1.0)) Standard Scheme's #i and #e are also useless because you can have any number after, for example, #b: > #b1.1 1.5 > #b1e2 4.0 > #o17.5+i 15.625+1i (But s7 uses #i for int-vector and does not implement #e). Speaking of #b and friends, what should (string->number "#xffff" 2) return?

define*, lambda*

define* and lambda* are extensions of define and lambda that make it easier to deal with optional, keyword, and rest arguments. The syntax is very simple: every argument to define* has a default value and is automatically available as a keyword argument. The default value is either #f if unspecified, or given in a list whose first member is the argument name. The last argument can be preceded by :rest or a dot to indicate that all other trailing arguments should be packaged as a list under that argument's name. A trailing or rest argument's default value is () and can't be specified in the declaration. The rest argument is not available as a keyword argument.

(define* (hi a (b 32) (c "hi")) (list a b c))

Here the argument "a" defaults to #f, "b" to 32, etc. When the function is called, the argument names are set from the values passed the function, then any unset arguments are bound to their default values, evaluated in left-to-right order. As the current argument list is scanned, any name that occurs as a keyword, :arg for example where the parameter name is arg, sets that argument's new value. Otherwise, as values occur, they are plugged into the actual argument list based on their position, counting a keyword/value pair as one argument. This is called an optional-key list in CLM. So, taking the function above as an example:

> (hi 1) (1 32 "hi") > (hi :b 2 :a 3) (3 2 "hi") > (hi 3 2 1) (3 2 1)

See s7test.scm for many examples. (s7's define* is very close to srfi-89's define*).

The combination of optional and keyword arguments is viewed with disfavor in the Lisp community, but the problem is in CL's implementation of the idea, not the idea itself. I've used the s7 style since around 1976, and have never found it confusing. The mistake in CL is to require the optional arguments if a keyword argument occurs, and to consider them as distinct from the keyword arguments. So everyone forgets and puts a keyword where CL expects a required-optional argument. CL then does something ridiculous, and the programmer stomps around shouting about keywords, but the fault lies with CL. If s7's way is considered too loose, one way to tighten it might be to insist that once a keyword is used, only keyword argument pairs can follow. A natural companion of lambda* is named let*. In named let, the implicit function's arguments have initial values, but thereafter, each call requires the full set of arguments. Why not treat the initial values as default values? > (let* func ((i 1) (j 2)) (+ i j (if (> i 0) (func (- i 1)) 0))) 5 > (letrec ((func (lambda* ((i 1) (j 2)) (+ i j (if (> i 0) (func (- i 1)) 0))))) (func)) 5 This is consistent with the lambda* arguments because their defaults are already set in left-to-right order, and as each parameter is set to its default value, the binding is added to the default value expression environment (just as if it were a let*). The let* name itself (the implicit function) is not defined until after the bindings have been evaluated (as in named let). In CL, keyword default values are handled in the same way: > (defun foo (&key (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c)) FOO > (foo :b 2 :a 60) (60 2 67) In s7, we'd use: (define* (foo (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c)) Also CL and s7 handle keywords as values in the same way: > (defun foo (&key a) a) FOO > (defvar x :a) X > (foo x 1) 1 > (define* (foo a) a) foo > (define x :a) :a > (foo x 1) 1 To try to catch what I believe are usually mistakes, I added two error checks. One is triggered if you set the same parameter twice in the same call, and the other if an unknown keyword is encountered in the key position. To turn off these errors, add :allow-other-keys at the end of the parameter list. These problems arise in a case such as (define* (f (a 1) (b 2)) (list a b)) You could do any of the following by accident: (f 1 :a 2) ; what is a? (f :b 1 2) ; what is b? (f :c 3) ; did you really want a to be :c and b to be 3? In the last case, to pass a keyword deliberately, either include the argument keyword: (f :a :c) , or make the default value a keyword: (define* (f (a :c) ...)) , or set (*s7* 'accept-all-keyword-arguments) to some true value. See s7test.scm for many examples. What if two functions share a keyword argument, and one wants to call the other, passing both arguments to the wrapper? (define* (f1 a) a) ; the wrappee (define* (f2 a :rest b :allow-other-keys) ; the wrapper (+ a (apply f1 b))) (f2 :a 3 :a 4) ; 7, b='(:a 4) (let ((c :a)) (f2 c 3 c 4)) ; also 7 Since named let* is a form of lambda*, the prohibition of repeated variable names makes it different from let*: (let* ((a 1) (a 2)) a) is 2, but (let* loop ((a 1) (a 2)) a) is an error. If let* and named let* agreed in this, we'd have an inconsistency with lambda*. If all three allowed repeated variables, the decision as to which parameter is intended becomes messy: ((lambda* (a a) a) 2 :a 3) , or (let* loop ((a 1) (a 2)) (loop 2 :a 3)) . CL and standard scheme accept repeated variables in let*, so I think the current choice is the least surprising. s7's lambda* arglist handling is not the same as CL's lambda-list. First, you can have more than one :rest parameter: > ((lambda* (:rest a :rest b) (map + a b)) 1 2 3 4 5) '(3 5 7 9) and second, the rest parameter, if any, takes up an argument slot just like any other argument: > ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 32) (32 1 ()) > ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 1 2 3 4 5) (1 3 (2 3 4 5)) CL would agree with the first case if we used &key for 'c', but would give an error in the second. Of course, the major difference is that s7 keyword arguments don't insist that the key be present. The :rest argument is needed in cases like these because we can't use an expression such as: > ((lambda* ((a 3) . b c) (list a b c)) 1 2 3 4 5) error: stray dot? > ((lambda* (a . (b 1)) b) 1 2) ; the reader turns the arglist into (a b 1) error: lambda* parameter '1 is a constant Yet another nit: the :rest argument is not considered a keyword argument, so > (define* (f :rest a) a) f > (f :a 1) (:a 1)

macros

define-macro, define-macro*, define-bacro, define-nacro*, macroexpand, gensym, gensym?, and macro? implement the standard old-time macros. The anonymous versions (analogous to lambda and lambda*) are macro, macro*, bacro, and bacro*. See s7test.scm for many examples of macros including such perennial favorites as loop, dotimes, do*, enum, pushnew, and defstruct.

> (define-macro (and-let* vars . body) `(let () (and ,@(map (lambda (v) `(define ,@v)) vars) (begin ,@body))))

macroexpand can help debug a macro. I always forget that it wants an expression:

> (define-macro (add-1 arg) `(+ 1 ,arg)) add-1 > (macroexpand (add-1 32)) (+ 1 32)

gensym returns a symbol that is guaranteed to be unused. It takes an optional string argument giving the new symbol name's prefix. gensym? returns #t if its argument is a symbol created by gensym.

(define-macro (pop! sym) (let ((v (gensym))) `(let ((,v (car ,sym))) (set! ,sym (cdr ,sym)) ,v)))

As in define*, the starred forms give optional and keyword arguments:

> (define-macro* (add-2 a (b 2)) `(+ ,a ,b)) add-2 > (add-2 1 3) 4 > (add-2 1) 3 > (add-2 :b 3 :a 1) 4

A macro is a first-class citizen of s7. You can pass it as a function argument, apply it to a list, return it from a function, call it recursively, and assign it to a variable. You can even set its setter! > (define-macro (hi a) `(+ ,a 1)) hi > (apply hi '(4)) 5 > (define (fmac mac) (apply mac '(4))) fmac > (fmac hi) 5 > (define (fmac mac) (mac 4)) fmac > (fmac hi) 5 > (define (make-mac) (define-macro (hi a) `(+ ,a 1))) make-mac > (let ((x (make-mac))) (x 2)) 3 > (define-macro (ref v i) `(vector-ref ,v ,i)) ref > (define-macro (set v i x) `(vector-set! ,v ,i ,x)) set > (set! (setter ref) set) set > (let ((v (vector 1 2 3))) (set! (ref v 0) 32) v) #(32 2 3) To expand all the macros in a piece of code: (define-macro (fully-macroexpand form) (list 'quote (let expand ((form form)) (cond ((not (pair? form)) form) ((and (symbol? (car form)) (macro? (symbol->value (car form)))) (expand (apply macroexpand (list form)))) ((and (eq? (car form) 'set!) ; look for (set! (mac ...) ...) and use mac's setter (pair? (cdr form)) (pair? (cadr form)) (macro? (symbol->value (caadr form)))) (expand (apply macroexpand (list (cons (setter (symbol->value (caadr form))) (append (cdadr form) (copy (cddr form)))))))) (else (cons (expand (car form)) (expand (cdr form)))))))) This does not always handle bacros correctly because their expansion can depend on the run-time state. A bacro is a macro that expands its body and evaluates the result in the calling environment. (define setf (let ((args (gensym)) (name (gensym))) (apply define-bacro `((,name . ,args) (unless (null? ,args) (apply set! (car ,args) (cadr ,args) ()) (apply setf (cddr ,args))))))) The setf argument is a gensym (created when setf is defined) so that its name does not shadow any existing variable. Bacros expand in the calling environment, and a normal argument name might shadow something in that environment while the bacro is being expanded. Similarly, if you introduce bindings in the bacro expansion code, you need to keep track of which environment you want things to happen in. Use with-let and gensym liberally. stuff.scm has bacro-shaker which can find inadvertent name collisions, but it is flighty and easily confused. The calling environment itself is (outlet (curlet)) from within a bacro, so (define-bacro (holler) `(format *stderr* "(~S~{ ~S ~S~^~})~%" (let ((f (*function*))) (if (pair? f) (car f) f)) (map (lambda (slot) (values (symbol->keyword (car slot)) (cdr slot))) (reverse (map values ,(outlet (curlet))))))) (define (f1 a b) (holler) (+ a b)) (f1 2 3) ; prints out "(f1 :a 2 :b 3)" and returns 5 Since a bacro (normally) sheds its define-time environment: (define call-bac (let ((x 2)) (define-bacro (m a) `(+ ,a ,x)))) > (call-bac 1) error: x: unbound variable A macro here returns 3. But don't be hasty! The bacro can get its define-time environment (its closure) via funclet, so in fact, define-macro is a special case of define-bacro! We can define macros that work in all four ways: the expansion can happen in either the definition or calling environment, as can the evaluation of that expansion. In a bacro, both happen in the calling environment if we take no other action, and in a normal macro (define-macro), the expansion happens in the definition environment, and the evaluation in the calling environment. Here's a brief example of all four: (let ((x 1) (y 2)) (define-bacro (bac1 a) `(+ ,x y ,a)) ; expand and eval in calling env (let ((x 32) (y 64)) (bac1 3))) ; (with-let (inlet 'x 32 'y 64) (+ 32 y 3)) -> 99 ; with-let and inlet refer to environments (let ((x 1) (y 2)) ; this is like define-macro (define-bacro (bac2 a) (with-let (sublet (funclet bac2) :a a) `(+ ,x y ,a))) ; expand in definition env, eval in calling env (let ((x 32) (y 64)) (bac2 3))) ; (with-let (inlet 'x 32 'y 64) (+ 1 y 3)) -> 68 (let ((x 1) (y 2)) (define-bacro (bac3 a) (let ((e (with-let (sublet (funclet bac3) :a a) `(+ ,x y ,a)))) `(with-let ,(sublet (funclet bac3) :a a) ,e))) ; expand and eval in definition env (let ((x 32) (y 64)) (bac3 3))) ; (with-let (inlet 'x 1 'y 2) (+ 1 y 3)) -> 6 (let ((x 1) (y 2)) (define-bacro (bac4 a) (let ((e `(+ ,x y ,a))) `(with-let ,(sublet (funclet bac4) :a a) ,e))) ; expand in calling env, eval in definition env (let ((x 32) (y 64)) (bac4 3))) ; (with-let (inlet 'x 1 'y 2) (+ 32 y 3)) -> 37 Backquote (quasiquote) in s7 is almost trivial. Constants are unchanged, symbols are quoted, ",arg" becomes "arg", and ",@arg" becomes "(apply values arg)" — hooray for real multiple values! It's almost as easy to write the actual macro body as the backquoted version of it. > (define-macro (hi a) `(+ 1 ,a)) hi > (procedure-source hi) (lambda (a) (list-values '+ 1 a)) > (define-macro (hi a) `(+ 1 ,@a)) hi > (procedure-source hi) (lambda (a) (list-values '+ 1 (apply-values a))) list-values and apply-values are quasiquote helper functions described below. There is no unquote-splicing macro in s7; ",@(...)" becomes "(unquote (apply-values ...))" at read-time. There shouldn't be any unquote either. In Scheme the reader turns ,x into (unquote x), so: > (let (,'a) unquote) a > (let (, (lambda (x) (+ x 1))) ,,,,'3) 7 comma becomes a sort of symbol macro! I think I'll remove unquote; ,x and ,@x will still work as expected, but there will not be any "unquote" or "unquote-splicing" in the resultant source code. Just to make life difficult: > (let (' 1) quote) 1 but that translation is so ingrained in lisp that I'm reluctant to change it. The two unquote names, on the other hand, seem unnecessary.

s7 macros are not hygienic. For example,

> (define-macro (mac b) `(let ((a 12)) (+ a ,b))) mac > (let ((a 1) (+ *)) (mac a)) 144

This returns 144 because '+' has turned into '*', and 'a' is the internal 'a', not the argument 'a'. We get (* 12 12) where we might have expected (+ 12 1) . Starting with the '+' problem, as long as the redefinition of '+' is local (that is, it happens after the macro definition), we can unquote the +:

> (define-macro (mac b) `(let ((a 12)) (,+ a ,b))) ; ,+ picks up the definition-time + mac > (let ((a 1) (+ *)) (mac a)) 24 ; (+ a a) where a is 12

But the unquote trick won't work if we have previously loaded some file that redefined '+' at the top-level (so at macro definition time, + is *, but we want the built-in +). Although this example is silly, the problem is real in Scheme because Scheme has no reserved words and only one name space.

> (define + *) + > (define (add a b) (+ a b)) add > (add 2 3) 6 > (define (divide a b) (/ a b)) divide > (divide 2 3) 2/3 > (set! / -) ; a bad idea — this turns off s7's optimizer - > (divide 2 3) -1

Obviously macros are not the problem here. Since we might be loading code written by others, it's sometimes hard to tell what names that code depends on or redefines. We need a way to get the pristine (start-up, built-in) value of '+'. One long-winded way in s7 uses unlet:

> (define + *) + > (define (add a b) (with-let (unlet) (+ a b))) add > (add 2 3) 5

But this is hard to read, and we might want all three values of a symbol, the start-up value, the definition-time value, and the current value. The latter can be accessed with the bare symbol, the definition-time value with unquote (','), and the start-up value with either unlet or #_<name>. That is, #_+ is a reader macro for (with-let (unlet) +) .

> (define-macro (mac b) `(#_let ((a 12)) (#_+ a ,b))) ; #_+ and #_let are start-up values mac > (let ((a 1) (+ *)) (mac a)) 24 ; (+ a a) where a is 12 and + is the start-up + ;;; make + generic (there's a similar C-based example below) > (define (+ . args) (if (null? args) 0 (apply (if (number? (car args)) #_+ #_string-append) args))) + > (+ 1 2) 3 > (+ "hi" "ho") "hiho"

Conceptually, #_<name> could be implemented via *#readers*: (set! *#readers* (cons (cons #\_ (lambda (str) (with-let (unlet) (string->symbol (substring str 1))))) *#readers*)) but s7 doesn't let you change the meaning of #\_; otherwise: (set! *#readers* (list (cons #\_ (lambda (str) (string->symbol (substring str 1)))))) and now #_ provides no protection: > (let ((+ -)) (#_+ 1 2)) -1 #t and #f (along with their stupid r7rs cousins #true and #false) are also not settable.

So, now we have only the variable capture problem ('a' has been captured in the preceding examples). This is the only thing that the gigantic "hygienic macro" systems actually deal with: a microscopic problem that you'd think, from the hype, was up there with malaria and the national debt. gensym is the standard approach:

> (define-macro (mac b) (let ((var (gensym))) `(#_let ((,var 12)) (#_+ ,var ,b)))) mac > (let ((a 1) (+ *)) (mac a)) 13 ;; or use lambda: > (define-macro (mac b) `((lambda (b) (let ((a 12)) (#_+ a b))) ,b)) mac > (let ((a 1) (+ *)) (mac a)) 13

I think syntax-rules and its friends try to conjure up gensyms automatically, but the real problem is not name collisions, but unspecified environments. In s7 we have first-class environments, so you have complete control over the environment at any point:

(define-macro (mac b) `(with-let (inlet 'b ,b) (let ((a 12)) (+ a b)))) > (let ((a 1) (+ *)) (mac a)) 13 (define-macro (mac1 . b) ; originally `(let ((a 12)) (+ a ,@b ,@b)) `(with-let (inlet 'e (curlet)) ; this 'e will not collide with the calling env (let ((a 12)) ; nor will 'a (so no gensyms are needed etc) (+ a (with-let e ,@b) (with-let e ,@b))))) > (let ((a 1) (e 2)) (mac1 (display a) (+ a e))) 18 ; (and it displays "11") (define-macro (mac2 x) ; this will use mac2's definition environment for its body `(with-let (sublet (funclet mac2) :x ,x) (let ((a 12)) (+ a b x)))) ; a is always 12, b is whatever b happens to be in mac2's env > (define b 10) ; this is mac2's b 10 > (let ((+ *) (a 1) (b 15)) (mac2 (+ a b))) 37 ; mac2 uses its own a (12), b (10), and + (+) ; but (+ a b) is 15 because at that point + is *: (* 1 15)

Hygienic macros are trivial! Who needs syntax-rules? To avoid the variable capture, avoid local variables in the generated code, or protect them via with-let; to avoid shadowing of functions and syntax, make the environment explicit (via #_ for example). s7's lint.scm will warn you about a problematic macro expansion, so I'd say just write macros as simply as possible, then let lint tell you that it's time to do the with-let shuffle. When that happens, wrap the macro body in a with-let that captures the current environment, and at each use of a macro argument wrap it in a with-let that re-establishes that environment.

(define-macro (swap a b) ; assume a and b are symbols `(with-let (inlet 'e (curlet) 'tmp ,a) (set! (e ',a) (e ',b)) (set! (e ',b) tmp))) > (let ((b 1) (tmp 2)) (swap b tmp) (list b tmp)) (2 1) (define-macro (swap a b) ; here a and b can be any settable expressions `(set! ,b (with-let (inlet 'e (curlet) 'tmp ,a) (with-let e (set! ,a ,b)) tmp))) > (let ((v (vector 1 2))) (swap (v 0) (v 1)) v) #(2 1) > (let ((tmp (cons 1 2))) (swap (car tmp) (cdr tmp)) tmp) (2 . 1) (set! (setter swap) (define-macro (set-swap a b c) `(set! ,b ,c))) > (let ((a 1) (b 2) (c 3) (d 4)) (swap a (swap b (swap c d))) (list a b c d)) (2 3 4 1) ;;; but this is simpler: (define-macro (rotate! . args) `(set! ,(args (- (length args) 1)) (with-let (inlet 'e (curlet) 'tmp ,(car args)) (with-let e ,@(map (lambda (a b) `(set! ,a ,b)) args (cdr args))) tmp))) > (let ((a 1) (b 2) (c 3)) (rotate! a b c) (list a b c)) (2 3 1)

If you want the macro's expanded result to be evaluated in its definition environment:

(let ((a 3)) (define-macro (mac b) `(with-let (inlet 'b ,b (funclet mac)) (+ a b))) ; definition-time "a", call-time "b" (define-macro (mac-1 b) `(+ a ,b)) ; call-time "a" and "b" (let ((a 32)) (list (mac 1) (mac-1 1))))

Here are some variations on "unless", inspired by the wikipedia hygienic macro page: (define-macro (my-unless condition . body) `(with-let (inlet (unlet) :condition ,condition) ; here unlet protects body (format below) (if (not condition) (begin ,@body)))) (let ((not (lambda (x) x)) (begin 32) (if +) (format abs)) (my-unless #t (format #t "This should not be printed!

")) (my-unless #f (format #t "This should be printed!

"))) (set! format abs) (let ((not (lambda (x) x))) (my-unless #t (format #t "This should not be printed!

")) (my-unless #f (format #t "This should be printed!

"))) (define (user-defined-operator x) (not x)) (define-macro (my-unless-1 condition . body) `(with-let (inlet (unlet) :condition ,condition) (if (user-defined-operator condition) (begin ,@body)))) (let ((user-defined-operator (lambda (x) x))) (my-unless-1 #t (format #t "This should not be printed!

")) (my-unless-1 #f (format #t "This should be printed!

"))) (define my-unless-2 (let ((op1 (lambda (x) (not x)))) (define-macro (_ condition . body) `(with-let (inlet (unlet) (funclet my-unless-2) :condition ,condition) ;; funclet above to get my-unless-2's version of op1 (if (op1 condition) (begin ,@body)))))) (let ((op1 (lambda (x) x))) (my-unless-2 #t (format #t "This should not be printed!

")) (my-unless-2 #f (format #t "This should be printed!

"))) (define my-unless-3 (let ((op1 (lambda (x) x))) (define-macro (_ condition . body) `(with-let (inlet (unlet) :condition ,condition :local-env (curlet)) ;; curlet to get run-time local version of op1 (if ((with-let local-env op1) condition) (begin ,@body)))))) (let ((op1 (lambda (x) (not x)))) (my-unless-3 #t (format #t "This should not be printed!

")) (my-unless-3 #f (format #t "This should be printed!

")))

On the subject of *#readers*, say we have: (set! *#readers* (list (cons #\o (lambda (str) 42)) ; #o... -> 42 (cons #\x (lambda (str) 3)))) ; #x... -> 3 Now we load a file with: (define (oct) #o123) (let-temporarily ((*#readers* ())) (eval (with-input-from-string "(define (hex) #x123)" read))) (define-constant old-readers *#readers*) (set! *#readers* ()) (define (oct1) #o123) (define (hex1) #x123) (set! *#readers* old-readers) (define (oct2) #o123) (define (hex2) #x123) Now we evaluate these functions, and get: (oct): 42 ; oct is not read-time hygienic so #o123 -> 42 (oct1): 83 ; oct1 is protected by the top-level set, #o123 -> 83 (oct2): 42 ; same as oct (hex): 291 ; hex is protected by let-temporarily + read (hex1): 291 ; hex1 is like oct1 (hex2): 3 ; hex2 is like oct

Here is Peter Seibel's wonderful once-only macro: (define-macro (once-only names . body) (let ((gensyms (map (lambda (n) (gensym)) names))) `(let (,@(map (lambda (g) (list g '(gensym))) gensyms)) `(let (,,@(map (lambda (g n) (list list g n)) gensyms names)) ,(let (,@(map list names gensyms)) ,@body))))) From the land of sparkling bacros: (define once-only (let ((names (gensym)) (body (gensym))) (apply define-bacro `((,(gensym) ,names . ,body) `(let (,@(map (lambda (name) `(,name ,(eval name))) ,names)) ,@,body))))) Sadly, with-let is simpler.

setter

(setter proc) (dilambda proc setter)

There are several kinds of setters, reflecting the many ways that set! can be called. First are the symbol setters:

> (let ((x 1)) (set! (setter 'x) (lambda (name new-value) (* new-value 2))) (set! x 2) x) 4

Here the setter is a function that is called before the variable is set. It can take two or three arguments. In the two argument case shown above, the first is the variable name (a symbol), and the second is the new-value. The variable is set to the value returned by the setter function. When s7 sees (set! x 2) above, it calls the setter which returns 4. So x is set to 4.

In some cases you need the environment that the variable lives in (to get its current value for example), so you can include that in the setter function parameter list:

> (let ((x 1)) (set! (setter 'x) (lambda (name new-value enviroment) (* new-value 2))) (set! x 2) x) 4 (define-macro (watch var) ; notification if 'var is set! `(set! (setter ',var) (lambda (s v e) (format *stderr* "~S set! to ~S~A~%" s v (let ((func (with-let e (*function*)))) (if (eq? func #<undefined>) "" (format #f ", ~S" func)))) v)))

Since symbol setters are often implementing type restrictions, you can use the built-in type checking functions such as integer? as a short-hand for a setter that insists the new value be an integer:

> (let ((x 1)) (set! (setter 'x) integer?) (set! x 3.14)) error: set! x: 3.14, is a real but should be an integer ;;; use typed-let from stuff.scm to do the same thing: > (typed-let ((x 3 integer?)) (set! x 3.14)) error: set! x: 3.14, is a real but should be an integer

C-side symbol setters go through s7_set_setter. There is an example below.

The second case is a function setter. Almost any function or macro can have an associated setter that is invoked when the function is the target of set!. In this case, the setter function does the set! itself (unlike a symbol setter):

> (setter cadr) #f ; by default cadr has no setter so (set! (cadr p) x) is an error > (set! (setter cadr) ; add a setter to cadr (lambda (lst val) (set! (car (cdr lst)) val))) #<lambda (lst val)> > (procedure-source (setter cadr)) (lambda (lst val) (set! (car (cdr lst)) val)) > (let ((lst (list 1 2 3))) (set! (cadr lst) 4) lst) (1 4 3)

In some cases, the setter needs to be a macro:

> (set! (setter logbit?) (define-macro (m var index on) ; here we want to set "var", so we need a macro `(if ,on (set! ,var (logior ,var (ash 1 ,index))) (set! ,var (logand ,var (lognot (ash 1 ,index))))))) m > (define (mingle a b) (let ((r 0)) (do ((i 0 (+ i 1))) ((= i 31) r) (set! (logbit? r (* 2 i)) (logbit? a i)) (set! (logbit? r (+ (* 2 i) 1)) (logbit? b i))))) mingle > (mingle 6 3) ; the INTERCAL mingle operator? 30

dilambda defines a function and its setter without having to set! the setter by hand:

> (define f (let ((x 123)) (dilambda (lambda () x) (lambda (new-value) (set! x new-value))))) f > (f) 123 ; x = 123 > (set! (f) 32) 32 ; now x = 32 > (f) 32

Here is a pretty example of dilambda: (define-macro (c?r path) ;; "path" is a list and "X" marks the spot in it that we are trying to access ;; (a (b ((c X)))) — anything after the X is ignored, other symbols are just placeholders ;; c?r returns a dilambda that gets/sets X (define (X-marks-the-spot accessor tree) (if (pair? tree) (or (X-marks-the-spot (cons 'car accessor) (car tree)) (X-marks-the-spot (cons 'cdr accessor) (cdr tree))) (and (eq? tree 'X) accessor))) (let ((body 'lst)) (for-each (lambda (f) (set! body (list f body))) (reverse (X-marks-the-spot () path))) `(dilambda (lambda (lst) ,body) (lambda (lst val) (set! ,body val))))) > ((c?r (a b (X))) '(1 2 (3 4) 5)) 3 > (let ((lst (list 1 2 (list 3 4) 5))) (set! ((c?r (a b (X))) lst) 32) lst) (1 2 (32 4) 5) > (procedure-source (c?r (a b (X)))) (lambda (lst) (car (car (cdr (cdr lst))))) > ((c?r (a b . X)) '(1 2 (3 4) 5)) ((3 4) 5) > (let ((lst (list 1 2 (list 3 4) 5))) (set! ((c?r (a b . X)) lst) '(32)) lst) (1 2 32) > (procedure-source (c?r (a b . X))) (lambda (lst) (cdr (cdr lst))) > ((c?r (((((a (b (c (d (e X)))))))))) '(((((1 (2 (3 (4 (5 6)))))))))) 6 > (let ((lst '(((((1 (2 (3 (4 (5 6))))))))))) (set! ((c?r (((((a (b (c (d (e X)))))))))) lst) 32) lst) (((((1 (2 (3 (4 (5 32))))))))) > (procedure-source (c?r (((((a (b (c (d (e X))))))))))) (lambda (lst) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (car (car (car lst)))))))))))))))

I may remove dilambda and dilambda? someday; they are trivial:

(define (dilambda get set) (set! (setter get) set) get) (define dilambda? setter)

When a function setter is called, (set! (func ...) val) is evaluated by s7 as ((setter func) ... val) , so the setter function needs to handle both the inner arguments to the function and the new value.

(let ((x 123)) (define (f a b) (+ x a b)) (set! (setter f) (lambda (a b val) (set! x val))) (display (f 1 2)) (newline) ; "126" (set! (f 1 2) 32) (display (f 1 2)) (newline)) ; "35"

A third type of setter handles vector element type and hash-table key and value types. These are described under typed vectors and typed hash-tables.

Speaking of INTERCAL, COME-FROM: (define-macro (define-with-goto-and-come-from name-and-args . body) (let ((labels ()) (gotos ()) (come-froms ())) (let collect-jumps ((tree body)) (when (pair? tree) (when (pair? (car tree)) (case (caar tree) ((label) (set! labels (cons tree labels))) ((goto) (set! gotos (cons tree gotos))) ((come-from) (set! come-froms (cons tree come-froms))) (else (collect-jumps (car tree))))) (collect-jumps (cdr tree)))) (for-each (lambda (goto) (let* ((name (cadr (cadar goto))) (label (member name labels (lambda (a b) (eq? a (cadr (cadar b))))))) (if label (set-cdr! goto (car label)) (error 'bad-goto "can't find label: ~S" name)))) gotos) (for-each (lambda (from) (let* ((name (cadr (cadar from))) (label (member name labels (lambda (a b) (eq? a (cadr (cadar b))))))) (if label (set-cdr! (car label) from) (error 'bad-come-from "can't find label: ~S" name)))) come-froms) `(define ,name-and-args (let ((label (lambda (name) #f)) (goto (lambda (name) #f)) (come-from (lambda (name) #f))) ,@body))))

applicable objects, generalized set!, generic functions

A procedure with a setter can be viewed as one generalization of set!. Another treats objects as having predefined get and set functions. In s7 lists, strings, vectors, hash-tables, environments, and any cooperating C or Scheme-defined objects are both applicable and settable. newLisp calls this implicit indexing, Kawa has it, Gauche implements it via object-apply, Guile via procedure-with-setter; CL's funcallable instance might be the same idea.

In (vector-ref #(1 2) 0) , for example, vector-ref is just a type declaration. But in Scheme, type declarations are unnecessary, so we get exactly the same result from (#(1 2) 0) . Similarly, (lst 1) is the same as (list-ref lst 1) , and (set! (lst 1) 2) is the same as (list-set! lst 1 2) . I like this syntax: the less noise, the better!

Well, maybe applicable strings look weird: ("hi" 1) is #\i, but worse, so is (cond (1 => "hi")) ! Even though a string, list, or vector is "applicable", it is not currently considered to be a procedure, so (procedure? "hi") is #f. map and for-each, however, accept anything that apply can handle, so (map #(0 1) '(1 0)) is '(1 0). (On the first call to map in this case, you get the result of (#(0 1) 1) and so on). string->list, vector->list, and let->list are (map values object) . Their inverses are (and always have been) equally trivial. The applicable object syntax makes it easy to write generic functions. For example, s7test.scm has implementations of Common Lisp's sequence functions. length, copy, reverse, fill!, iterate, map and for-each are generic in this sense (map always returns a list). > (map (lambda (a b) (- a b)) (list 1 2) (vector 3 4)) (5 -3 9) > (length "hi") 2 Here's a generic FFT: (define* (cfft data n (dir 1)) ; complex data (unless n (set! n (length data))) (do ((i 0 (+ i 1)) (j 0)) ((= i n)) (if (> j i) (let ((temp (data j))) (set! (data j) (data i)) (set! (data i) temp))) (do ((m (/ n 2) (/ m 2))) ((or (< m 2) (< j m)) (set! j (+ j m))) (set! j (- j m)))) (do ((ipow (floor (log n 2))) (prev 1) (lg 0 (+ lg 1)) (mmax 2 (* mmax 2)) (pow (/ n 2) (/ pow 2)) (theta (complex 0.0 (* pi dir)) (* theta 0.5))) ((= lg ipow)) (do ((wpc (exp theta)) (wc 1.0) (ii 0 (+ ii 1))) ((= ii prev) (set! prev mmax)) (do ((jj 0 (+ jj 1)) (i ii (+ i mmax)) (j (+ ii prev) (+ j mmax))) ((>= jj pow)) (let ((tc (* wc (data j)))) (set! (data j) (- (data i) tc)) (set! (data i) (+ (data i) tc)))) (set! wc (* wc wpc)))) data) > (cfft (list 0.0 1+i 0.0 0.0)) (1+1i -1+1i -1-1i 1-1i) > (cfft (vector 0.0 1+i 0.0 0.0)) #(1+1i -1+1i -1-1i 1-1i) And a generic function that copies one sequence's elements into another sequence: (define (copy-into source dest) ; this is equivalent to (copy source dest) (do ((i 0 (+ i 1))) ((= i (min (length source) (length dest))) dest) (set! (dest i) (source i)))) but that is already built-in as the two-argument version of the copy function. There is one place where list-set! and friends are not the same as set!: the former evaluate their first argument, but set! does not (with a quibble; see below): > (let ((str "hi")) (string-set! (let () str) 1 #\a) str) "ha" > (let ((str "hi")) (set! (let () str) 1 #\a) str) ;((let () str) 1 #\a): too many arguments to set! > (let ((str "hi")) (set! ((let () str) 1) #\a) str) "ha" > (let ((str "hi")) (set! (str 1) #\a) str) "ha" set! looks at its first argument to decide what to set. If it's a symbol, no problem. If it's a pair, set! looks at its car to see if it is some object that has a setter. If the car is itself a list, set! evaluates the internal expression, and tries again. So the second case above is the only one that won't work. And of course: > (let ((x (list 1 2))) (set! ((((lambda () (list x))) 0) 0) 3) x) (3 2) By my count, around 20 of the Scheme built-in functions are already generic in the sense that they accept arguments of many types (leaving aside the numeric and type checking functions, take for example equal?, display, member, assoc, apply, eval, quasiquote, and values). s7 extends that list with map, for-each, reverse, and length, and adds a few others such as copy, fill!, sort!, object->string, object->let, and append. newLisp takes a more radical approach than s7: it extends operators such as '>' to compare strings and lists, as well as numbers. In map and for-each, however, you can mix the argument types, so I'm not as attracted to making '>' generic; you can't, for example, (> "hi" 32.1) , or even (> 1 0+i) .

The somewhat non-standard generic sequence functions in s7 are:

(sort! sequence less?) (reverse! sequence) and (reverse sequence) (fill! sequence value (start 0) end) (copy obj) and (copy source destination (start 0) end) (object->string obj) (object->let obj) (length obj) (append . sequences) (map func . sequences) and (for-each func . sequences) (equivalent? obj1 obj2)

copy returns a (shallow) copy of its argument. If a destination is provided, it need not match the source in size or type. The start and end indices refer to the source.

> (copy '(1 2 3 4) (make-list 2)) (1 2) > (copy #(1 2 3 4) (make-list 5) 1) ; start at 1 in the source (2 3 4 #f #f) > (copy "1234" (make-vector 2)) #(#\1 #\2) > (define lst (list 1 2 3 4 5)) (1 2 3 4 5) > (copy #(8 9) (cddr lst)) (8 9 5) > lst (1 2 8 9 5)

reverse! is an in-place version of reverse. That is, it modifies the sequence passed to it in the process of reversing its contents. If the sequence is a list, remember to use set!: (set! p (reverse! p)) . This is somewhat inconsistent with other cases, but historically, lisp programmers have treated the in-place reverse as the fast version, so s7 follows suit.

> (define lst (list 1 2 3)) (1 2 3) > (reverse! lst) (3 2 1) > lst (1)

Leaving aside the weird list case, append returns a sequence of the same type as its first argument.

> (append #(1 2) '(3 4)) #(1 2 3 4) > (append (float-vector) '(1 2) (byte-vector 3 4)) (float-vector 1.0 2.0 3.0 4.0)

sort! sorts a sequence using the function passed as its second argument:

> (sort! (list 3 4 8 2 0 1 5 9 7 6) <) (0 1 2 3 4 5 6 7 8 9)

Underlying some of these functions are generic iterators, also built-into s7:

(make-iterator sequence) (iterator? obj) (iterate iterator) (iterator-sequence iterator) (iterator-at-end? iterator)

make-iterator takes a sequence argument and returns an iterator object that traverses that sequence as it is called. The iterator itself can be treated as a function of no arguments, or (for code clarity) it can be the argument to iterate, which does the same thing. That is (iter) is the same as (iterate iter) . The sequence that an iterator is traversing is iterator-sequence.

If the sequence is a hash-table or let, the iterator normally returns a cons of the key and value. There are many cases where this overhead is objectionable, so make-iterator takes a third optional argument, the cons to use (changing its car and cdr directly on each call).

When an iterator reaches the end of its sequence, it returns #<eof>. It used to return nil; I can't decide whether this change is an improvement. If an iterator over a list notices that its list is circular, it returns #<eof>. map and for-each use iterators, so if you pass a circular list to either, it will stop eventually. (An arcane consequence for method writers: specialize make-iterator, not map or for-each).

(define (find-if f sequence) (let ((iter (make-iterator sequence))) (do ((x (iter) (iter))) ((or (eof-object? x) (f x)) (and (not (eof-object? x)) x)))))

But of course a sequence might contain #<eof>! So to be really safe, use iterator-at-end? instead of eof-object?.

The argument to make-iterator can also be a function or macro. There should be a variable named '+iterator+ with a non-#f value in the closure's environment:

(define (make-circular-iterator obj) (let ((iter (make-iterator obj))) (make-iterator (let ((+iterator+ #t)) (lambda () (case (iter) ((#<eof>) ((set! iter (make-iterator obj)))) (else)))))))

The 'iterator? variable is similar to the '+documentation+ variable used by documentation. It gives make-iterator some hope of catching inadvertent bogus function arguments that would otherwise cause an infinite loop.

multidimensional vectors

s7 supports vectors with any number of dimensions. It is here, in particular, that generalized set! shines. make-vector's second argument can be a list of dimensions, rather than an integer as in the one dimensional case:

(make-vector (list 2 3 4)) (make-vector '(2 3) 1.0) (vector-dimensions (make-vector '(2 3 4))) -> (2 3 4)

The second example includes the optional initial element. (vect i ...) or (vector-ref vect i ...) return the given element, and (set! (vect i ...) value) and (vector-set! vect i ... value) set it. vector-length (or just length) returns the total number of elements. vector-dimensions returns a list of the dimensions.

> (define v (make-vector '(2 3) 1.0)) #2d((1.0 1.0 1.0) (1.0 1.0 1.0)) > (set! (v 0 1) 2.0) #2d((1.0 2.0 1.0) (1.0 1.0 1.0)) > (v 0 1) 2.0 > (vector-length v) 6

This function initializes each element of a multidimensional vector:

(define (make-array dims . inits) (subvector (apply vector (flatten inits)) 0 (apply * dims) dims)) > (make-array '(3 3) '(1 1 1) '(2 2 2) '(3 3 3)) #2d((1 1 1) (2 2 2) (3 3 3))

make-int-vector, make-float-vector, and make-byte-vector produce homogeneous vectors holding s7_ints, s7_doubles, or unsigned bytes.

(make-vector length-or-list-of-dimensions initial-value element-type-function) (float-vector? obj) (float-vector . args) (make-float-vector len (init 0.0)) (float-vector-ref obj . indices) (float-vector-set! obj indices[...] value) (int-vector? obj) (int-vector . args) (make-int-vector len (init 0)) (int-vector-ref obj . indices) (int-vector-set! obj indices[...] value) (byte-vector? obj) (byte-vector . args) (make-byte-vector len (init 0)) (byte-vector-ref obj . indices) (byte-vector-set! obj indices[...] byte) (byte? obj) (string->byte-vector str) (byte-vector->string str) (subvector vector start end dimensions) (subvector? obj) (subvector-vector obj) (subvector-position obj)

In addition to the dimension list mentioned above, make-vector accepts optional arguments giving the initial element and the element type. If the type is given, every attempt to set an element of the vector first calls the type function on the new value. If the type function is omitted (or set to #t), no type checking is performed. If the type function is a closure (rather than a C-defined or built-in function), its name must be accessible; it can't be an anonymous lambda (the signature and error handlers need this name).

> (define v (make-vector 3 'x symbol?)) ; initial element: 'x, elements must be symbols #(x x x) > (vector-set! v 0 123) error: vector-set! argument 3, 123, is an integer but should be a symbol? > (define (10|12? val) (memv val '(10 12))) 10|12? > (define v1 (make-vector 3 10 10|12?)) ; only allow values 10 or 12 (initially 10) #(10 10 10) > (set! (v1 0) 12) 12 > v1 #(12 10 10) > (set! (v1 1) 32) error: vector-set! argument 3, 32, is an integer but should be a 10|12?

To access a vector's elements with different dimensions than the original had, use (subvector original-vector 0 (length original-vector) new-dimensions) :

> (let ((v1 #2d((1 2 3) (4 5 6)))) (let ((v2 (subvector v1))) ; flatten the original (1D is the default) v2)) #(1 2 3 4 5 6) > (let ((v1 #(1 2 3 4 5 6))) (let ((v2 (subvector v1 0 6 '(3 2)))) v2)) #2d((1 2) (3 4) (5 6))

A subvector is a window onto some other vector's data. The data is not copied, just accessed differently. The new-dimensions parameter is a list giving the lengths of the dimensions. The start and end parameters refer to positions in the original vector. subvector-vector returns the underlying vector, and subvector-position returns the starting point of the subvector in the underlying data.

subvector's parameter list changed 8-Jul-2020. It was (subvector vect new-length-or-dimension-list start) , but that conflicts with substring, and is confusing (the start position follows the length). To translate from the old subvector to the new: (define (old-subvector vect len (offset 0)) (if (pair? len) (subvector vect offset (+ offset (apply * len)) len) (if (not len) (subvector vect offset (length vect)) (subvector vect offset (+ offset len)))))

matrix multiplication: (define (matrix-multiply A B) ;; assume square matrices and so on for simplicity (let ((size (car (vector-dimensions A)))) (do ((C (make-vector (list size size) 0)) (i 0 (+ i 1))) ((= i size) C) (do ((j 0 (+ j 1))) ((= j size)) (do ((sum 0) (k 0 (+ k 1))) ((= k size) (set! (C i j) sum)) (set! sum (+ sum (* (A i k) (B k j))))))))) Conway's game of Life: (define* (life (width 40) (height 40)) (let ((state0 (make-vector (list width height) 0)) (state1 (make-vector (list width height) 0))) ;; initialize with some random pattern (do ((x 0 (+ x 1))) ((= x width)) (do ((y 0 (+ y 1))) ((= y height)) (set! (state0 x y) (if (< (random 100) 15) 1 0)))) (do () () ;; show current state (using terminal escape sequences, borrowed from the Rosetta C code) (format *stderr* "~C[H" #\escape) ; ESC H = tab set (do ((y 0 (+ y 1))) ((= y height)) (do ((x 0 (+ x 1))) ((= x width)) (format *stderr* (if (zero? (state0 x y)) " " ; ESC 07m below = inverse (values "~C[07m ~C[m" #\escape #\escape)))) (format *stderr* "~C[E" #\escape)) ; ESC E = next line ;; get the next state (do ((x 1 (+ x 1))) ((= x (- width 1))) (do ((y 1 (+ y 1))) ((= y (- height 1))) (let ((n (+ (state0 (- x 1) (- y 1)) (state0 x (- y 1)) (state0 (+ x 1) (- y 1)) (state0 (- x 1) y) (state0 (+ x 1) y) (state0 (- x 1) (+ y 1)) (state0 x (+ y 1)) (state0 (+ x 1) (+ y 1))))) (set! (state1 x y) (if (or (= n 3) (and (= n 2) (not (zero? (state0 x y))))) 1 0))))) (copy state1 state0)))) Multidimensional vector constant syntax is modelled after CL: #nd(...) signals that the lists specify the elements of an 'n' dimensional vector: #2d((1 2 3) (4 5 6)) int-vector constants use #i, float-vectors use #r. I wanted to use #f, but that is already taken. Append the "nd" business after the type indication: #i2d((1 2) (3 4)) . This syntax collides with the r7rs byte-vector notation "#u8"; s7 uses "#u" for byte-vectors. "#u2d(...)" is a two-dimensional byte-vector. For backwards compatibility, you can use "#u8" for one-dimensional byte-vectors. > (vector-ref #2d((1 2 3) (4 5 6)) 1 2) 6 > (matrix-multiply #2d((-1 0) (0 -1)) #2d((2 0) (-2 2))) #2d((-2 0) (2 -2)) > (int-vector 1 2 3) #i(1 2 3) > (make-float-vector '(2 3) 1.0) #r2d((1.0 1.0 1.0) (1.0 1.0 1.0)) > (vector (vector 1 2) (int-vector 1 2) (float-vector 1 2)) #(#(1 2) #i(1 2) #r(1.0 2.0)) If any dimension has 0 length, you get an n-dimensional empty vector. It is not equal to a 1-dimensional empty vector. > (make-vector '(10 0 3)) #3d() > (equal? #() #3d()) #f To save on costly parentheses, and make it easier to write generic multidimensional sequence functions, you can use this same syntax with lists. > (let ((L '((1 2 3) (4 5 6)))) (L 1 0)) ; same as (list-ref (list-ref L 1) 0) or ((L 1) 0) 4 > (let ((L '(((1 2 3) (4 5 6)) ((7 8 9) (10 11 12))))) (set! (L 1 0 2) 32) ; same as (list-set! (list-ref (list-ref L 1) 0) 2 32) which is unreadable! L) (((1 2 3) (4 5 6)) ((7 8 32) (10 11 12))) Or with vectors of vectors, of course: > (let ((V #(#(1 2 3) #(4 5 6)))) (V 1 2)) ; same as (vector-ref (vector-ref V 1) 2) or ((V 1) 2) 6 > (let ((V #2d((1 2 3) (4 5 6)))) (V 0)) #(1 2 3) There's one difference between a vector-of-vectors and a multidimensional vector: in the latter case, you can't clobber one of the inner vectors. > (let ((V #(#(1 2 3) #(4 5 6)))) (set! (V 1) 32) V) #(#(1 2 3) 32) > (let ((V #2d((1 2 3) (4 5 6)))) (set! (V 1) 32) V) ;not enough args for vector-set!: (#2d((1 2 3) (4 5 6)) 1 32) Using lists to display the inner vectors may not be optimal, especially when the elements are also lists: #2d(((0) (0) ((0))) ((0) 0 ((0)))) The "#()" notation is no better (the elements can be vectors), and I'm not a fan of "[]" parentheses. Perhaps we could use different colors? Or different size parentheses? #2D(((0) (0) ((0))) ((0) 0 ((0)))) #2D(((0) (0) ((0))) ((0) 0 ((0)))) I'm not sure how to handle vector->list and list->vector in the multidimensional case. Currently, vector->list flattens the vector, and list->vector always returns a one dimensional vector, so the two are not inverses. > (vector->list #2d((1 2) (3 4))) (1 2 3 4) ; should this be '((1 2) (3 4)) or '(#(1 2) #(3 4))? > (list->vector '(#(1 2) #(3 4))) ; what about '((1 2) (3 4))? #(#(1 2) #(3 4)) This also affects format and sort!: > (format #f "~{~A~^ ~}" #2d((1 2) (3 4))) "1 2 3 4" > (sort! #2d((1 4) (3 2)) >) #2d((4 3) (2 1)) Perhaps subvector can help: >(subvector (list->vector '(1 2 3 4)) 0 4 '(2 2)) #2d((1 2) (3 4)) > (let ((a #2d((1 2) (3 4))) (b #2d((5 6) (7 8)))) (list (subvector (append a b) 0 8 '(2 4)) (subvector (append a b) 0 8 '(4 2)) (subvector (append (a 0) (b 0) (a 1) (b 1)) 0 8 '(2 4)) (subvector (append (a 0) (b 0) (a 1) (b 1)) 0 8 '(4 2)))) (#2d((1 2 3 4) (5 6 7 8)) #2d((1 2) (3 4) (5 6) (7 8)) #2d((1 2 5 6) (3 4 7 8)) #2d((1 2) (5 6) (3 4) (7 8))) Another question: should we accept the multi-index syntax in a case such as (#("abc" "def") 0 2) ? My first thought was that the indices should all refer to the same type of object, so s7 would complain in a mixed case like that. If we can nest any applicable objects and apply the whole thing to an arbitrary list of indices, ambiguities arise: ((lambda (x) x) "hi" 0) ((lambda (x) (lambda (y) (+ x y))) 1 2) I think these should complain that the function got too many arguments, but from the implicit indexing point of view, they could be interpreted as: (string-ref ((lambda (x) x) "hi") 0) ; i.e. (((lambda (x) x) "hi") 0) (((lambda (x) (lambda (y) (+ x y))) 1) 2) Add optional and rest arguments, and you can't tell who is supposed to take which arguments. Currently, you can mix types with implicit indices, but a function grabs all remaining indices. To insist that all objects are of the same type, use an explicit getter: > (list-ref (list 1 (list 2 3)) 1 0) ; same as ((list 1 (list 2 3)) 1 0) 2 > ((list 1 (vector 2 3)) 1 0) 2 > (list-ref (list 1 (vector 2 3)) 1 0) error: list-ref argument 1, #(2 3), is a vector but should be a proper list

hash-tables

(make-hash-table (size 8) eq-func typers)

(make-weak-hash-table (size 8) eq-func typers)

(hash-table ...)

(weak-hash-table ...)

(hash-table? obj)

(weak-hash-table? obj)

(hash-table-ref ht key)

(hash-table-set! ht key value)

(hash-table-entries ht)

Each hash-table keeps track of the keys it contains, optimizing the search wherever possible. Any s7 object can be the key or the key's value. If you pass a table size that is not a power of 2, make-hash-table rounds it up to the next power of 2. The table grows as needed. length returns the current size. If a key is not in the table, hash-table-ref returns #f. To remove a key, set its value to #f; to remove all keys, (fill! table #f) .

> (let ((ht (make-hash-table))) (set! (ht "hi") 123) (ht "hi")) 123

hash-table (the function) parallels the functions vector, list, and string. Its arguments are the keys and values: (hash-table 'a 1 'b 2) . Implicit indexing gives multilevel hashes:

> (let ((h (hash-table 'a (hash-table 'b 2 'c 3)))) (h 'a 'b)) 2 > (let ((h (hash-table 'a (hash-table 'b 2 'c 3)))) (set! (h 'a 'b) 4) (h 'a 'b)) 4

Since hash-tables accept the same applicable-object syntax that vectors use, we can treat a hash-table as, for example, a sparse array: > (define make-sparse-array make-hash-table) make-sparse-array > (let ((arr (make-sparse-array))) (set! (arr 1032) "1032") (set! (arr -23) "-23") (list (arr 1032) (arr -23))) ("1032" "-23") map and for-each accept hash-table arguments. On each iteration, the map or for-each function is passed an entry, '(key . value) , in whatever order the entries are encountered in the table. (define (hash-table->alist table) (map values table)) reverse of a hash-table returns a new table with the keys and values reversed. fill! sets all the values. Two hash-tables are equal if they have the same keys with the same values. This is independent of the table sizes, or the order in which the key/value pairs were added. The second argument to make-hash-table (eq-func) is slightly complicated. If it is omitted, s7 chooses the hashing equality and mapping functions based on the keys in the hash-table. There are times when you know in advance what equality function you want. If it's one of the built-in s7 equality functions, eq?, eqv?, equal?, equivalent?, =, string=?, string-ci=?, char=?, or char-ci=?, you can pass that function as the second argument. In any other case, you need to give s7 both the equality function and the mapping function. The latter takes any object and returns the hash-table location for it (an integer). The problem here is that for the arbitrary equality function to work, objects that are equal according to that function have to be mapped to the same hash-table location. There's no way for s7 to intuit what this mapping should be except in the built-in cases. So to specify some arbitrary function, the second argument is a cons: '(equality-checker mapper). Here's a brief example. In CLM, we have c-objects of type mus-generator (from s7's point of view), and we want to hash them using equal? (which will call the generator-specific equality function). But s7 doesn't realize that the mus-generator type covers 40 or 50 internal types, so as the mapper we pass mus-type: (make-hash-table 64 (cons equal? mus-type)) . If the hash key is a float (a non-rational number), hash-table-ref uses equivalent?. Otherwise, for example, you could use NaN as a key, but then never be able to access it! To implement read-time hash-tables using #h(...): (set! *#readers* (cons (cons #\h (lambda (str) (and (string=? str "h") ; #h(...) (apply hash-table (read))))) *#readers*)) (display #h(:a 1)) (newline) (display #h(:a 1 :b "str")) (newline) These can be made immutable by (immutable! (apply...)) , or even better, (let ((h (apply hash-table (read)))) (if (> (*s7* 'safety) 1) (immutable! h) h)) (define-macro (define-memoized name&arg . body) (let ((arg (cadr name&arg)) (memo (gensym "memo"))) `(define ,(car name&arg) (let ((,memo (make-hash-table))) (lambda (,arg) (or (,memo ,arg) ; check for saved value (set! (,memo ,arg) (begin ,@body)))))))) ; set! returns the new value > (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) fib > (define-memoized (memo-fib n) (if (< n 2) n (+ (memo-fib (- n 1)) (memo-fib (- n 2))))) memo-fib > (time (fib 34)) ; un-memoized time 1.168 ; 0.70 on ccrma's i7-3930 machines > (time (memo-fib 34)) ; memoized time 3.200e-05 > (outlet (funclet memo-fib)) (inlet '{memo}-18 (hash-table '(0 . 0) '(1 . 1) '(2 . 1) '(3 . 2) '(4 . 3) '(5 . 5) '(6 . 8) '(7 . 13) '(8 . 21) '(9 . 34) '(10 . 55) '(11 . 89) '(12 . 144) '(13 . 233) '(14 . 377) '(15 . 610) '(16 . 987) '(17 . 1597) '(18 . 2584) '(19 . 4181) '(20 . 6765) '(21 . 10946) '(22 . 17711) '(23 . 28657) '(24 . 46368) '(25 . 75025) '(26 . 121393) '(27 . 196418) '(28 . 317811) '(29 . 514229) '(30 . 832040) '(31 . 1346269) '(32 . 2178309) '(33 . 3524578) '(34 . 5702887))) but the tail recursive version of fib is simpler and almost as fast as the memoized version, and the iterative version beats both. The third argument, typers, sets type checkers for the keys and values in the table, much like the third argument to make-vector. It is a cons of the type functions, (cons symbol? integer?) for example. This says that all the keys must be symbols and all the values integers. > (define (10|12? val) (memv val '(10 12))) 10|12? > (define hash (make-hash-table 8 #f (cons #t 10|12?))) ; any key is ok, but all values must be 10 or 12 (hash-table) > (set! (hash 'a) 10) 10 > hash (hash-table 'a 10) > (set! (hash 'b) 32) error: hash-table-set! value argument 3, 32, is an integer but should be a 10|12?

environments

An environment holds symbols and their values. The global environment, for example, holds all the variables that are defined at the top level. Environments are first class (and applicable) objects in s7.

(rootlet) the top-level (global) environment (curlet) the current (innermost) environment (funclet proc) the environment at the time when proc was defined (funclet? env) #t if env is a funclet (owlet) the environment at the point of the last error (unlet) a let with any built-in functions that do not have their original value (let-ref env sym) get value of sym in env, same as (env sym) (let-set! env sym val) set value of sym in env to val, same as (set! (env sym) val) (inlet . bindings) make a new environment with the given bindings (sublet env . bindings) same as inlet, but the new environment is local to env (varlet env . bindings) add new bindings directly to env (cutlet env . fields) remove bindings from env (let? obj) #t if obj is an environment (with-let env . body) evaluate body in the environment env (outlet env) the environment that encloses the environment env (settable) (let->list env) return the environment bindings as a list of (symbol . value) cons's (openlet env) mark env as open (see below) (openlet? env) #t is env is open (coverlet env) mark env as closed (undo an earlier openlet) (object->let obj) return an environment containing information about obj (let-temporarily vars . body)

> (inlet 'a 1 'b 2) (inlet 'a 1 'b 2) > (let ((a 1) (b 2)) (curlet)) (inlet 'a 1 'b 2) > (let ((x (inlet :a 1 :b 2))) (x 'a)) 1 > (with-let (inlet 'a 1 'b 2) (+ a b)) 3 > (let ((x (inlet :a 1 :b 2))) (set! (x 'a) 4) x) (inlet 'a 4 'b 2) > (let ((x (inlet))) (varlet x 'a 1) x) (inlet 'a 1) > (let ((a 1)) (let ((b 2)) (outlet (curlet)))) (inlet 'a 1) > (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (e 'a 'b)) ; in C terms, e->a->b 1 > (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (set! (e 'a 'b) 3) (e 'a 'b)) 3 > (define* (make-let (a 1) (b 2)) (sublet (rootlet) (curlet))) make-let > (make-let :b 32) (inlet 'a 1 'b 32)

As the names suggest, in s7 an environment is viewed as a disembodied let. Environments are equal if they contain the same symbols with the same values leaving aside shadowing, and taking into account the environment chain up to the rootlet. That is, two environments are equal if any local variable of either has the same value in both.

let-ref and let-set! return #<undefined> if the first argument is not defined in the environment or its parents. To search just the given environment (ignoring its outlet chain), use defined? with the third argument #t before calling let-ref or let-set!:

> (defined? 'car (inlet 'a 1) #t) #f > (defined? 'car (inlet 'a 1)) #t

This matters in let-set!: (let-set! (inlet 'a 1) 'car #f) is the same as (set! car #f) !

with-let evaluates its body in the given environment, so (with-let e . body) is equivalent to (eval `(begin ,@body) e) , but probably faster. Similarly, (let bindings . body) is equivalent to (eval `(begin ,@body) (apply inlet (flatten bindings))) , ignoring the outer (enclosing) environment (the default outer environment of inlet is rootlet). Or better,

(define-macro (with-environs e . body) `(apply let (map (lambda (a) (list (car a) (cdr a))) ,e) '(,@body)))

Or turning it around,

(define-macro (Let vars . body) `(with-let (sublet (curlet) ,@(map (lambda (var) (values (symbol->keyword (car var)) (cadr var))) vars)) ,@body)) (Let ((c 4)) (Let ((a 2) (b (+ c 2))) (+ a b c)))

let-temporarily (now built-into s7) is somewhat similar to fluid-let in other Schemes. Its syntax looks like let, but it first saves the current value, then sets the variable to the new value (via set!), calls the body, and finally restores the original value. It can handle anything settable:

(let-temporarily (((*s7* 'print-length) 8)) (display x))

This sets s7's print-length variable to 8 while displaying x, then puts it back to its original value.

> (define ourlet (let ((x 1)) (define (a-func) x) (define b-func (let ((y 1)) (lambda () (+ x y)))) (curlet))) (inlet 'x 1 'a-func a-func 'b-func b-func) > (ourlet 'x) 1 > (let-temporarily (((ourlet 'x) 2)) ((ourlet 'a-func))) 2 > ((funclet (ourlet 'b-func)) 'y) 1 > (let-temporarily ((((funclet (ourlet 'b-func)) 'y) 3)) ((ourlet 'b-func))) 4

Despite the name, no new environment is created by let-temporarily: (let () (let-temporarily () (define x 2)) (+ x 1)) is 3.

sublet adds bindings (symbols with associated values) to an environment. It does not change the environment passed to it, but just prepends the new bindings, shadowing any old ones, as if you had called "let". To add the bindings directly to the environment, use varlet. Both of these functions accept nil as the 'env' argument as shorthand for (rootlet) . Both also accept other environments as well as individual bindings, adding all the argument's bindings to the new environment. inlet is very similar, but normally omits the environment argument. The arguments to sublet and inlet can be passed as symbol/value pairs, as a cons, or using keywords as if in define*. inlet can also be used to copy an environment without accidentally invoking that environment's copy method.

Here's an example: we want to define two functions that share a local variable:

(varlet (curlet) ; import f1 and f2 into the current environment (let ((x 1)) ; x is our local variable (define (f1 a) (+ a x)) (define (f2 b) (* b x)) (inlet 'f1 f1 'f2 f2))) ; export f1 and f2

One way to add reader and writer functions to an individual environment slot is:

(define e (inlet 'x (let ((local-x 3)) ; x's initial value (dilambda (lambda () local-x) (lambda (val) (set! local-x (max 0 (min val 100)))))))) > ((e 'x)) 3 > (set! ((e 'x)) 123) 100

funclet returns a function's local environment. Here's an example that keeps a circular buffer of the calls to that function:

(define func (let ((history (let ((lst (make-list 8 #f))) (set-cdr! (list-tail lst 7) lst)))) (lambda (x y) (let ((result (+ x y))) (set-car! history (list result x y)) (set! history (cdr history)) result)))) > (func 1 2) 3 > (func 3 4) 7 > ((funclet func) 'history) #1=(#f #f #f #f #f #f (3 1 2) (7 3 4) . #1#)

It is possible in Scheme to redefine built-in functions such as car. To ensure that some code sees the original built-in function definitions, wrap it in (with-let (unlet) ...) :

> (let ((caar 123)) (+ caar (with-let (unlet) (caar '((2) 3))))) 125

Or perhaps better, to keep the current environment intact except for the changed built-ins:

> (let ((x 1) (display 3)) (with-let (sublet (curlet) (unlet)) ; (curlet) picks up 'x, (unlet) the original 'display (display x))) 1

with-let and unlet are constants, so you can use them in any context without worrying about whether they've been redefined. As mentioned in the macro section, #_<name> is a built-in reader macro for (with-let (unlet) <name>) , so for example, #_+ is the built-in + function, no matter what. (The environment of built-in functions that unlet accesses is not accessible from scheme code, so there's no way that those values can be clobbered). I think these functions can implement the notions of libraries, separate namespaces, or modules. Here's one way: first the library writer just writes his library. The normal user simply loads it. The abnormal user worries about everything, so first he loads the library in a local let to make sure no bindings escape to pollute his code, and then he uses unlet to make sure that none of his bindings pollute the library code: (let () (with-let (unlet) (load "any-library.scm" (curlet)) ;; by default load puts stuff in the global environment ...)) Now Abnormal User can do what he wants with the library entities. Say he wants to use "lognor" under the name "bitwise-not-or", and all the other functions are of no interest: (varlet (curlet) 'bitwise-not-or (with-let (unlet) (load "any-library.scm" (curlet)) lognor)) ; lognor is presumably defined in "any-library.scm" Say he wants to make sure the library is cleanly loaded, but all its top-level bindings are imported into the current environment: (varlet (curlet) (with-let (unlet) (let () (load "any-library.scm" (curlet)) (curlet)))) ; these are the bindings introduced by loading the library To do the same thing, but prepend "library:" to each name: (apply varlet (curlet) (with-let (unlet) (let () (load "any-library.scm" (curlet)) (map (lambda (binding) (cons (symbol "library:" (symbol->string (car binding))) (cdr binding))) (curlet))))) That's all there is to it! Here is the same idea as a macro: (define-macro (let! init end . body) ;; syntax mimics 'do: (let! (vars&values) ((exported-names) result) body) ;; (let! ((a 1)) ((hiho)) (define (hiho x) (+ a x))) `(let ,init ,@body (varlet (outlet (curlet)) ,@(map (lambda (export) `(cons ',export ,export)) (car end))) ,@(cdr end))) Well, almost, darn it. If the loaded library file sets (via set!) a global value such as abs, we need to put it back to its original form: (define (safe-load file) (let ((e (with-let (unlet) ; save the environment before loading (let->list (curlet))))) (load file (curlet)) (let ((new-e (with-let (unlet) ; get the environment after loading (let->list (curlet))))) (for-each ; see if any built-in functions were stepped on (lambda (sym) (unless (assoc (car sym) e) (format () "~S clobbered ~A~%" file (car sym)) (apply set! (car sym) (list (cdr sym))))) new-e)))) ;; say libtest.scm has the line (set! abs odd?) > (safe-load "libtest.scm") "libtest.scm" clobbered abs > (abs -2) 2

openlet marks its argument, either an environment, a closure, a c-object, or a c-pointer as open; coverlet as closed. I need better terminology here! An open object is one that the built-in s7 functions handle specially. If they encounter one in their argument list, they look in the object for their own name, and call that function if it exists. A bare-bones example:

> (abs (openlet (inlet 'abs (lambda (x) 47)))) 47 > (define* (f1 (a 1)) (if (real? a) (abs a) ((a 'f1) a))) f1 > (f1 :a (openlet (inlet 'f1 (lambda (e) 47)))) 47

In CLOS, we'd declare a class and a method, and call make-instance, and then discover that it wouldn't work anyway. Here we have, in effect, an anonymous instance of an anonymous class. I think this is called a "prototype system"; javascript is apparently similar. A slightly more complex example:

(let* ((e1 (openlet (inlet 'x 3 '* (lambda args (apply * (if (number? (car args)) (values (car args) ((cadr args) 'x) (cddr args)) (values ((car args) 'x) (cdr args)))))))) (e2 (copy e1))) (set! (e2 'x) 4) (* 2 e1 e2)) ; (* 2 3 4) => 24

Perhaps these names would be better: openlet -> with-methods, coverlet -> without-methods, and openlet? -> methods?.

let-ref and let-set! are problematic as methods. It is very easy to get into an infinite loop, especially with let-ref since any reference to the let within the method body probably calls let-ref, which calls the let-ref method. We used to recommend coverlet here, but even that is not enough, so not let-ref and let-set! are immutable; they can't be used as methods. Use let-ref-fallback and let-set-fallback instead, if possible.

object->let returns an environment (more of a dictionary really) that contains details about its argument. It is intended as a debugging aid, underlying a debugger's "inspect" for example.

> (let ((iter (make-iterator "1234"))) (iter) (iter) (object->let iter)) (inlet 'value #<iterator: string> 'type iterator? 'at-end #f 'sequence "1234" 'length 4 'position 2)

A c-object (in the sense of s7_make_c_type), can add its own info to this namespace via an object->let method in its local environment. snd-marks.c has a simple example using a class-wide environment (g_mark_methods), holding as the value of its 'object->let field the function s7_mark_to_let. The latter uses s7_varlet to add information to the namespace created by (object->let mark) .

(define-macro (value->symbol expr) `(let ((val ,expr) (e1 (curlet))) (call-with-exit (lambda (return) (do ((e e1 (outlet e))) () (for-each (lambda (slot) (if (equal? val (cdr slot)) (return (car slot)))) e) (if (eq? e (rootlet)) (return #f))))))) > (let ((a 1) (b "hi")) (value->symbol "hi")) b

openlet alerts the rest of s7 that the environment has methods. (begin (define fvector? #f) (define make-fvector #f) (let ((type (gensym)) (->float (lambda (x) (if (real? x) (* x 1.0) (error 'wrong-type-arg "fvector new value is not a real: ~A" x))))) (set! make-fvector (lambda* (len (init 0.0)) (openlet (inlet :v (make-vector len (->float init)) :type type :length (lambda (f) len) :object->string (lambda (f . args) "#<fvector>") :let-set! (lambda (fv i val) (#_vector-set! (fv 'v) i (->float val))) :let-ref-fallback (lambda (fv i) (#_vector-ref (fv 'v) i)))))) (set! fvector? (lambda (p) (and (let? p) (eq? (p 'type) type)))))) > (define fv (make-fvector 32)) fv > fv #<fvector> > (length fv) 32 > (set! (fv 0) 123) 123.0 > (fv 0) 123.0

If an s7 function ignores the type of an argument, as in cons or vector for example, then that argument won't be treated as having any methods. Since outlet is settable, there are two ways an environment can become circular. One is to include the current environment as the value of one of its variables. The other is: (let () (set! (outlet (curlet)) (curlet))) . If you want to hide an environment's fields from any part of s7 that does not know the field names in advance, (openlet ; make it appear to be empty to the rest of s7 (inlet 'object->string (lambda args "#<let>") 'map (lambda args ()) 'for-each (lambda args #<unspecified>) 'let->list (lambda args ()) 'length (lambda args 0) 'copy (lambda args (inlet)) 'open #t 'coverlet (lambda (e) (set! (e 'open) #f) e) 'openlet (lambda (e) (set! (e 'open) #t) e) 'openlet? (lambda (e) (e 'open)) ;; your secret data here )) (There are still at least two ways to tell that something is fishy).

Here's one way to add a method to a closure: (define sf (let ((object->string (lambda (obj . arg) "#<secret function!>"))) (openlet (lambda (x) (+ x 1))))) > sf #<secret function!>

multiple-values

In s7, multiple values are spliced directly into the caller's argument list.

> (+ (values 1 2 3) 4) 10 > (string-ref ((lambda () (values "abcd" 2)))) #\c > ((lambda (a b) (+ a b)) ((lambda () (values 1 2)))) 3 > (+ (call/cc (lambda (ret) (ret 1 2 3))) 4) ; call/cc has an implicit "values" 10 > ((lambda* ((a 1) (b 2)) (list a b)) (values :a 3)) (3 2) (define-macro (call-with-values producer consumer) `(,consumer (,producer))) (define-macro (multiple-value-bind vars expr . body) `((lambda ,vars ,@body) ,expr)) (define-macro (define-values vars expression) `(if (not (null? ',vars)) (varlet (curlet) ((lambda ,vars (curlet)) ,expression)))) (define (curry function . args) (if (null? args) function (lambda more-args (if (null? more-args) (apply function args) (function (apply values args) (apply values more-args))))))

multiple-values are useful in a several situations. For example, (if test (+ a b c) (+ a b d e)) can be written (+ a b (if test c (values d e))) . There are a few special uses of multiple-values. First, you can use the values function to return any number of values, including 0, from map's function application: > (map (lambda (x) (if (odd? x) (values x (* x 20)) (values))) (list 1 2 3)) (1 20 3 60) > (map values (list 1 2 3) (list 4 5 6)) (1 4 2 5 3 6) (define (remove-if func lst) (map (lambda (x) (if (func x) (values) x)) lst)) (define (pick-mappings func lst) (map (lambda (x) (or (func x) (values))) lst)) (define (shuffle . args) (apply map values args)) > (shuffle '(1 2 3) #(4 5 6) '(7 8 9)) (1 4 7 2 5 8 3 6 9) (define (concatenate . args) (apply append (map (lambda (arg) (map values arg)) args))) Second, a macro can return multiple values; these are evaluated and spliced, exactly like a normal macro, so you can use (values '(define a 1) '(define b 2)) to splice multiple definitions at the macro invocation point. If an expansion returns (values), nothing is spliced in. This is mostly useful in reader-cond and the #; reader. > (define-expansion (comment str) (values)) comment > (+ 1 (comment "one") 2 (comment "two")) 3 At the top-level (in the REPL), since there's nothing to splice into, you simply get your values back: > (values 1 (list 1 2) (+ 3 4 5)) (values 1 (1 2) 12) But this printout is just trying to be informative. There is no multiple-values object in s7. You can't (set! x (values 1 2)) , for example. The values function tells s7 that its arguments should be handled in a special way, and the multiple-value indication goes away as soon as the arguments are spliced into some caller's arguments. There are two helper functions for multiple values, apply-values and list-values, both intended primarily for quasiquote where (apply-values ...) implements what other schemes call unquote-splicing (",@..."). (apply-values lst) is like (apply values lst), and (list-values ...) is like (list ...) except in one special case. It is common in writing macros to create some piece of code to be spliced into the output, but if that code is nil, the resulting macro code should contain nothing (not nil). apply-values and list-values cooperate with quasiquote to implement this. As an example: > (list-values 1 2 (apply-values) 3) (1 2 3) > (define (supply . args) (apply-values args)) supply > (define (consume f . args) (apply f (apply list-values args))) consume > (consume + (supply 1 2) (supply 3 4 5) (supply)) 15 > (consume + (supply)) 0 It might seem simpler to return "nothing" from (values), rather than #<unspecified>, but that has drawbacks. First, (abs -1 (values)) , or worse (abs (f x) (f y)) is no longer an error at the level of the program text; you lose the ability to see at a glance that a normal function has the right number of arguments. Second, a lot of code currently assumes that (values) returns #<unspecified>, and that implies that (apply values ()) does as well. But it would be nice if ((lambda* ((x 1)) x) (values)) returned 1! Since set! does not evaluate its first argument, and there is no setter for "values", (set! (values x) ...) is not the same as (set! x ...) . (string-set! (values string) ...) works because string-set! does evaluate its first argument. ((values + 1 2) (values 3 4) 5) is 15, as anyone would expect. One problem with this way of handling multiple values involves cases where you can't tell whether an expression will return multiple values. Then you have, for example, (let ((val (expr)))...) and need to accept either a normal single value from expr , or one member of the possible set of multiple values. In lint.scm, I'm currently handling this with lambda: (let ((val ((lambda args (car args)) (expr))))...) , but this feels kludgey. CL has nth-value which appears to do "the right thing" in this context; perhaps s7 needs it too. A similar difficulty arises in (if (expr) ...) where (expr) might return multiple values. CL (or sbcl anyway) treats this as if it were wrapped in (nth-value 0 (expr)) . Splicing the values in, on the other hand, could lead to disaster: there would be no way to tell from the code that the if statement was valid, or which branch would be taken! So, in those cases where a syntactic form evaluates an argument, s7 follows CL, and uses only the first of the values (this affects if, when, unless, cond, and case).

call-with-exit, with-baffle and continuation?

call-with-exit is call/cc without the ability to jump back into the original context, similar to "return" in C. This is cleaner than call/cc, and much faster.

(define-macro (block . body) ;; borrowed loosely from CL — predefine "return" as an escape `(call-with-exit (lambda (return) ,@body))) (define-macro (while test . body) ; while loop with predefined break and continue `(call-with-exit (lambda (break) (let continue () (if (let () ,test) (begin (let () ,@body) (continue)) (break)))))) (define-macro (switch selector . clauses) ; C-style case (branches fall through unless break called) `(call-with-exit (lambda (break) (case ,selector ,@(do ((clause clauses (cdr clause)) (new-clauses ())) ((null? clause) (reverse new-clauses)) (set! new-clauses (cons `(,(caar clause) ,@(cdar clause) ,@(map (lambda (nc) (apply values (cdr nc))) ; doubly spliced! (if (pair? clause) (cdr clause) ()))) new-clauses))))))) (define (and-for-each func . args) ;; apply func to the first member of each arg, stopping if it returns #f (call-with-exit (lambda (quit) (apply for-each (lambda arglist (if (not (apply func arglist)) (quit #<unspecified>))) args)))) (define (find-if f . args) ; generic position-if is very similar (call-with-exit (lambda (return) (apply for-each (lambda main-args (if (apply f main-args) (apply return main-args))) args)))) > (find-if even? #(1 3 5 2)) 2 > (* (find-if > #(1 3 5 2) '(2 2 2 3))) 6

The call-with-exit function's argument (the "continuation") is only valid within the call-with-exit function. In call/cc, you can save it, then call it later to jump back, but if you try that with call-with-exit (from outside the call-with-exit function's body), you'll get an error. This is similar to trying to read from a closed input port.

The other side, so to speak, of call-with-exit, is with-baffle. Sometimes we need a normal call/cc, but want to make sure it is active only within a given block of code. Normally, if a continuation gets away, there's no telling when it might wreak havoc on us. with-baffle blocks that — no continuation can jump into its body:

(let ((what's-for-breakfast ()) (bad-dog 'fido)) ; bad-dog wonders what's for breakfast? (with-baffle ; the syntax is (with-baffle . body) (set! what's-for-breakfast (call/cc (lambda (biscuit?) (set! bad-dog biscuit?) ; bad-dog smells a biscuit! 'biscuit!)))) (if (eq? what's-for-breakfast 'biscuit!) (bad-dog 'biscuit!)) ; now, outside the baffled block, bad-dog wants that biscuit! what's-for-breakfast) ; but s7 says "No!": baffled! ("continuation can't jump into with-baffle")

continuation? returns #t if its argument is a continuation, as opposed to a normal procedure. I don't know why Scheme hasn't had this function from the very beginning, but it's needed if you want to write a continuable error handler. Here is a sketch of the situation:

(catch #t (lambda () (let ((res (call/cc (lambda (ok) (error 'cerror "an error" ok))))) (display res) (newline))) (lambda args (when (and (eq? (car args) 'cerror) (continuation? (cadadr args))) (display "continuing...") ((cadadr args) 2)) (display "oops")))

In a more general case, the error handler is separate from the catch body, and needs a way to distinguish a real continuation from a simple procedure.

(define (continuable-error . args) (call/cc (lambda (continue) (apply error args)))) (define (continue-from-error) (if (continuation? ((owlet) 'continue)) ; might be #<undefined> or a function as in the while macro (((owlet) 'continue)) 'bummer))

format, object->string

object->string returns the string representation of its argument. Its optional second argument can be #f or :display (use display), #t or :write (the default, use write), or :readable. In the latter case, object->string tries to produce a string that can be evaluated via eval-string to return an object equal to the original. The optional third argument sets the maximum desired string length; if object->string notices it has exceeded this limit, it returns the partial string.

> (object->string "hiho") "\"hiho\"" > (format #f "~S" "hiho") "\"hiho\""

s7's format function is very close to that in srfi-48.

> (format #f "~A ~D ~F" 'hi 123 3.14) "hi 123 3.140000"

The format directives (tilde chars) are:

~% insert newline ~& insert newline if preceding char was not newline ~~ insert tilde ~

(tilde followed by newline): trim white space ~{ begin iteration (take arguments from a list, string, vector, or any other applicable object) ~} end iteration ~^ ~| jump out of iteration ~* ignore the current argument ~C print character (numeric argument = how many times to print it) ~P insert 's' if current argument is not 1 or 1.0 (use ~@P for "ies" or "y") ~A object->string as in display ~S object->string as in write ~B number->string in base 2 ~O number->string in base 8 ~D number->string in base 10 ~X number->string in base 16 ~E float to string, (format #f "~E" 100.1) -> "1.001000e+02", (%e in C) ~F float to string, (format #f "~F" 100.1) -> "100.100000", (%f in C) ~G float to string, (format #f "~G" 100.1) -> "100.1", (%g in C) ~T insert spaces (padding) ~N get numeric argument from argument list (similar to ~V in CL) ~W object->string with :readable (write readably; s7 is the intended reader)

The eight directives before ~W take the usual numeric arguments to specify field width and precision. These can also be ~N or ~n in which case the numeric argument is read from the list of arguments:

(format #f "~ND" 20 1234) ; => (format "~20D" 1234) " 1234"

(format #f ...) simply returns the formatted string; (format #t ...) also sends the string to the current-output-port. (format () ...) sends the output to the current-output-port without returning the string (this mimics the other IO routines such as display and newline). Other built-in port choices are *stdout* and *stderr*.

Floats can occur in any base, so: > #xf.c 15.75 This also affects format. In most Schemes, (format #f "~X" 1.25) is an error. In CL, it is equivalent to using ~A which is perverse. But > (number->string 1.25 16) "1.4" and there's no obvious way to get the same effect from format unless we accept floats in the "~X" case. So in s7, > (format #f "~X" 21) "15" > (format #f "~X" 1.25) "1.4" > (format #f "~X" 1.25+i) "1.4+1.0i" > (format #f "~X" 21/4) "15/4" That is, the output choice matches the argument. A case that came up in the Guile mailing lists is: (format #f "~F" 1/3) . s7 currently returns "1/3", but Clisp returns "0.33333334".

The curly bracket directive applies to anything you can map over, not just lists: > (format #f "~{~C~^ ~}" "hiho") "h i h o" > (format #f "~{~{~C~^ ~}~^...~}" (list "hiho" "test")) "h i h o...t e s t" > (with-input-from-string (format #f "(~{~C~^ ~})" (format #f "~B" 1367)) read) ; integer->list (1 0 1 0 1 0 1 0 1 1 1)

Since any sequence can be passed to ~{~}, we need a way to truncate output and represent the rest of the sequence with "...", but ~^ only stops at the end of the sequence. ~| is like ~^ but it also stops after it handles (*s7* 'print-length) elements and prints "...". So, (format #f "~{~A~| ~}" #(0 1 2 3 4)) returns "0 1 2 ..." if (*s7* 'print-length) is 3.

I added object->string to s7 before deciding to include format. format excites a vague disquiet — why do we need this ancient unlispy thing? We can almost replace it with: (define (objects->string . objects) (apply string-append (map (lambda (obj) (object->string obj #f)) objects))) But how to handle lists (~{...~} in format), or columnized output (~T)? I wonder whether formatted string output still matters outside a REPL. Even in that context, a modern GUI leaves formatting decisions to a text or table widget. (define-macro (string->objects str . objs) `(with-input-from-string ,str (lambda () ,@(map (lambda (obj) `(set! ,obj (eval (read)))) objs)))) format is a mess. It is trying to cram two different choices into its first ("port") argument. Perhaps it should be split into format->string and format->port. format->string has no port argument and returns a string. format->port writes to its port argument (which must be an output port, not a boolean), and returns #f or maybe <unspecified>. Then: (format #f ...) -> (format->string ...) (format () ...) -> (format->port (current-output-port) ...) (format #t ...) -> (display (format->string ...)) (format port ...) -> (display (format->string ...) port) and the currently unavailable choice, format to port without creating a string: (format->port port ...) .

hooks

(make-hook . fields) ; make a new hook (hook-functions hook) ; the hook's list of 'body' functions

A hook is a function created by make-hook, and called (normally from C) when something interesting happens. In GUI toolkits hooks are called callback-lists, in CL conditions, in other contexts watchpoints or signals. s7 itself has several hooks: *error-hook*, *read-error-hook*, *unbound-variable-hook*, *missing-close-paren-hook*, *rootlet-redefinition-hook*, *load-hook*, and *autoload-hook*. make-hook is:

(define (make-hook . args) (let ((body ())) (apply lambda* args '(let ((result #<unspecified>)) (let ((e (curlet))) (for-each (lambda (f) (f e)) body) result)) ())))

So the result of calling make-hook is a function (the lambda* that is applied to args above) that contains a list of functions, 'body. Each function in that list takes one argument, the hook. Each time the hook itself is called, each of the body functions is called, and the value of 'result is returned. That variable, and each of the hook's arguments are accessible to the hook's internal functions by going through the environment passed to the internal functions. This is a bit circuitous; here's a sketch:

> (define h (make-hook '(a 32) 'b)) ; h is a function: (lambda* ((a 32) b) ...) h > (set! (hook-functions h) ; this sets ((funclet h) 'body) (list (lambda (hook) ; each hook internal function takes one argument, the environment (set! (hook 'result) ; this is the "result" variable above (format #f "a: ~S, b: ~S" (hook 'a) (hook 'b)))))) (#<lambda (hook)>) > (h 1 2) ; this calls the hook's internal functions (just one in this case) "a: 1, b: 2" ; we set "result" to this string, so it is returned as the hook application result > (h) "a: 32, b: #f"

In C, to make a hook:

hook = s7_eval_c_string("(make-hook '(a 32) 'b)"); s7_gc_protect(s7, hook);

And call it:

result = s7_call(s7, hook, s7_list(s7, 2, s7_make_integer(s7, 1), s7_make_integer(s7, 2)));

(define-macro (hook . body) ; return a new hook with "body" as its body, setting "result" `(let ((h (make-hook))) (set! (hook-functions h) (list (lambda (h) (set! (h 'result) (begin ,@body))))) h))

variable info

(documentation obj) ; old name: (procedure-documentation obj) (signature obj) ; old: (procedure-signature obj) (setter obj) ; old: (procedure-setter obj) (arity obj) ; very old: (procedure-arity obj) (aritable? obj num-args) (funclet proc) (procedure-source proc)

funclet returns a procedure's environment.

> (funclet (let ((b 32)) (lambda (a) (+ a b)))) (inlet 'b 32) > (funclet abs) (rootlet)

setter returns or sets the set function associated with a procedure (set-car! with car, for example).

procedure-source returns the procedure source (a list):

(define (procedure-arglist f) (cadr (procedure-source f)))

documentation returns the documentation string associated with a procedure. This used to be the initial string in the function's body (as in CL), but now it is the value of the '+documentation+ variable, if any, in the procedure's local environment:

(define func (let ((+documentation+ "helpful info")) (lambda (a) a))) > (documentation func) "helpful info"

Since documentation is a method, a function's documentation can be computed at run-time:

(define func (let ((documentation (lambda (f) (format #f "this is func's funclet: ~S" (funclet f))))) (lambda (x) (+ x 1)))) > (documentation func) "this is func's funclet: (inlet 'x ())"

arity takes any object and returns either #f if it is not applicable, or a cons containing the minimum and maximum number of arguments acceptable. If the maximum reported is a really big number, that means any number of arguments is ok. aritable? takes two arguments, an object and an integer, and returns #t if the object can be applied to that many arguments.

> (define* (add-2 a (b 32)) (+ a b)) add-2 > (procedure-source add-2) (lambda* (a (b 32)) (+ a b)) > (arity add-2) (0 . 2) > (aritable? add-2 1) #t

signature is a list describing the argument types and returned value type of the function. The first entry in the list is the return type, and the rest are argument types. #t means any type is possible, and 'values means the function returns multiple values.

> (signature round) (integer? real?) ; round takes a real argument, returns an integer > (signature vector-ref) (#t vector? . #1=(integer? . #1#)) ; trailing args are all integers (indices)

If an entry is a list, any of the listed types can occur:

> (signature char-position) ((boolean? integer?) (char? string?) string? integer?)

which says that the first argument to char-position can be a string or a character, and the return type can be either boolean or an integer. If the function is defined in scheme, its signature is the value of the '+signature+ variable in its closure:

> (define f1 (let ((+documentation+ "helpful info") (+signature+ '(boolean? real?))) (lambda (x) (positive? x)))) f1 > (documentation f1) "helpful info" > (signature f1) (boolean? real?)

We could do the same thing using methods:

> (define f1 (let ((documentation (lambda (f) "helpful info")) (signature (lambda (f) '(boolean? real?)))) (openlet ; openlet alerts s7 that f1 has methods (lambda (x) (positive? x))))) > (documentation f1) "helpful info" > (signature f1) (boolean? real?)

signature could also be used to implement CL's 'the:

(define-macro (the value-type form) `((let ((+signature+ (list ,value-type))) (lambda () ,form)))) (display (+ 1 (the integer? (+ 2 3))))

but the optimizer currently doesn't know how to take advantage of this pattern.

You can obviously add your own methods:

(define my-add (let ((tester (lambda () (if (not (= (my-add 2 3) 5)) (format #t "oops: (myadd 2 3) -> ~A~%" (my-add 2 3)))))) (lambda (x y) (- x y)))) (define (auto-test) ; scan the symbol table for procedures with testers (let ((st (symbol-table))) (for-each (lambda (f) (let* ((fv (and (defined? f) (symbol->value f))) (testf (and (procedure? fv) ((funclet fv) 'tester)))) (when (procedure? testf) ; found one! (testf)))) st))) > (auto-test) oops: (myadd 2 3) -> -1

Even the setter can be set this way:

(define flocals (let ((x 1)) (let ((+setter+ (lambda (val) (set! x val)))) (lambda () x)))) > (flocals) 1 > (setter flocals) #<lambda (val)> > (set! (flocals) 32) 32 > (flocals) 32



(define (for-each-subset func args) ;; form each subset of args, apply func to the subsets that fit its arity (let subset ((source args) (dest ()) (len 0)) (if (null? source) (if (aritable? func len) ; does this subset fit? (apply func dest)) (begin (subset (cdr source) (cons (car source) dest) (+ len 1)) (subset (cdr source) dest len)))))

eval

eval evaluates its argument, a list representing a piece of code. It takes an optional second argument, the environment in which the evaluation should take place. eval-string is similar, but its argument is a string.

> (eval '(+ 1 2)) 3 > (eval-string "(+ 1 2)") 3

Leaving aside a few special cases, eval-string could be defined:

(define-macro* (eval-string x e) `(eval (with-input-from-string ,x read) (or ,e (curlet))))

IO and other OS functions

Besides files, ports can also represent strings and functions. The string port functions are:

(with-output-to-string thunk) ; open a string port as current-output-port, call thunk, return string (with-input-from-string string thunk) ; open string as current-input-port, call thunk (call-with-output-string proc) ; open a string port, apply proc to it, return string (call-with-input-string string proc) ; open string as current-input-port, apply proc to it (open-output-string) ; open a string output port (get-output-string port clear) ; return output accumulated in the string output port (open-input-string string) ; open a string input port reading string (open-input-function function) ; open a function input port (open-output-function function) ; open a function output port

> (let ((result #f) (p (open-output-string))) (format p "this ~A ~C test ~D" "is" #\a 3) (set! result (get-output-string p)) (close-output-port p) result) "this is a test 3"

In get-output-string, if the optional 'clear' argument is #t, the port is cleared (the default in r7rs I think). Other functions:

read-byte and write-byte: binary IO

read-line: line-at-a-time reads, optional third argument #t to include the newline

read-string (r7rs)

current-error-port, set-current-error-port

port-filename and port-line-number (input ports)

port-position (input port, settable)

port-file

Use length to get the length in bytes of an input port's file or string. port-line-number is settable (for fancy *#readers*). port-position is the position in bytes of the reader in the port. It is settable. port-file is intended for use with the *libc* library. It returns a c-pointer containing the FILE* pointer associated with the file port (except in Windows):

(call-with-input-file "s7test.scm" (lambda (p) (with-let (sublet *libc* :file (port-file p)) (fseek file 1000 SEEK_SET))))

The variable (*s7* 'print-length) sets the upper limit 