Let’s agree that serif fonts do not always carry boring stuff. And have a taste of it:
Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. — Revised 7 Report on the Algorithmic Language Scheme, Introduction.
Otherwise said, Scheme offers a minimalist core of powerful primitives upon which one can build abstractions to solve (real world) problems.
The Scheme universe is vast and prolific. As programming languages, Scheme dialects target various niches and implement various paradigms. Some of them are part of the de facto standards (namely RnRS and SRFIs).
The bestknown paradigm of agreedupon practices revolve around Functional Programming.
Scheme might be a dynamically typed language, but it can compete with its scions and siblings when performance matters.
Few programming languages can compete with Scheme when it comes to computer science whether it is Programming Language Theory, or Artificial Intelligence.
That being said, Scheme implementations might be missing some love. That’s a good opportunity for you to learn something useful and give something back.
Or, like others, to make it your secret sauce.
(scheme base)
R7RSsmall(scheme bitwise)
(scheme box)
(scheme bytevector)
(scheme caselambda)
R7RSsmall(scheme char)
R7RSsmall(scheme charset)
(scheme comparator)
(scheme complex)
R7RSsmall(scheme cxr)
R7RSsmall(scheme division)
(scheme ephemeron)
(scheme eval)
R7RSsmall(scheme file)
R7RSsmall(scheme fixnum)
(scheme flonum)
(scheme generator)
(scheme hashtable)
(scheme idque)
(scheme ilist)
(scheme inexact)
R7RSsmall(scheme lazy)
R7RSsmall(scheme list)
(scheme listqueue)
(scheme load)
R7RSsmall(scheme lseq)
(scheme mapping)
(scheme mappinghash)
(scheme processcontext)
R7RSsmall(scheme r5rs)
R7RSsmall(scheme read)
R7RSsmall(scheme regex)
(scheme repl)
R7RSsmall(scheme rlist)
(scheme set)
(scheme show)
(scheme sort)
(scheme stream)
(scheme text)
(scheme time)
R7RSsmall(scheme vector)
(scheme write)
R7RSsmallYou can find the source over the rainbow. There is available a single markdown file, and a single html file and a pdf;
Except otherwise noted, this documentation is licensed under the SRFI license:
Copyright (C) Amirouche Amazigh BOUBEKKI, and contributors (2021).
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # A cheatsheet on Discourse.
Before you speak, let your words pass through three gates.
You should attempt to reexpress your target’s position so clearly, vividly, and fairly that your target says, “Thanks, I wish I’d thought of putting it that way.”
You should list any points of agreement (especially if they are not matters of general or widespread agreement).
You should mention anything you have learned from your target.
Only then are you permitted to say so much as a word of rebuttal or criticism.
●●●●●  Highlevel generators  Disagreements that remain when everyone understands exactly what’s being argued, and agrees on what all the evidence says, but have vague and hardtodefine reasons for disagreeing.
●●●●○  Operationalizing  Where both parties understand they’re in a cooperative effort to fix exactly what they’re arguing about.
●●●○○  Survey of evidence  Not trying to devastate the other person with a mountain of facts and start looking at the studies and arguments on both sides and figuring out what kind of complex picture they paint.
●●●○○  Disputing definitions  Argument hinges on the meaning of words, or whether something counts as a member of a category or not.
●●○○○  Single Studies  Better than scattered facts, proving they at least looked into the issue formally.
●●○○○  Demands for rigor  Attempts to demand that an opposing argument be held to such strict standards that nothing could possibly clear the bar.
●○○○○  Single Facts One fact, which admittedly does support their argument, but presented as if it solves the debate in and of itself.
●○○○○  Gotchas  Short claims that purport to be devastating proof that one side can’t possibly be right.
○○○○○  Social shaming A demand for listeners to place someone outside the boundary of whom deserve to be heard.
“How to apologize: Quickly, specifically, sincerely.”
— Kevin Kelly
Belief : The mental state in which an individual holds a proposition to be true.
Priors : The beliefs an agent holds regarding a fact, hypothesis or consequence, before being presented with evidence.
Alief : An independent source of emotional reaction which can coexist with a contradictory belief. Example The fear felt when a monster jumps out of the darkness in a scary movie is based on the alief that the monster is about to attack you, even though you believe that it cannot.
Proper belief : Requires observations, gets updated upon encountering new evidence, and provides practical benefit in anticipated experience.
Improper belief : Is a belief that isn’t concerned with describing the territory. Note that the fact that a belief just happens to be true doesn’t mean you’re right to have it. If you buy a lottery ticket, certain that it’s a winning ticket (for no reason), and it happens to be, believing that was still a mistake.
Belief in belief : Where it is difficult to believe a thing, it is often much easier to believe that you ought to believe it. Were you to really believe and not just believe in belief, the consequences of error would be much more severe. When someone makes up excuses in advance, it would seem to require that belief, and belief in belief, have become unsynchronized.
A Priori : Knowledge which we can be sure of without any empirical evidence(evidence from our senses). So, knowledge that you could realize if you were just a mind floating in a void unconnected to a body.
“A leader is best when people barely know they exists, when their work is done, their aim fulfilled, people will say: we did it ourselves.”
— 老子(Lao Tse), 道德經(Dao De Jing)
The first principle of Wikipedia etiquette has been said to be Assume Good Faith, also they Be Bold, but not Reckless.
Wrong discourse
Answer: Jumping into a conversation with endless unapplicable, unrealistic or unrelated answers to the question.
Question: Spouting accusations while cowardly hiding behind the claim of just asking questions, and ignoring the answers. Asking loaded questions.
Good discourse
Answer: A clear and honest response to the central point of a question without an aggressive attempt to convince.
Question: question asked with the intention to be fair, open, and honest, regardless of the outcome of the interaction.
Social rules are expected to be broken from time to time, in that regard they are different from a code of conduct.
●●●●●  Release  Initiating a discussion on the lessons learnt from a project.
●●●●○  Update  Presenting the recent development of a personal experience, ongoing event or work in progress.
●●●○○  Soapbox  Spontaneous and or enthusiastic posts about a general topic of interest or finding.
●●○○○  Rant Venting frustration publicly without explicitly looking to have a conversation about the matter.
●○○○○  Shitpost  Aggressively or ironically looking for the biggest reaction with the least effort possible. Includes subtoots and vagueposting.
Seduction  You are led to feel that the fulfillment of your dreams depends on your doing what the other is encouraging you to do.
Alignment  The interests of the system are presented as fulfilling your emotional needs. You are led to feel that your survival, your viability in society or your very identity depends on your doing what the other is requiring of you.
Reduction  Complex subjects are reduced to a single, emotionally charged issue.
Polarization  Issues are presented in such a way that you are either right or wrong. You are told that any dialogue between different perspectives is suspect, dangerous or simply not permissible.
Marginalization  You are made to feel that your own interests (or interests that run counter to the interests of the other) are inconsequential.
Framing  The terms of a debate are set so that issues that threaten the system cannot be articulated or discussed. You are led to ignore aspects of the issue that may be vitally important to your own interests but are contrary to the interests of the other that is seeking to make you act in their interests.
“Kings speak for the realm, governors for the state, popes for the church. Indeed, the titled, as titled, cannot speak with annyone.”
— James P. Carse, Finite and Infinite Games
“Instead of trying to prove your opponent wrong, try to see in what sense he might be right.” — Robert Nozick, Anarchy, State, and Utopia
“I don’t argue: I just say what I know or what I believe, as the case may be.” — John W. Cohan
“You should mention anything you have learned from your target.”
The whole page is licensed under ccbyncsa; it is slightly adapted from https://wiki.xxiivv.com/site/discourse.html to be able to support the static site generator used on https://scheme.rs and to avoid the words “bad” (replaced with “wrong”) and “faith” (replaced with “discourse”), a few other changes, see history for complete log. # Tutorial
After reading this section you will be able to write basic Scheme programs. In particular, you will study:
How to comment code
How to write literals for builtin types
How to call a procedure
How to define a variable
How to compare objects
How to define a procedure
You can comment code with the semicolon, that is ;
.
Idiomatic code use two semicolons:
;; Everything after one semicolon is a comment.
The following sections will use two semicolons with followed by an
arrow =>
to describe the return value.
42
3.1415
#f
#t
Characters can be written with their natural representation prefixed
with #\\
, for instance the character x
is
represented in Scheme code as follow:
#\x
A string is written with double quotes, that is "
, for
instance:
"hello world"
A symbol is most of the time written with a simple quote prefix, that
is '
. For instance:
'unique
A pair of the symbol 'pi
and the value
3.1415
can be written as:
. 3.1415) '(pi
A list can be written as literals separated by one space and enclosed by parenthesis. For instance, the following list has three items:
"hello world" (pi . 3.1415))` '(unique
The first item is the symbol 'unique
, the second item is
a string, the third item is a pair.
The empty list is written '()
.
A vector looks somewhat like a list but without the explicit simple quote. It use a hash prefix. For instance, the following vector has three items:
"hello world" 42) #(unique
The first item is the symbol 'unique
, the second item is
a string, the third item is a number.
A bytevector is like vector but can contain only bytes. It looks like
a list of integers, prefixed with #vu8
. For instance, the
following bytevector has three bytes:
0 42 255) #vu8(
A procedure call looks like a list without the simple quote prefix.
The following describe the addition 21 and 21:
+ 21 21) ;; => 42 (
It returns 42
. So does the following multiplication:
* 21 2) ;; => 42 (
The first item is a procedure object. Most of the time, procedure
names are made of letters separated with dashes. That usually called
kebabcase
.
Here is another procedure call:
stringappend "hello" " " "world") ;; => "hello world" (
It will return a string "hello world"
.
The first kind of variables that you encountered are procedures,
things like +
, *
or
stringappend
.
Variables can also contain constants. You can use
define
:
define %thruth 42) (
The above code will create a variable called %thruth
that contains 42
.
Look at this very complicated computation:
+ %thruth 1 (* 2 647)) ;; => 1337 (
To compare by identity, in pratice, whether two object represent the
same memory location, you can use the procedure eq?
.
In the case where you are comparing symbols you can use the procedure
eq?
:
eq? 'unique 'unique) ;; => #t
(eq? 'unique 'singleton) ;; => #f (
If you do not know the type of the compared objects, or the objects
can be of different types, you can use the procedure
equal?
:
equal? #t "true") ;; => #f (
The string "true"
is not equivalent to the boolean
#t
.
It is rare to use equal?
, because, usually, you know the
type of the compared objects and the compared object have the same
type.
The astute reader might have recognized a pattern in the naming of
the equivalence procedures eq?
and equal?
:
both end with a question mark. That is a convention that all procedures
that can only return a boolean should end with a question mark. Those
are called predicates.
They are predicates for every builtin types. For instance string type
has a string equivalence predicate written string=?
:
string=? "hello" "hello world" "hello, world!") ;; => #f (
The predicate procedure string=?
will return
#t
if all arguments are the same string, in the sense they
contain the same characters.
The simplest procedure ever, is the procedure that takes no argument and returns itself:
define (ruse)
( ruse)
The above is sugar syntax for the following:
define ruse (lambda () ruse)) (
A procedure that takes no arguments is called a thunk.
Indentation and the newline are cosmetic conventions. If you call the
procedure ruse
, it will return ruse
:
eq? ruse (ruse)) (
One can define a procedure that adds one as follow:
define (add1 number)
(+ number 1)) (
The predicate to compare numbers is =
. Hence, the
following:
= 2006 (add1 2005)) ;; => #t (
Mind the fact that it returns a new number. It does not mutate the value even if it is passed as a variable.
Let’s imagine a procedure that appends a name to the string
"Hello"
. For instance, given "Aziz"
or a
variable containing "Aziz"
, it will return
"Hello Aziz"
.
define name "Aziz")
(
define (sayhello name)
(stringappend "Hello " name))
(
string=? "Hello Aziz" (sayhello name)) ;; => #t
(
;; XXX: the variable name still contains "Aziz"
string=? name "Aziz")) ;; => #t (
It does not matter for the callee whether the arguments are passed as variables or literals:
string=? "Hello John" (sayhello "John")) ;; => #t (
In this section you learned:
How to comment code using a semicolon character
;
How to write literals for builtin types
42
3.1415
'unique
"hello world"
(pi . 3.1415)
'(42 "hello world" (pi . 3.1415))
#(42 "hello world" (pi . 3.1415))
#vu8(1 42 255)
How to call a procedure
(stringappend "hello " "Aziz")
How to define a variable
(define %thruth 42)
How to compare objects using their type specific predicates. For
instance: (string=? "hello" "hello")
How to define a procedure again using define
with
slightly different syntax
(define (add1 number) (+ number 1))
After reading this section you will be able to write more complex Scheme code. In particular you will study:
How to create lexical bindings
How to set a variable
How to do a branch if
How to create a new type
How to write a namedlet
Lexical bindings can be created with let
,
let*
, letrec
and letrec*
. They
have slightly different behaviors, but the same syntax:
let (<binding> ...) <expression> ...) (
Where <binding>
looks like an association of a
variable name with the initial value it is holding. For instance:
let ((a 1)
(2))
(b + a b 3)) ;; => 6 (
The above let
form will bind a
to
1
, b
to 2
and return the output
of (+ a b 3)
that is 6
.
To change what a variable holds without overriding it or mutating the
object contained in the varialbe, you can use set!
. Mind
the exclamation mark, it is a convention that forms that have a
sideeffect ends with a exclamation mark. For instance:
define %thruth 42)
(
display %truth)
(newline)
(
set! %thruth 101)
(
display %truth)
(newline) (
if
Scheme if
will consider false, only the object
#f
. Hence, one can do the following:
if #t
(display "true")
(display "never executed")) (
Similarly:
if #f
(display "never executed")
(display "false")) (
In particular, the number zero is true according to scheme
if
:
if 0
(display "zero is true")
(display "never executed")) (
If you want to check whether a value is zero you can use the
predicate zero?
like so:
if (zero? %thruth)
(display "%thruth is zero")
(display "%thruth is not zero")) (
Or the less idiomatic predicate =
:
if (= %truth 0)
(display "%thruth is zero")
(display "%thruth is not zero")) (
To create a new type you can use the macro
definerecordtype
. For instance, in a todo list
application, we will need an <item>
type that can be
defined as:
definerecordtype <item>
(
(makeitem title body status)
item?
(title itemtitle itemtitle!)
(body itembody itembody!) (status itemstatus itemstatus!))
Where:
<item>
is the record name,makeitem
is the constructor of record instances,item?
is the predicate that allows to tell whether an
object is a <item>
type,title
, body
and status
are
fields with their associated getters and setters. Setters ends with an
exclamation mark. They will mutate the object. Setters are
optional.Here is an example use of the above <item>
definition:
define item (makeitem "Learn Scheme" "The Scheme programming language is awesome, I should learn it" 'todo))
(
;; To change the status, one can do the following:
(itemstatus! item 'wip)
;; to get the title, one can do the following:
display (itemtitle item))
(newline) (
A namedlet allows to do recursion without going through the ceremony
of defining a separate procedure. In pratice, it used in similar
contexts such as for
or while
loop in other
languages. Given the procedure (cons item items)
that will
return a new list with ITEMS
as tail and ITEM
as first item, study the following code:
let loop ((index 0)
(
(out '())if (= index 10)
(display out)
(+ index 1) (cons index out)))) (loop (
It is equivalent to the following:
define (loop index out)
(if (= index 10)
(display out)
(+ index 1) (cons index out))))
(loop (
0 '()) (loop
A namedlet, look like a let
form that can be used to
bind variables prefixed with a name. Here is some pseudocode that
describe the syntax of the namedlet form:
let <name> (<binding> ...) expression ...)) (
So <binding>
and <expression>
are very similar to a let
. <name>
will
be bound to a procedure that takes as many argument as there is
<binding>
and its body will be
<expression> ...
. It will be called with the
associated objects in <binding> ...
.
expression
can call <name>
most likely
in tail call position but not necessarly. If the namedlet is not
tailrecursive, it is also known to be a grow the stack recursive
call. Another way to see the namedlet is pseudocode:
define <name> (lambda <formals> <expression> ...))
(
...) (<name> <arguments>
Where:
<formals>
are the variable names from
<binding> ...
<arguments>
are the initial object bound in
<binding> ...
That is all.
How to create lexical bindings with let
,
let*
, letrec
and
letrec*
,
How to set a variable using
(set! %thruth 42)
,
How to do a if
with
(if %thruth (display "That is true") (display "That is false"))
,
How to create a new type using definerecordtype
that can look like:
definerecordtype <recordname>
(...)
(makerecordname field0
recordname? (field0 recordnamefield0 recordnamefield0!))
let loop ((index 0))
(display index)
(+ index 1))) (loop (
After reading this section you will be able to create libraries.
Note: This is a port of R^{7}RS specification from tex to markdown that is rendered to html. It does not include formal semantics.
The report gives a defining description of the programming language Scheme. Scheme is a statically scoped and properly tail recursive dialect of the Lisp programming language invented by Guy Lewis Steele Jr. and Gerald Jay Sussman. It was designed to have exceptionally clear and simple semantics and few different ways to form expressions. A wide variety of programming paradigms, including imperative, functional, and objectoriented styles, find convenient expression in Scheme.
The introduction offers a brief history of the language and of the report.
The first three chapters present the fundamental ideas of the language and describe the notational conventions used for describing the language and for writing programs in the language.
Chapters [expressionchapter] and [programchapter] describe the syntax and semantics of expressions, definitions, programs, and libraries.
Chapter [builtinchapter] describes Scheme’s builtin procedures, which include all of the language’s data manipulation and input/output primitives.
Chapter [formalchapter] provides a formal syntax for Scheme written in extended BNF, along with a formal denotational semantics. An example of the use of the language follows the formal syntax and semantics.
Appendix [stdlibraries] provides a list of the standard libraries and the identifiers that they export.
Appendix [stdfeatures] provides a list of optional but standardized implementation feature names.
The report concludes with a list of references and an alphabetic index.
Note: The editors of the R^{5}RS and R^{6}RS reports are listed as authors of this report in recognition of the substantial portions of this report that are copied directly from R^{5}RS and R^{6}RS. There is no intended implication that those editors, individually or collectively, support or do not support this report.
Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible enough to support most of the major programming paradigms in use today.
Scheme was one of the first programming languages to incorporate firstclass procedures as in the lambda calculus, thereby proving the usefulness of static scope rules and block structure in a dynamically typed language. Scheme was the first major dialect of Lisp to distinguish procedures from lambda expressions and symbols, to use a single lexical environment for all variables, and to evaluate the operator position of a procedure call in the same way as an operand position. By relying entirely on procedure calls to express iteration, Scheme emphasized the fact that tailrecursive procedure calls are essentially GOTOs that pass arguments, thus allowing a programming style that is both coherent and efficient. Scheme was the first widely used programming language to embrace firstclass escape procedures, from which all previously known sequential control structures can be synthesized. A subsequent version of Scheme introduced the concept of exact and inexact numbers, an extension of Common Lisp’s generic arithmetic. More recently, Scheme became the first programming language to support hygienic macros, which permit the syntax of a blockstructured language to be extended in a consistent and reliable manner.
The first description of Scheme was written in 1975 . A revised report appeared in 1978, which described the evolution of the language as its MIT implementation was upgraded to support an innovative compiler . Three distinct projects began in 1981 and 1982 to use variants of Scheme for courses at MIT, Yale, and Indiana University . An introductory computer science textbook using Scheme was published in 1984 .
As Scheme became more widespread, local dialects began to diverge until students and researchers occasionally found it difficult to understand code written at other sites. Fifteen representatives of the major implementations of Scheme therefore met in October 1984 to work toward a better and more widely accepted standard for Scheme. Their report, the RRRS , was published at MIT and Indiana University in the summer of 1985. Further revision took place in the spring of 1986, resulting in the R^{3}RS . Work in the spring of 1988 resulted in R^{4}RS , which became the basis for the IEEE Standard for the Scheme Programming Language in 1991 . In 1998, several additions to the IEEE standard, including highlevel hygienic macros, multiple return values, and eval, were finalized as the R^{5}RS .
In the fall of 2006, work began on a more ambitious standard, including many new improvements and stricter requirements made in the interest of improved portability. The resulting standard, the R^{6}RS, was completed in August 2007 , and was organized as a core language and set of mandatory standard libraries. Several new implementations of Scheme conforming to it were created. However, most existing R^{5}RS implementations (even excluding those which are essentially unmaintained) did not adopt R^{6}RS, or adopted only selected parts of it.
In consequence, the Scheme Steering Committee decided in August 2009 to divide the standard into two separate but compatible languages — a “small” language, suitable for educators, researchers, and users of embedded languages, focused on R^{5}RS compatibility, and a “large” language focused on the practical needs of mainstream software development, intended to become a replacement for R^{6}RS. The present report describes the “small” language of that effort: therefore it cannot be considered in isolation as the successor to R^{6}RS.
We intend this report to belong to the entire Scheme community, and so we grant permission to copy it in whole or in part without fee. In particular, we encourage implementers of Scheme to use this report as a starting point for manuals and other documentation, modifying it as necessary.
We would like to thank the members of the Steering Committee, William Clinger, Marc Feeley, Chris Hanson, Jonathan Rees, and Olin Shivers, for their support and guidance.
This report is very much a community effort, and we’d like to thank everyone who provided comments and feedback, including the following people: David Adler, Eli Barzilay, Taylan Ulrich Bayırlı/Kammer, Marco Benelli, Pierpaolo Bernardi, Peter Bex, Per Bothner, John Boyle, Taylor Campbell, Raffael Cavallaro, Ray Dillinger, Biep Durieux, Sztefan Edwards, Helmut Eller, Justin Ethier, Jay Reynolds Freeman, Tony GarnockJones, Alan Manuel Gloria, Steve Hafner, Sven Hartrumpf, Brian Harvey, Moritz Heidkamp, JeanMichel Hufflen, Aubrey Jaffer, Takashi Kato, Shiro Kawai, Richard Kelsey, Oleg Kiselyov, Pjotr Kourzanov, Jonathan Kraut, Daniel Krueger, Christian Stigen Larsen, Noah Lavine, Stephen Leach, Larry D. Lee, Kun Liang, Thomas Lord, Vincent Stewart Manis, Perry Metzger, Michael Montague, Mikael More, Vitaly Magerya, Vincent Manis, Vassil Nikolov, Joseph Wayne Norton, Yuki Okumura, Daichi Oohashi, Jeronimo Pellegrini, Jussi Piitulainen, Alex Queiroz, Jim Rees, Grant Rettke, Andrew Robbins, Devon Schudy, Bakul Shah, Robert Smith, Arthur Smyles, Michael Sperber, John David Stone, Jay Sulzberger, Malcolm Tredinnick, Sam TobinHochstadt, Andre van Tonder, Daniel Villeneuve, Denis Washington, Alan Watson, Mark H. Weaver, Göran Weinholt, David A. Wheeler, Andy Wingo, James Wise, Jörg F. Wittenberger, Kevin A. Wortman, Sascha Ziemann.
In addition we would like to thank all the past editors, and the people who helped them in turn: Hal Abelson, Norman Adams, David Bartley, Alan Bawden, Michael Blair, Gary Brooks, George Carrette, Andy Cromarty, Pavel Curtis, Jeff Dalton, Olivier Danvy, Ken Dickey, Bruce Duba, Robert Findler, Andy Freeman, Richard Gabriel, Yekta Gürsel, Ken Haase, Robert Halstead, Robert Hieb, Paul Hudak, Morry Katz, Eugene Kohlbecker, Chris Lindblad, Jacob Matthews, Mark Meyer, Jim Miller, Don Oxley, Jim Philbin, Kent Pitman, John Ramsdell, Guillermo Rozas, Mike Shaff, Jonathan Shapiro, Guy Steele, Julie Sussman, Perry Wagle, Mitchel Wand, Daniel Weise, Henry Wu, and Ozan Yigit. We thank Carol Fessenden, Daniel Friedman, and Christopher Haynes for permission to use text from the Scheme 311 version 4 reference manual. We thank Texas Instruments, Inc. for permission to use text from the TI Scheme Language Reference Manual . We gladly acknowledge the influence of manuals for MIT Scheme , T , Scheme 84 , Common Lisp , and Algol 60 , as well as the following SRFIs: 0, 1, 4, 6, 9, 11, 13, 16, 30, 34, 39, 43, 46, 62, and 87, all of which are available at http://srfi.schemers.org.
This section gives an overview of Scheme’s semantics. A detailed informal semantics is the subject of chapters [basicchapter] through [builtinchapter]. For reference purposes, section [formalsemanticssection] provides a formal semantics of Scheme.
Scheme is a statically scoped programming language. Each use of a variable is associated with a lexically apparent binding of that variable.
Scheme is a dynamically typed language. Types are associated with values (also called objects) rather than with variables. Statically typed languages, by contrast, associate types with variables and expressions as well as with values.
All objects created in the course of a Scheme computation, including procedures and continuations, have unlimited extent. No Scheme object is ever destroyed. The reason that implementations of Scheme do not (usually!) run out of storage is that they are permitted to reclaim the storage occupied by an object if they can prove that the object cannot possibly matter to any future computation.
Implementations of Scheme are required to be properly tailrecursive. This allows the execution of an iterative computation in constant space, even if the iterative computation is described by a syntactically recursive procedure. Thus with a properly tailrecursive implementation, iteration can be expressed using the ordinary procedurecall mechanics, so that special iteration constructs are useful only as syntactic sugar. See section [proper tail recursion].
Scheme procedures are objects in their own right. Procedures can be created dynamically, stored in data structures, returned as results of procedures, and so on.
One distinguishing feature of Scheme is that continuations, which in most other languages only operate behind the scenes, also have “firstclass” status. Continuations are useful for implementing a wide variety of advanced control constructs, including nonlocal exits, backtracking, and coroutines. See section [continuations].
Arguments to Scheme procedures are always passed by value, which means that the actual argument expressions are evaluated before the procedure gains control, regardless of whether the procedure needs the result of the evaluation.
Scheme’s model of arithmetic is designed to remain as independent as possible of the particular ways in which numbers are represented within a computer. In Scheme, every integer is a rational number, every rational is a real, and every real is a complex number. Thus the distinction between integer and real arithmetic, so important to many programming languages, does not appear in Scheme. In its place is a distinction between exact arithmetic, which corresponds to the mathematical ideal, and inexact arithmetic on approximations. Exact arithmetic is not limited to integers.
Scheme, like most dialects of Lisp, employs a fully parenthesized prefix notation for programs and other data; the grammar of Scheme generates a sublanguage of the language used for data. An important consequence of this simple, uniform representation is that Scheme programs and data can easily be treated uniformly by other Scheme programs. For example, the eval procedure evaluates a Scheme program expressed as data.
The read procedure performs syntactic as well as lexical decomposition of the data it reads. The read procedure parses its input as data (section [datumsyntax]), not as program.
The formal syntax of Scheme is described in section [BNF].
Every identifier defined in this report appears in one or more of
several libraries
. Identifiers defined in the base
library are not marked specially in the body of the report. This
library includes the core syntax of Scheme and generally useful
procedures that manipulate data. For example, the variable abs is bound
to a procedure of one argument that computes the absolute value of a
number, and the variable + is bound to a procedure that computes sums.
The full list all the standard libraries and the identifiers they export
is given in Appendix [stdlibraries].
All implementations of Scheme:
Must provide the base library and all the identifiers exported from it.
May provide or omit the other libraries given in this report, but each library must either be provided in its entirety, exporting no additional identifiers, or else omitted altogether.
May provide other libraries not described in this report.
May also extend the function of any identifier in this report, provided the extensions are not in conflict with the language reported here.
Must support portable code by providing a mode of operation in which the lexical syntax does not conflict with the lexical syntax described in this report.
When speaking of an error situation, this report uses the phrase “an error is signaled” to indicate that implementations must detect and report the error. An error is signaled by raising a noncontinuable exception, as if by the procedure raise as described in section [exceptionsection]. The object raised is implementationdependent and need not be distinct from objects previously used for the same purpose. In addition to errors signaled in situations described in this report, programmers can signal their own errors and handle signaled errors.
The phrase “an error that satisfies predicate is signaled”
means that an error is signaled as above. Furthermore, if the object
that is signaled is passed to the specified predicate (such as
fileerror? or readerror?), the predicate returns #t
.
If such wording does not appear in the discussion of an error, then implementations are not required to detect or report the error, though they are encouraged to do so. Such a situation is sometimes, but not always, referred to with the phrase “an error.” In such a situation, an implementation may or may not signal an error; if it does signal an error, the object that is signaled may or may not satisfy the predicates errorobject?, fileerror?, or readerror?. Alternatively, implementations may provide nonportable extensions.
For example, it is an error for a procedure to be passed an argument of a type that the procedure is not explicitly specified to handle, even though such domain errors are seldom mentioned in this report. Implementations may signal an error, extend a procedure’s domain of definition to include such arguments, or fail catastrophically.
This report uses the phrase “may report a violation of an implementation restriction” to indicate circumstances under which an implementation is permitted to report that it is unable to continue execution of a correct program because of some restriction imposed by the implementation. Implementation restrictions are discouraged, but implementations are encouraged to report violations of implementation restrictions.
For example, an implementation may report a violation of an implementation restriction if it does not have enough storage to run a program, or if an arithmetic operation would produce an exact number that is too large for the implementation to represent.
If the value of an expression is said to be “unspecified,” then the expression must evaluate to some object without signaling an error, but the value depends on the implementation; this report explicitly does not say what value is returned.
Finally, the words and phrases “must,” “must not,” “shall,” “shall not,” “should,” “should not,” “may,” “required,” “recommended,” and “optional,” although not capitalized in this report, are to be interpreted as described in RFC 2119 . They are used only with reference to implementer or implementation behavior, not with reference to programmer or program behavior.
Chapters [expressionchapter] and [builtinchapter] are organized into entries. Each entry describes one language feature or a group of related features, where a feature is either a syntactic construct or a procedure. An entry begins with one or more header lines of the form
template
category
for identifiers in the base library, or
template
name library category
where name
is the short name of a library as defined in
Appendix [stdlibraries].
If category
is “syntax,” the entry describes an
expression type, and the template gives the syntax of the expression
type. Components of expressions are designated by syntactic variables,
which are written using angle brackets, for example expression and
variable. Syntactic variables are intended to denote segments of program
text; for example, expression stands for any string of characters which
is a syntactically valid expression. The notation
thing ...
indicates zero or more occurrences of a thing
, and
thing thing ...
indicates one or more occurrences of a thing.
If category
is “auxiliary syntax,” then the entry
describes a syntax binding that occurs only as part of specific
surrounding expressions. Any use as an independent syntactic construct
or variable is an error.
If category
is “procedure,” then the entry describes a
procedure, and the header line gives a template for a call to the
procedure. Argument names in the template are italicized. Thus
the header line
(vectorref vector k)
procedure
indicates that the procedure bound to the vectorref
variable takes two arguments, a vector vector
and an exact
nonnegative integer k
(see below). The header lines
(makevector k)
procedure
(makevector k fill)
procedure
indicate that the makevector
procedure must be defined
to take either one or two arguments.
It is an error for a procedure to be presented with an argument that
it is not specified to handle. For succinctness, we follow the
convention that if an argument name is also the name of a type listed in
section [disjointness], then it is an error
if that argument is not of the named type. For example, the header line
for vectorref
given above dictates that the first argument
to vectorref
is a vector. The following naming conventions
also imply type restrictions:
alist  association list (list of pairs) 
boolean  boolean value (#t or
#f ) 
byte  exact integer 0 ≤ byte < 256 
bytevector  bytevector 
char  character 
end  exact nonnegative integer 
k, k_{1}, … k_{j}, …  exact nonnegative integer 
letters  alphabetic character 
list, list_{1}, … list_{j}, …  list (see section [listsection]) 
n, n_{1}, … n_{j}, …  integer 
obj  any object 
pair  pair 
port  port 
proc  procedure 
q, q_{1}, … q_{j}, …  rational number 
start  exact nonnegative integer 
string  string 
symbol  symbol 
thunk  zeroargument procedure 
vector  vector 
x, x_{1}, … x_{j}, …  real number 
y, y_{1}, … y_{j}, …  real number 
z, z_{1}, … z_{j}, …  complex number 
The names start
and end
are used as indexes
into strings, vectors, and bytevectors. Their use implies the
following:
It is an error if start
is greater than
end
.
It is an error if end
is greater than the length of
the string, vector, or bytevector.
If start
is omitted, it is assumed to be
zero.
If end
is omitted, it assumed to be the length of
the string, vector, or bytevector.
The index start
is always inclusive and the index
end
is always exclusive. As an example, consider a string.
If start
and end
are the same, an empty
substring is referred to, and if start
is zero and
end
is the length of string
, then the entire
string is referred to.
The symbol “=>” used in program examples is read “evaluates to.” For example,
* 5 8) ;; => 40 (
means that the expression (* 5 8)
evaluates to the
object 40
. Or, more precisely: the expression given by the
sequence of characters “(* 5 8)
” evaluates, in an
environment containing the base library, to an object that can be
represented externally by the sequence of characters “40
.”
See section [externalreps] for a discussion
of external representations of objects.
By convention, ?
is the final character of the names of
procedures that always return a boolean value. Such procedures are
called predicates. Predicates are generally understood to be
sideeffect free, except that they may raise an exception when passed
the wrong type of argument.
Similarly, !
is the final character of the names of
procedures that store values into previously allocated locations (see
section [storagemodel]). Such procedures are
called mutation procedures. The value returned by a mutation
procedure is unspecified.
By convention, “>
” appears within the names of
procedures that take an object of one type and return an analogous
object of another type. For example, list>vector takes a list and
returns a vector whose elements are the same as those of the list.
A command is a procedure that does not return useful values to its continuation.
A thunk is a procedure that does not accept arguments.
This section gives an informal account of some of the lexical conventions used in writing Scheme programs. For a formal syntax of Scheme, see section [BNF].
An identifier is any sequence of letters, digits, and “extended
identifier characters” provided that it does not have a prefix which is
a valid number. However, the .
token (a single period) used
in the list syntax is not an identifier.
All implementations of Scheme must support the following extended identifier characters:
!\ \$ \% & * +  . / :\ < = > ? @ ^ _ ~ %
Alternatively, an identifier can be represented by a sequence of zero or more characters enclosed within vertical lines (), analogous to string literals. Any character, including whitespace characters, but excluding the backslash and vertical line characters, can appear verbatim in such an identifier. In addition, characters can be specified using either an inline hex escape or the same escapes available in strings.
For example, the identifier H\x65;llo
is the same
identifier as Hello
, and in an implementation that supports
the appropriate Unicode character the identifier \x3BB;
is the same as the identifier λ
. What is more,
\t\t
and \x9;\x9;
are the same. Note that

is a valid identifier that is different from any other
identifier.
Here are some examples of identifiers:
... {+}
+soup+ <=?
>string a34kTMNs
lambda list>vector
q V17a
two words two\x20;words
thewordrecursionhasmanymeanings
See section [extendedalphas] for the formal syntax of identifiers.
Identifiers have two uses within Scheme programs:
Any identifier can be used as a variable or as a syntactic keyword (see sections [variablesection] and [macrosection]).
When an identifier appears as a literal or within a literal (see section [quote]), it is being used to denote a symbol (see section [symbolsection]).
In contrast with earlier revisions of the report , the syntax distinguishes between upper and lower case in identifiers and in characters specified using their names. However, it does not distinguish between upper and lower case in numbers, nor in inline hex escapes used in the syntax of identifiers, characters, or strings. None of the identifiers defined in this report contain uppercase characters, even when they appear to do so as a result of the Englishlanguage convention of capitalizing the first word of a sentence.
The following directives give explicit control over case folding.
#!foldcase
#!nofoldcase
These directives can appear anywhere comments are permitted (see section [wscommentsection]) but must be followed by a delimiter. They are treated as comments, except that they affect the reading of subsequent data from the same port. The #!foldcase directive causes subsequent identifiers and character names to be casefolded as if by stringfoldcase (see section [stringsection]). It has no effect on character literals. The #!nofoldcase directive causes a return to the default, nonfolding behavior.
Whitespace characters include the space, tab, and newline characters. (Implementations may provide additional whitespace characters such as page break.) Whitespace is used for improved readability and as necessary to separate tokens from each other, a token being an indivisible lexical unit such as an identifier or number, but is otherwise insignificant. Whitespace can occur between any two tokens, but not within a token. Whitespace occurring inside a string or inside a symbol delimited by vertical lines is significant.
The lexical syntax includes several comment forms. Comments are treated exactly like whitespace.
A semicolon (;
) indicates the start of a line comment.
The comment continues to the end of the line on which the semicolon
appears.
Another way to indicate a comment is to prefix a datum
(cf. section [datumsyntax]) with
#;
and optional whitespace. The comment consists of the
comment prefix #;
, the space, and the datum together. This
notation is useful for “commenting out” sections of code.
Block comments are indicated with properly nested #
and
#
pairs.
#
The FACT procedure computes the factorial
of a nonnegative integer.
#
define fact
(lambda (n)
(if (= n 0)
(#;(= n 1)
1 ;Base case: return 1
* n (fact ( n 1)))))) (
For a description of the notations used for numbers, see section [numbersection].
. + 
These are used in numbers, and can also occur
anywhere in an identifier. A delimited plus or minus sign by itself is
also an identifier. A delimited period (not occurring within a number or
identifier) is used in the notation for pairs (section [listsection]), and to indicate a restparameter
in a formal parameter list (section [lambda]).
Note that a sequence of two or more periods is an
identifier.
( )
Parentheses are used for grouping and to notate
lists (section [listsection]).
'
The apostrophe (single quote) character is used to
indicate literal data (section [quote]).
` The grave accent (backquote) character is used to indicate partly constant data (section [quasiquote]).
, ,@
The character comma and the sequence comma
atsign are used in conjunction with quasiquotation (section [quasiquote]).
"
The quotation mark character is used to delimit
strings (section [stringsection]).
\
Backslash is used in the syntax for character
constants (section [charactersection])
and as an escape character within string constants (section [stringsection]) and identifiers (section [extendedalphas]).
[ ] { }
Left and right square and curly brackets
(braces) are reserved for possible future extensions to the
language.
#
The number sign is used for a variety of purposes
depending on the character that immediately follows it:
#t
#f
These are the boolean constants
(section [booleansection]), along with the
alternatives #true
and #false
.
#\
This introduces a character constant (section [charactersection]).
#(
This introduces a vector constant (section [vectorsection]). Vector constants are
terminated by )
.
#u8(
This introduces a bytevector constant
(section [bytevectorsection]).
Bytevector constants are terminated by )
.
#e #i #b #o #d #x
These are used in the notation for
numbers (section [numbernotations]).
#n= #n#
These are used for labeling and referencing
other literal data (section [labelsection]).
#n=datum
lexicalsyntax
#n#
lexical syntax
The lexical syntax #n=datum
reads the same as datum, but
also results in datum being labelled by n
. It is an error
if n
is not a sequence of digits.
The lexical syntax #n#
serves as a reference to some
object labelled by #n=
; the result is the same object as
the #n=
(see section [equivalencesection]).
Together, these syntaxes permit the notation of structures with shared or circular substructure.
let ((x (list 'a 'b 'c)))
(setcdr! (cddr x) x)
(;; => #0=(a b c . #0#) x)
The scope of a datum label is the portion of the outermost datum in which it appears that is to the right of the label. Consequently, a reference #n# can occur only after a label #n=; it is an error to attempt a forward reference. In addition, it is an error if the reference appears as the labelled object itself (as in #n= #n#), because the object labelled by #n= is not well defined in this case.
It is an error for a program or library to include circular references except in literals. In particular, it is an error for quasiquote (section [quasiquote]) to contain them.
1=(begin (display #\x) #1#)
#;; => error
An identifier can name either a type of syntax or a location where a value can be stored. An identifier that names a type of syntax is called a syntactic keyword and is said to be bound to a transformer for that syntax. An identifier that names a location is called a variable and is said to be bound to that location. The set of all visible bindings in effect at some point in a program is known as the environment in effect at that point. The value stored in the location to which a variable is bound is called the variable’s value. By abuse of terminology, the variable is sometimes said to name the value or to be bound to the value. This is not quite accurate, but confusion rarely results from this practice.
Certain expression types are used to create new kinds of syntax and to bind syntactic keywords to those new syntaxes, while other expression types create new locations and bind variables to those locations. These expression types are called binding constructs.
Those that bind syntactic keywords are listed in section [macrosection]. The most fundamental of the variable binding constructs is the lambda expression, because all other variable binding constructs (except toplevel bindings) can be explained in terms of lambda expressions. The other variable binding constructs are let, let*, letrec, letrec*, letvalues, let*values, and do expressions (see sections [lambda], [letrec], and [do]).
Scheme is a language with block structure. To each place where an identifier is bound in a program there corresponds a region of the program text within which the binding is visible. The region is determined by the particular binding construct that establishes the binding; if the binding is established by a lambda expression, for example, then its region is the entire lambda expression. Every mention of an identifier refers to the binding of the identifier that established the innermost of the regions containing the use. If there is no binding of the identifier whose region contains the use, then the use refers to the binding for the variable in the global environment, if any (chapters [expressionchapter] and [initialenv]); if there is no binding for the identifier, it is said to be unbound.
No object satisfies more than one of the following predicates:
boolean? bytevector?
char? eofobject?
null? number?
pair? port?
procedure? string?
symbol? vector?
and all predicates created by definerecordtype.
These predicates define the types boolean, bytevector, character, the empty list object, eofobject, number, pair, port, procedure, string, symbol, vector, and all record types.
Although there is a separate boolean type, any Scheme value can be used as a boolean value for the purpose of a conditional test. As explained in section [booleansection], all values count as true in such a test except for #f. This report uses the word “true” to refer to any Scheme value except #f, and the word “false” to refer to #f.
An important concept in Scheme (and Lisp) is that of the external
representation of an object as a sequence of characters. For
example, an external representation of the integer 28 is the sequence of
characters “28
”, and an external representation of a list
consisting of the integers 8 and 13 is the sequence of characters
“(8 13)
”.
The external representation of an object is not necessarily unique.
The integer 28 also has representations “#e28.000
” and
“#x1c
”, and the list in the previous paragraph also has the
representations “( 08 13 )
” and
“(8 . (13 . ()))
” (see section [listsection]).
Many objects have standard external representations, but some, such as procedures, do not have standard representations (although particular implementations may define representations for them).
An external representation can be written in a program to obtain the corresponding object (see quote, section [quote]).
External representations can also be used for input and output. The procedure read (section [read]) parses external representations, and the procedure write (section [write]) generates them. Together, they provide an elegant and powerful input/output facility.
Note that the sequence of characters “(+ 2 6)
” is
not an external representation of the integer 8, even though it
is an expression evaluating to the integer 8; rather, it is an
external representation of a threeelement list, the elements of which
are the symbol +
and the integers 2 and 6. Scheme’s syntax
has the property that any sequence of characters that is an expression
is also the external representation of some object. This can lead to
confusion, since it is not always obvious out of context whether a given
sequence of characters is intended to denote data or program, but it is
also a source of power, since it facilitates writing programs such as
interpreters and compilers that treat programs as data (or vice
versa).
The syntax of external representations of various kinds of objects accompanies the description of the primitives for manipulating the objects in the appropriate sections of chapter [initialenv].
Variables and objects such as pairs, strings, vectors, and
bytevectors implicitly denote locations or sequences of locations. A
string, for example, denotes as many locations as there are characters
in the string. A new value can be stored into one of these locations
using the stringset!
procedure, but the string continues
to denote the same locations as before.
An object fetched from a location, by a variable reference or by a
procedure such as car, vectorref, or stringref, is equivalent in the
sense of eqv?
(section [equivalencesection]) to the object last
stored in the location before the fetch.
Every location is marked to show whether it is in use. No variable or object ever refers to a location that is not in use.
Whenever this report speaks of storage being newly allocated for a variable or object, what is meant is that an appropriate number of locations are chosen from the set of locations that are not in use, and the chosen locations are marked to indicate that they are now in use before the variable or object is made to denote them. Notwithstanding this, it is understood that the empty list cannot be newly allocated, because it is a unique object. It is also understood that empty strings, empty vectors, and empty bytevectors, which contain no locations, may or may not be newly allocated.
Every object that denotes locations is either mutable or immutable.
Literal constants, the strings returned by
symbol>string
, and possibly the environment returned by
schemereportenvironment are immutable objects. All objects created by
the other procedures listed in this report are mutable. It is an error
to attempt to store a new value into a location that is denoted by an
immutable object.
These locations are to be understood as conceptual, not physical. Hence, they do not necessarily correspond to memory addresses, and even if they do, the memory address might not be constant.
Rationale: In many systems it is desirable for constants (i.e. the values of literal expressions) to reside in readonly memory. Making it an error to alter constants permits this implementation strategy, while not requiring other systems to distinguish between mutable and immutable objects.
Implementations of Scheme are required to be properly tailrecursive. Procedure calls that occur in certain syntactic contexts defined below are tail calls. A Scheme implementation is properly tailrecursive if it supports an unbounded number of active tail calls. A call is active if the called procedure might still return. Note that this includes calls that might be returned from either by the current continuation or by continuations captured earlier by callwithcurrentcontinuation that are later invoked. In the absence of captured continuations, calls could return at most once and the active calls would be those that had not yet returned. A formal definition of proper tail recursion can be found in .
Rationale:
Intuitively, no space is needed for an active tail call because the continuation that is used in the tail call has the same semantics as the continuation passed to the procedure containing the call. Although an improper implementation might use a new continuation in the call, a return to this new continuation would be followed immediately by a return to the continuation passed to the procedure. A properly tailrecursive implementation returns to that continuation directly.
Proper tail recursion was one of the central ideas in Steele and Sussman’s original version of Scheme. Their first Scheme interpreter implemented both functions and actors. Control flow was expressed using actors, which differed from functions in that they passed their results on to another actor instead of returning to a caller. In the terminology of this section, each actor finished with a tail call to another actor.
Steele and Sussman later observed that in their interpreter the code for dealing with actors was identical to that for functions and thus there was no need to include both in the language.
A tail call is a procedure call that occurs in a tail context. Tail contexts are defined inductively. Note that a tail context is always determined with respect to a particular lambda expression.
The last expression within the body of a lambda expression, shown as tail expression below, occurs in a tail context. The same is true of all the bodies of caselambda expressions. ̄  ̄ (lāmbda formals expression tail expression)
(caselambda (formals tail body))
If one of the following expressions is in a tail context, then the subexpressions shown as tail expression are in a tail context. These were derived from rules in the grammar given in chapter [formalchapter] by replacing some occurrences of body with tail body, some occurrences of expression with tail expression, and some occurrences of sequence with tail sequence. Only those rules that contain tail contexts are shown here.
```scheme (if expression tail expression tail expression)
(if expression tail expression)
(cond cond_clause …)
(cond cond clause … (else tail sequence))
(case expression …)
(case expression (else tail sequence))
(and expression tail expression)
(or expression tail expression)
(when test tail sequence)
(unless test tail sequence)
(let (binding spec) tail body)
(let variable (binding spec) tail body)
(let* (binding spec) tail body)
(letrec (binding spec) tail body)
(letrec* (binding spec) tail body)
(letvalues (mv binding spec) tail body)
(let*values (mv binding spec) tail body)
(letsyntax (syntax spec) tail body)
(letrecsyntax (syntax spec) tail body)
(begin tail sequence)
(do (̄iteration spec) (test tail sequence) )
where
cond clause ⟶ (test tail sequence)
case clause ⟶ ((datum) tail sequence)
tail body ⟶ definition tail sequence tail sequence ⟶ expression tail expression
Certain procedures defined in this report are also required to
perform tail calls. The first argument passed to apply
and
to callwithcurrentcontinuation
, and the second argument
passed to callwithvalues
, must be called via a tail call.
Similarly, eval
must evaluate its first argument as if it
were in tail position within the eval
procedure.
In the following example the only tail call is the call to f. None of the calls to g or h are tail calls. The reference to x is in a tail context, but it is not a call and thus is not a tail call.
lambda ()
(if (g)
(let ((x (h)))
(
x)and (g) (f)))) (
Note: Implementations may recognize that some nontail calls, such as the call to h above, can be evaluated as though they were tail calls. In the example above, the let expression could be compiled as a tail call to h. (The possibility of h returning an unexpected number of values can be ignored, because in that case the effect of the let is explicitly unspecified and implementationdependent.)
Expression types are categorized as primitive or derived. Primitive expression types include variables and procedure calls. Derived expression types are not semantically primitive, but can instead be defined as macros. Suitable syntax definitions of some of the derived expressions are given in section [derivedsection].
The procedures force, promise?, makepromise, and makeparameter are also described in this chapter because they are intimately associated with the delay, delayforce, and parameterize expression types.
variable syntax An expression consisting of a variable (section [variablesection]) is a variable reference. The value of the variable reference is the value stored in the location to which the variable is bound. It is an error to reference an unbound variable.
define x 28)
(;; => 28 x
(quote datum) syntax ’
datum syntax constant
syntax (quote datum) evaluates to datum. Datum can be any external
representation of a Scheme object (see section [externalreps]). This notation is used to
include literal constants in Scheme code.
quote a) ;; => a
(quote #(a b c)) ;; => #(a b c)
(quote (+ 1 2)) ;; => (+ 1 2) (
(quote datum) can be abbreviated as ’
datum. The two
notations are equivalent in all respects.
;; => a
'a ;; => #(a b c)
'#(a b c) ;; => ()
'() + 1 2) ;; => (+ 1 2)
'(quote a) ;; => (quote a)
'(;; => (quote a) ''a
Numerical constants, string constants, character constants, vector constants, bytevector constants, and boolean constants evaluate to themselves; they need not be quoted.
145932 ;; => 145932
'145932 ;; => 145932
"abc" ;; => "abc"
'"abc" ;; => "abc"
#\a ;; => #\a
'#\a ;; => #\a
10) ;; => #(a 10)
'#(a 10) ;; => #(a 10)
#(a 64 65) ;; => #u8(64 65)
'#u8(64 65) ;; => #u8(64 65)
#u8(#t ;; => #t
'#t ;; => #t
As noted in section [storagemodel], it is an error to attempt to alter a constant (i.e. the value of a literal expression) using a mutation procedure like setcar! or stringset!.
(operator operand_{1} … ) syntax A procedure call is written by enclosing in parentheses an expression for the procedure to be called followed by expressions for the arguments to be passed to it. The operator and operand expressions are evaluated (in an unspecified order) and the resulting procedure is passed the resulting arguments.
+ 3 4) ;; => 7
(if #f + *) 3 4) ;; => 12 ((
The procedures in this document are available as the values of variables exported by the standard libraries. For example, the addition and multiplication procedures in the above examples are the values of the variables + and * in the base library. New procedures are created by evaluating lambda expressions (see section [lambda]).
Procedure calls can return any number of values (see
values
in section [proceduresection]). Most of the procedures
defined in this report return one value or, for procedures such as
apply, pass on the values returned by a call to one of their arguments.
Exceptions are noted in the individual descriptions.
Note: In contrast to other dialects of Lisp, the order of evaluation is unspecified, and the operator expression and the operand expressions are always evaluated with the same evaluation rules.
Note: Although the order of evaluation is otherwise unspecified, the effect of any concurrent evaluation of the operator and operand expressions is constrained to be consistent with some sequential order of evaluation. The order of evaluation may be chosen differently for each procedure call.
Note: In many dialects of Lisp, the empty list,
()
, is a legitimate expression evaluating to itself. In
Scheme, it is an error.
(lambda formals body) syntax Syntax: Formals is a formal arguments list as described below, and body is a sequence of zero or more definitions followed by one or more expressions.
Semantics: A lambda expression evaluates to a procedure. The environment in effect when the lambda expression was evaluated is remembered as part of the procedure. When the procedure is later called with some actual arguments, the environment in which the lambda expression was evaluated will be extended by binding the variables in the formal argument list to fresh locations, and the corresponding actual argument values will be stored in those locations. (A fresh location is one that is distinct from every previously existing location.) Next, the expressions in the body of the lambda expression (which, if it contains definitions, represents a letrec* form — see section [letrecstar]) will be evaluated sequentially in the extended environment. The results of the last expression in the body will be returned as the results of the procedure call.
lambda (x) (+ x x)) ;; => a procedure
(lambda (x) (+ x x)) 4) ;; => 8
((
define reversesubtract
(lambda (x y) ( y x)))
(7 10) ;; => 3
(reversesubtract
define add4
(let ((x 4))
(lambda (y) (+ x y))))
(6) ;; => 10 (add4
Formals have one of the following forms:
(variable_1 ...)
: The procedure takes a fixed number
of arguments; when the procedure is called, the arguments will be stored
in fresh locations that are bound to the corresponding
variables.
variable: The procedure takes any number of arguments; when the procedure is called, the sequence of actual arguments is converted into a newly allocated list, and the list is stored in a fresh location that is bound to variable.
(variable_1 ... variable_{n} . variable_{n+1})
: If a
spacedelimited period precedes the last variable, then the procedure
takes n or more arguments, where n is the number of
formal arguments before the period (it is an error if there is not at
least one). The value stored in the binding of the last variable will be
a newly allocated list of the actual arguments left over after all the
other actual arguments have been matched up against the other formal
arguments.
It is an error for a variable to appear more than once in formals.
lambda x x) 3 4 5 6) ;; => (3 4 5 6)
((lambda (x y . z) z) 3 4 5 6) ;; => (5 6) ((
Each procedure created as the result of evaluating a lambda
expression is (conceptually) tagged with a storage location, in order to
make eqv?
and eq?
work on procedures (see
section [equivalencesection]).
(if test consequent alternate)
syntax
(if test consequent)
syntax
Syntax: Test, consequent, and alternate are expressions.
Semantics: An if expression is evaluated as follows: first,
test
is evaluated. If it yields a true value (see
section [booleansection]), then
consequent
is evaluated and its values are returned.
Otherwise alternate
is evaluated and its values are
returned. If test yields a false value and no alternate is specified,
then the result of the expression is unspecified.
if (> 3 2) 'yes 'no) ;; => yes
(if (> 2 3) 'yes 'no) ;; => no
(if (> 3 2)
( 3 2)
(+ 3 2)) ;; => 1 (
(set! variable expression)
syntax
Semantics: Expression is evaluated, and the resulting value is stored in the location to which variable is bound. It is an error if variable is not bound either in some region enclosing the set! expression or else globally. The result of the set! expression is unspecified.
define x 2)
(+ x 1) ;; => 3
(set! x 4) ;; => unspecified
(+ x 1) ;; => 5 (
(include string ...)
syntax
(includeci sitring ... *)
syntax
Semantics: Both include
and
includeci
take one or more filenames expressed as string
literals, apply an implementationspecific algorithm to find
corresponding files, read the contents of the files in the specified
order as if by repeated applications of read, and effectively replace
the include or includeci expression with a begin expression containing
what was read from the files. The difference between the two is that
includeci
reads each file as if it began with the
#!foldcase directive, while include
does not.
Note: Implementations are encouraged to search for files in the directory which contains the including file, and to provide a way for users to specify other directories to search.
The constructs in this section are hygienic, as discussed in section [macrosection]. For reference purposes, section [derivedsection] gives syntax definitions that will convert most of the constructs described in this section into the primitive constructs described in the previous section.
(cond clause ... )
syntax
else
auxiliary syntax
=>
auxiliary syntax
Syntax: Clauses take one of two forms, either
...) (<test> <expression>
where test is any expression, or
=> <expression>) (<test>
The last clause can be an “else clause,” which has the form
else <expression> <expression> ...) (
Semantics: A cond expression is evaluated by evaluating the test expressions of successive clauses in order until one of them evaluates to a true value (see section [booleansection]). When a test evaluates to a true value, the remaining expressions in its clause are evaluated in order, and the results of the last expression in the clause are returned as the results of the entire cond expression.
If the selected clause contains only the test and no expressions,
then the value of the test is returned as the result. If the selected
clause uses the =>
alternate form, then the expression
is evaluated. It is an error if its value is not a procedure that
accepts one argument. This procedure is then called on the value of the
test and the values returned by this procedure are returned by the cond
expression.
If all tests evaluate to #f, and there is no else clause, then the result of the conditional expression is unspecified; if there is an else clause, then its expressions are evaluated in order, and the values of the last one are returned.
cond ((> 3 2) 'greater)
(< 3 2) 'less)) ;; => greater
((
cond ((> 3 3) 'greater)
(< 3 3) 'less)
((else 'equal)) ;; => equal
(
cond ((assv 'b '((a 1) (b 2))) => cadr)
(else #f)) ;; => 2 (
(case key clause ...)
syntax
Syntax: Key can be any expression. Each clause has the form
...) <expression> <expression> ...) ((<datum>
where each datum is an external representation of some object. It is an error if any of the datums are the same anywhere in the expression. Alternatively, a clause can be of the form
...) => <expression>) ((<datum>
The last clause can be an “else clause,” which has one of the forms
else <expression> <expression> ...) (
or
else => <expression>) (
Semantics: A case expression is evaluated as follows. Key is evaluated and its result is compared against each datum. If the result of evaluating key is the same (in the sense of eqv?; see section [eqv?]) to a datum, then the expressions in the corresponding clause are evaluated in order and the results of the last expression in the clause are returned as the results of the case expression.
If the result of evaluating key is different from every datum, then if there is an else clause, its expressions are evaluated and the results of the last are the results of the case expression; otherwise the result of the case expression is unspecified.
If the selected clause or else clause uses the =>
alternate form, then the expression is evaluated. It is an error if its
value is not a procedure accepting one argument. This procedure is then
called on the value of the key and the values returned by this procedure
are returned by the case expression.
case (* 2 3)
(2 3 5 7) 'prime)
((1 4 6 8 9) 'composite)) ;; => composite
((case (car '(c d))
(
((a) 'a);; => unspecified
((b) 'b)) case (car '(c d))
(
((a e i o u) 'vowel)
((w y) 'semivowel)else => (lambda (x) x))) ;; => c (
(and test ... *)
syntax
Semantics: The test expressions are evaluated from left to
right, and if any expression evaluates to #f
(see
section [booleansection]), then
#f
is returned. Any remaining expressions are not
evaluated. If all the expressions evaluate to true values, the values of
the last expression are returned. If there are no expressions, then
#t
is returned.
and (= 2 2) (> 2 1)) ;; => #t
(and (= 2 2) (< 2 1)) ;; => #f
(and 1 2 'c '(f g)) ;; => (f g)
(and) ;; => #t (
(or test .... *)
syntax
Semantics: The test expressions are evaluated from left to
right, and the value of the first expression that evaluates to a true
value (see section [booleansection]) is
returned. Any remaining expressions are not evaluated. If all
expressions evaluate to #f
or if there are no expressions,
then #f
is returned.
or (= 2 2) (> 2 1)) ;; => #t
(or (= 2 2) (< 2 1)) ;; => #t
(or #f #f #f) ;; => #f
(or (memq 'b '(a b c))
(/ 3 0)) ;; => (b c) (
(when test expression ...)
syntax
Syntax: The test is an expression.
Semantics: The test is evaluated, and if it evaluates to a true value, the expressions are evaluated in order. The result of the when expression is unspecified.
= 1 1.0)
(when (display "1")
(display "2")) ;; => unspecified
(;; and prints 12
`(unless test expression …) syntax
Syntax: The test is an expression.
Semantics: The test is evaluated, and if it evaluates to #f, the expressions are evaluated in order. The result of the unless expression is unspecified.
= 1 1.0)
(unless (display "1")
(display "2")) ;; => unspecified
(;; and prints nothing
(condexpand ceclause ...)
syntax
Syntax: The condexpand
expression type
provides a way to statically expand different expressions depending on
the implementation. A ceclause
takes the following
form:
...) (feature requirement expression
The last clause can be an “else clause,” which has the form
else expression ...) (
A feature requirement takes one of the following forms:
feature identifier
(library library name)
(and feature requirement ...)
(or feature requirement ...)
(not feature requirement)
Semantics: Each implementation maintains a list of feature
identifiers which are present, as well as a list of libraries which can
be imported. The value of a feature requirement is determined by
replacing each feature identifier and
(library library name)
on the implementation’s lists with
#t
, and all other feature identifiers and library names
with #f, then evaluating the resulting expression as a Scheme boolean
expression under the normal interpretation of and, or, and not.
A condexpand
is then expanded by evaluating the
feature requirements of successive ceclauses in order until one of them
returns #t
. When a true clause is found, the corresponding
expressions are expanded to a begin, and the remaining clauses are
ignored. If none of the feature requirements evaluate to #t, then if
there is an else clause, its expressions are included. Otherwise, the
behavior of the condexpand
is unspecified. Unlike cond,
condexpand does not depend on the value of any variables.
The exact features provided are implementationdefined, but for portability a core set of features is given in appendix [stdfeatures].
The binding constructs let, let*, letrec, letrec*, letvalues, and let*values give Scheme a block structure, like Algol 60. The syntax of the first four constructs is identical, but they differ in the regions they establish for their variable bindings. In a let expression, the initial values are computed before any of the variables become bound; in a let* expression, the bindings and evaluations are performed sequentially; while in letrec and letrec* expressions, all the bindings are in effect while their initial values are being computed, thus allowing mutually recursive definitions. The letvalues and let*values constructs are analogous to let and let* respectively, but are designed to handle multiplevalued expressions, binding different identifiers to the returned values.
(let bindings body)
syntax
Syntax: Bindings has the form
...) ((<variable> <init>)
where each init is an expression, and body is a sequence of zero or more definitions followed by a sequence of one or more expressions as described in section [lambda]. It is an error for a variable to appear more than once in the list of variables being bound.
Semantics: The inits are evaluated in the current environment (in some unspecified order), the variables are bound to fresh locations holding the results, the body is evaluated in the extended environment, and the values of the last expression of body are returned. Each binding of a variable has body as its region.
let ((x 2) (y 3))
(* x y)) ;; => 6
(
let ((x 2) (y 3))
(let ((x 7)
(+ x y)))
(z (* z x))) ;; => 35 (
See also “named let,” section [namedlet].
(let* bindings body)
syntax
Syntax: Bindings has the form
...) ((<variable> <init>)
and body is a sequence of zero or more definitions followed by one or more expressions as described in section [lambda].
Semantics: The let* binding construct is similar to let, but the bindings are performed sequentially from left to right, and the region of a binding indicated by (variable init) is that part of the let* expression to the right of the binding. Thus the second binding is done in an environment in which the first binding is visible, and so on. The variables need not be distinct.
let ((x 2) (y 3))
(let* ((x 7)
(+ x y)))
(z (* z x))) ;; => 70 (
(letrec bindings body)
syntax
Syntax: Bindings has the form
...) ((<variable> <init>)
and body is a sequence of zero or more definitions followed by one or more expressions as described in section [lambda]. It is an error for a variable to appear more than once in the list of variables being bound.
Semantics: The variables are bound to fresh locations holding unspecified values, the inits are evaluated in the resulting environment (in some unspecified order), each variable is assigned to the result of the corresponding init, the body is evaluated in the resulting environment, and the values of the last expression in body are returned. Each binding of a variable has the entire letrec expression as its region, making it possible to define mutually recursive procedures.
letrec ((even?
(lambda (n)
(if (zero? n)
(#t
odd? ( n 1)))))
(odd?
(lambda (n)
(if (zero? n)
(#f
even? ( n 1))))))
(even? 88))
(;; => #t
One restriction on letrec is very important: if it is not possible to evaluate each init without assigning or referring to the value of any variable, it is an error. The restriction is necessary because letrec is defined in terms of a procedure call where a lambda expression binds the variables to the values of the inits. In the most common uses of letrec, all the inits are lambda expressions and the restriction is satisfied automatically.
(letrec* bindings body)
syntax
Syntax: Bindings has the form
...) ((<variable> <init>)
and body is a sequence of zero or more definitions followed by one or more expressions as described in section [lambda]. It is an error for a variable to appear more than once in the list of variables being bound.
Semantics: The variables are bound to fresh locations, each variable is assigned in lefttoright order to the result of evaluating the corresponding init (interleaving evaluations and assignments), the body is evaluated in the resulting environment, and the values of the last expression in body are returned. Despite the lefttoright evaluation and assignment order, each binding of a variable has the entire letrec* expression as its region, making it possible to define mutually recursive procedures.
If it is not possible to evaluate each init without assigning or referring to the value of the corresponding variable or the variable of any of the bindings that follow it in bindings, it is an error. Another restriction is that it is an error to invoke the continuation of an init more than once.
;; Returns the arithmetic, geometric, and
;; harmonic means of a nested list of numbers
define (means ton)
(letrec*
(
((meanlambda (f g)
(/ (sum g ton) n))))
(f (
(sumlambda (g ton)
(if (null? ton)
(+)
(if (number? ton)
(
(g ton)+ (sum g (car ton))
(cdr ton)))))))
(sum g (lambda (x) 1) ton)))
(n (sum (values (mean values values)
(exp log)
(mean / /)))) (mean
Evaluating (means ’(3 (1 4)))
returns three values:
8/3
, 2.28942848510666
(approximately), and
36/19
.
(letvalues mv binding spec body)
syntax
Syntax: Mv binding spec has the form
...) ((<formals> <init>)
where each init is an expression, and body is zero or more definitions followed by a sequence of one or more expressions as described in section [lambda]. It is an error for a variable to appear more than once in the set of formals.
Semantics: The inits are evaluated in the current environment (in some unspecified order) as if by invoking callwithvalues, and the variables occurring in the formals are bound to fresh locations holding the values returned by the inits, where the formals are matched to the return values in the same way that the formals in a lambda expression are matched to the arguments in a procedure call. Then, the body is evaluated in the extended environment, and the values of the last expression of body are returned. Each binding of a variable has body as its region.
It is an error if the formals do not match the number of values returned by the corresponding init.
letvalues (((root rem) (exactintegersqrt 32)))
(* root rem)) ;; => 35 (
(let*values mv binding spec body)
syntax
Syntax: Mv binding spec has the form
...) ((<formals> <init>)
and body is a sequence of zero or more definitions followed by one or more expressions as described in section [lambda]. In each formals, it is an error if any variable appears more than once.
Semantics: The let*values construct is similar to letvalues, but the inits are evaluated and bindings created sequentially from left to right, with the region of the bindings of each formals including the inits to its right as well as body. Thus the second init is evaluated in an environment in which the first set of bindings is visible and initialized, and so on.
let ((a 'a) (b 'b) (x 'x) (y 'y))
(let*values (((a b) (values x y))
(values a b)))
((x y) (list a b x y))) ;; => (x y x y) (
Both of Scheme’s sequencing constructs are named begin, but the two have slightly different forms and uses:
(begin expressionordefinition ...)
syntax
This form of begin can appear as part of a body, or at the outermost level of a program, or at the REPL, or directly nested in a begin that is itself of this form. It causes the contained expressions and definitions to be evaluated exactly as if the enclosing begin construct were not present.
Rationale: This form is commonly used in the output of macros (see section [macrosection]) which need to generate multiple definitions and splice them into the context in which they are expanded.
(begin expression ...)
syntax
This form of begin can be used as an ordinary expression. The expressions are evaluated sequentially from left to right, and the values of the last expression are returned. This expression type is used to sequence side effects such as assignments or input and output.
define x 0)
(
and (= x 0)
(begin (set! x 5)
(+ x 1))) ;; => 6
(
begin (display "4 plus 1 equals ")
(display (+ 4 1))) ;; => unspecified
(;; and prints 4 plus 1 equals 5
Note that there is a third form of begin used as a library declaration: see section [librarydeclarations].
(do ((variable<sub>1</sub> init<sub>1</sub> step<sub>1</sub>) ...) (test expression ...) command ...)
syntax
Syntax: All of init, step, test, and command are expressions.
Semantics: A do expression is an iteration construct. It specifies a set of variables to be bound, how they are to be initialized at the start, and how they are to be updated on each iteration. When a termination condition is met, the loop exits after evaluating the expressions.
A do expression is evaluated as follows: The init expressions are evaluated (in some unspecified order), the variables are bound to fresh locations, the results of the init expressions are stored in the bindings of the variables, and then the iteration phase begins.
Each iteration begins by evaluating test; if the result is false (see section [booleansection]), then the command expressions are evaluated in order for effect, the step expressions are evaluated in some unspecified order, the variables are bound to fresh locations, the results of the steps are stored in the bindings of the variables, and the next iteration begins.
If test evaluates to a true value, then the expressions are evaluated from left to right and the values of the last expression are returned. If no expressions are present, then the value of the do expression is unspecified.
The region of the binding of a variable consists of the entire do expression except for the inits. It is an error for a variable to appear more than once in the list of do variables.
A step can be omitted, in which case the effect is the same as if (variable init variable) had been written instead of (variable init).
do ((vec (makevector 5))
(0 (+ i 1)))
(i = i 5) vec)
((vectorset! vec i i)) ;; => #(0 1 2 3 4)
(
let ((x '(1 3 5 7 9)))
(do ((x x (cdr x))
(0 (+ sum (car x))))
(sum null? x) sum))) ;; => 25 ((
(let bindings body ...)
syntax
Semantics: “Named let” is a variant on the syntax of
let
which provides a more general looping construct than do
and can also be used to express recursion. It has the same syntax and
semantics as ordinary let except that variable is bound within body to a
procedure whose formal arguments are the bound variables and whose body
is body. Thus the execution of body can be repeated by invoking the
procedure named by variable.
let loop ((numbers '(3 2 1 6 5))
(
(nonneg '())
(neg '()))cond ((null? numbers) (list nonneg neg))
(>= (car numbers) 0)
((cdr numbers)
(loop (cons (car numbers) nonneg)
(
neg))< (car numbers) 0)
((cdr numbers)
(loop (
nonnegcons (car numbers) neg)))))
(;; => ((6 1 3) (5 2))
(delay expression)
lazy library syntax
Semantics: The delay construct is used together with the
procedure force
to implement lazy evaluation or
call by need. (delay expression)
returns an object
called a promise which at some point in the future can be asked
(by the force procedure) to evaluate expression, and deliver the
resulting value.
The effect of expression returning multiple values is unspecified.
(delayforce expression)
lazy library syntax
Semantics: The expression
(delayforce *expression*)
is conceptually similar to
(delay (force *expression*))
, with the difference that
forcing the result of delayforce will in effect result in a tail call
to (force *expression*)
, while forcing the result of
(delay (force *expression*))
might not. Thus iterative lazy
algorithms that might result in a long series of chains of
delay
and force
can be rewritten using
delayforce
to prevent consuming unbounded space during
evaluation.
(force *promise*)
lazy library procedure
The force procedure forces the value of a promise
created by delay
, delayforce
, or
makepromise
. If no value has been computed for the
promise, then a value is computed and returned. The value of the promise
must be cached (or “memoized”) so that if it is forced a second time,
the previously computed value is returned. Consequently, a delayed
expression is evaluated using the parameter values and exception handler
of the call to force which first requested its value. If
promise
is not a promise, it may be returned unchanged.
force (delay (+ 1 2))) ;; => 3
(let ((p (delay (+ 1 2))))
(list (force p) (force p)))
(;; => (3 3)
define integers
(letrec ((next
(lambda (n)
(cons n (next (+ n 1)))))))
(delay (0)))
(next define head
(lambda (stream) (car (force stream))))
(define tail
(lambda (stream) (cdr (force stream))))
(
(head (tail (tail integers)));; => 2
The following example is a mechanical transformation of a lazy streamfiltering algorithm into Scheme. Each call to a constructor is wrapped in delay, and each argument passed to a deconstructor is wrapped in force. The use of (delayforce …) instead of (delay (force …)) around the body of the procedure ensures that an evergrowing sequence of pending promises does not exhaust available storage, because force will in effect force such sequences iteratively.
define (streamfilter p? s)
(
(delayforceif (null? (force s))
(
(delay '())let ((h (car (force s)))
(cdr (force s))))
(t (if (p? h)
(cons h (streamfilter p? t)))
(delay (
(streamfilter p? t))))))
odd? integers))))
(head (tail (tail (streamfilter ;; => 5
The following examples are not intended to illustrate good programming style, as delay, force, and delayforce are mainly intended for programs written in the functional style. However, they do illustrate the property that only one value is computed for a promise, no matter how many times it is forced.
define count 0)
(define p
(begin (set! count (+ count 1))
(delay (if (> count x)
(
countforce p)))))
(define x 5)
(;; => a promise
p force p) ;; => 6
(;; => a promise, still
p begin (set! x 10)
(force p)) ;; => 6 (
Various extensions to this semantics of delay, force and delayforce are supported in some implementations:
Calling force on an object that is not a promise may simply return the object.
It may be the case that there is no means by which a promise can
be operationally distinguished from its forced value. That is,
expressions like the following may evaluate to either #t
or
to #f, depending on the implementation:
eqv? (delay 1) 1) ;; => unspecified
(pair? (delay (cons 1 2))) ;; => unspecified (
Implementations may implement “implicit forcing,” where the value of a promise is forced by procedures that operate only on arguments of a certain type, like cdr and *. However, procedures that operate uniformly on their arguments, like list, must not force them.
+ (delay (* 3 7)) 13) ;; => unspecified
(car
(list (delay (* 3 7)) 13)) ;; => a promise (
(promise? obj)
lazy library procedure
The promise? procedure returns #t
if its argument is a
promise, and #f otherwise. Note that promises are not necessarily
disjoint from other Scheme types such as procedures.
(makepromise obj)
lazy library procedure
The makepromise procedure returns a promise which, when forced, will
return obj
. It is similar to delay, but does not delay its
argument: it is a procedure rather than syntax. If obj
is
already a promise, it is returned.
The dynamic extent of a procedure call is the time between when it is initiated and when it returns. In Scheme, callwithcurrentcontinuation (section [continuations]) allows reentering a dynamic extent after its procedure call has returned. Thus, the dynamic extent of a call might not be a single, continuous time period.
This sections introduces parameter objects, which can be bound to new values for the duration of a dynamic extent. The set of all parameter bindings at a given time is called the dynamic environment.
(makeparameter init)
procedure
(makeparameter init converter)
procedure
Returns a newly allocated parameter object, which is a procedure that
accepts zero arguments and returns the value associated with the
parameter object. Initially, this value is the value of
(converter
init
), or of init
if
the conversion procedure converter
is not specified. The
associated value can be temporarily changed using parameterize, which is
described below.
The effect of passing arguments to a parameter object is implementationdependent.
(parameterize ((param value) …)) syntax
Syntax: Both param and value are expressions.
It is an error if the value of any param expression is not a parameter object.
Semantics: A parameterize expression is used to change the values returned by specified parameter objects during the evaluation of the body.
The param and value expressions are evaluated in an unspecified order. The body is evaluated in a dynamic environment in which calls to the parameters return the results of passing the corresponding values to the conversion procedure specified when the parameters were created. Then the previous values of the parameters are restored without passing them to the conversion procedure. The results of the last expression in the body are returned as the results of the entire parameterize expression.
Note: If the conversion procedure is not idempotent, the
results of (parameterize ((x (x))) …), which appears to bind the
parameter x
to its current value, might not be what the
user expects.
If an implementation supports multiple threads of execution, then parameterize must not change the associated values of any parameters in any thread other than the current thread and threads created inside body.
Parameter objects can be used to specify configurable settings for a computation without the need to pass the value to every procedure in the call chain explicitly.
define radix
(
(makeparameter10
lambda (x)
(if (and (exactinteger? x) (<= 2 x 16))
(
xerror "invalid radix")))))
(
define (f n) (number>string n (radix)))
(
12) ;; => "12"
(f 2))
(parameterize ((radix 12)) ;; => "1100"
(f 12) ;; => "12"
(f
16) ;; => unspecified
(radix
0))
(parameterize ((radix 12)) ;; => error (f
(guard (variable cond_clause …) express …)` syntax
Syntax: Each cond_clause
is as in the
specification of cond
.
Semantics: The body is evaluated with an exception handler
that binds the raised object (see raise
in section [exceptionsection]) to variable and, within
the scope of that binding, evaluates the clauses as if they were the
clauses of a cond expression. That implicit cond expression is evaluated
with the continuation and dynamic environment of the guard expression.
If every cond clause’s test evaluates to #f
and there is no
else clause, then raisecontinuable is invoked on the raised object
within the dynamic environment of the original call to raise or
raisecontinuable, except that the current exception handler is that of
the guard expression.
See section [exceptionsection] for a more complete discussion of exceptions.
guard (condition
(assq 'a condition) => cdr)
((assq 'b condition)))
((raise (list (cons 'a 42))))
(;; => 42
guard (condition
(assq 'a condition) => cdr)
((assq 'b condition)))
((raise (list (cons 'b 23))))
(;; => (b . 23)
(quasiquote qq template)
syntax
qq_template
syntax
unquote
auxiliary syntax
'
auxiliary syntax
unquotesplicing
auxiliary syntax
` auxiliary syntax
“Quasiquote” expressions are useful for constructing a list or vector
structure when some but not all of the desired structure is known in
advance. If no commas appear within the qq template, the result of
evaluating
`qq template is equivalent to the result of evaluating
’qq template. If a comma appears within the qq template, however, the expression following the comma is evaluated (“unquoted”) and its result is inserted into the structure instead of the comma and the expression. If a comma appears followed without intervening whitespace by a commercial atsign (
’`),
then it is an error if the following expression does not evaluate to a
list; the opening and closing parentheses of the list are then “stripped
away” and the elements of the list are inserted in place of the comma
atsign expression sequence. A comma atsign normally appears only
within a list or vector qq template.
Note: In order to unquote an identifier beginning with @, it is necessary to use either an explicit unquote or to put whitespace after the comma, to avoid colliding with the comma atsign sequence.
list ,(+ 1 2) 4) ;; => (list 3 4)
`(let ((name 'a)) `(list ,name ',name))
(;; => (list a (quote a))
+ 1 2) ,@(map abs '(4 5 6)) b)
`(a ,(;; => (a 3 4 5 6 b)
 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
`((foo ,(;; => ((foo 7) . cons)
10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
`#(;; => #(10 5 2 4 3 8)
let ((foo '(foo bar)) (@baz 'baz))
(list ,@foo , @baz))
`(;; => (list foo bar baz)
Quasiquote expressions can be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost quasiquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation.
+ 1 2) ,(foo ,(+ 1 3) d) e) f)
`(a `(b ,(;; => (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
let ((name1 'x)
(
(name2 'y))
`(a `(b ,,name1 ,',name2 d) e));; => (a `(b ,x ,'y d) e)
A quasiquote expression may return either newly allocated, mutable objects or literal structure for any structure that is constructed at run time during the evaluation of the expression. Portions that do not need to be rebuilt are always literal. Thus,
let ((a 3)) `((1 2) ,a ,4 ,'five 6)) (
may be treated as equivalent to either of the following expressions:
1 2) 3 4 five 6)
`((
let ((a 3))
(cons '(1 2)
(cons a (cons 4 (cons 'five '(6)))))) (
However, it is not equivalent to this expression:
let ((a 3)) (list (list 1 2) a 4 'five 6)) (
The two notations `qq template and
(quasiquote
qq template)are identical in all respects. ,expression is identical to (unquote expression), and ,@expression is identical to (unquotesplicing expression). The
write`
procedure may output either format.
quasiquote (list (unquote (+ 1 2)) 4))
(;; => (list 3 4)
quasiquote (list (unquote (+ 1 2)) 4))
'(;; => `(list ,(+ 1 2) 4)
;; i.e., (quasiquote (list (unquote (+ 1 2)) 4))
It is an error if any of the identifiers quasiquote, unquote, or unquotesplicing appear in positions within a qq template otherwise than as described above.
(caselambda clause ...)
caselambda library syntax
Syntax: Each clause is of the form (formals body), where formals and body have the same syntax as in a lambda expression.
Semantics: A caselambda expression evaluates to a procedure that accepts a variable number of arguments and is lexically scoped in the same manner as a procedure resulting from a lambda expression. When the procedure is called, the first clause for which the arguments agree with formals is selected, where agreement is specified as for the formals of a lambda expression. The variables of formals are bound to fresh locations, the values of the arguments are stored in those locations, the body is evaluated in the extended environment, and the results of body are returned as the results of the procedure call.
It is an error for the arguments not to agree with the formals of any clause.
define range
(caselambda
(0 e))
((e) (range do ((r '() (cons e r))
((b e) ( e 1) ( e 1)))
(e (< e b) r)))))
((
3) ;; => (0 1 2)
(range 3 5) ;; => (3 4) (range
Scheme programs can define and use new derived expression types, called macros. Programdefined expression types have the syntax
...) (<keyword> <datum>
where keyword is an identifier that uniquely determines the
expression type. This identifier is called the syntactic
keyword, or simply keyword
, of the macro. The number
of the datums, and their syntax, depends on the expression type.
Each instance of a macro is called a use of the macro. The
set of rules that specifies how a use of a macro is transcribed into a
more primitive expression is called the transformer
of the
macro.
The macro definition facility consists of two parts:
A set of expressions used to establish that certain identifiers are macro keywords, associate them with macro transformers, and control the scope within which a macro is defined, and
a pattern language for specifying macro transformers.
The syntactic keyword of a macro can shadow variable bindings, and local variable bindings can shadow syntactic bindings. Two mechanisms are provided to prevent unintended conflicts:
If a macro transformer inserts a binding for an identifier (variable or keyword), the identifier will in effect be renamed throughout its scope to avoid conflicts with other identifiers. Note that a global variable definition may or may not introduce a binding; see section [defines].
If a macro transformer inserts a free reference to an identifier, the reference refers to the binding that was visible where the transformer was specified, regardless of any local bindings that surround the use of the macro.
In consequence, all macros defined using the pattern language are “hygienic” and “referentially transparent” and thus preserve Scheme’s lexical scoping.
Implementations may provide macro facilities of other types.
The letsyntax and letrecsyntax binding constructs are analogous to let and letrec, but they bind syntactic keywords to macro transformers instead of binding variables to locations that contain values. Syntactic keywords can also be bound globally or locally with definesyntax; see section [definesyntax].
(letsyntax bindings body)
syntax
Syntax: Bindings has the form
...) ((<keyword> <transformerspec>)
Each keyword is an identifier, each transformer spec is an instance of syntaxrules, and body is a sequence of zero or more definitions followed by one or more expressions. It is an error for a keyword to appear more than once in the list of keywords being bound.
Semantics: The body is expanded in the syntactic environment obtained by extending the syntactic environment of the letsyntax expression with macros whose keywords are the keywords, bound to the specified transformers. Each binding of a keyword has body as its region.
letsyntax ((giventhat (syntaxrules ()
(...)
((giventhat test stmt1 stmt2 if test
(begin stmt1
(...))))))
stmt2 let ((if #t))
(if (set! if 'now))
(giventhat if)) ;; => now
let ((x 'outer))
(letsyntax ((m (syntaxrules () ((m) x))))
(let ((x 'inner))
(;; => outer (m))))
(letrecsyntax bindings body)
syntax
Syntax: Same as for letsyntax.
Semantics: The body is expanded in the syntactic environment obtained by extending the syntactic environment of the letrecsyntax expression with macros whose keywords are the keywords, bound to the specified transformers. Each binding of a keyword has the transformer specs as well as the body within its region, so the transformers can transcribe expressions into uses of the macros introduced by the letrecsyntax expression.
letrecsyntax
(syntaxrules ()
((myor (#f)
((myor)
((myor e) e)...)
((myor e1 e2 let ((temp e1))
(if temp
(
temp...)))))))
(myor e2 let ((x #f)
(7)
(y 8)
(temp let odd?)
(if even?))
(
(myor xlet temp)
(if y)
(;; => 7 y)))
A transformer spec has one of the following forms:
scheme TODO FIXME > `(syntaxrules (pattern literal … )` *syntax* ` ...) ` (syntaxrules ellipsis (pattern literal … ) syntax ` ...)` \_ auxiliary syntax … auxiliary syntax
Syntax: It is an error if any of the pattern literals, or the ellipsis in the second form, is not an identifier. It is also an error if syntax rule is not of the form
(<pattern> <template>)
The pattern in a syntax rule is a list pattern whose first element is an identifier.
A pattern is either an identifier, a constant, or one of the following
...)
(<pattern> ... . <pattern>)
(<pattern> <pattern> ... <pattern> ... <pattern> ...)
(<pattern> ... <pattern> ... <pattern> ...
(<pattern> . <pattern>)
...)
#(<pattern> ... <pattern> ... <pattern> ...) #(<pattern>
and a template is either an identifier, a constant, or one of the following
...)
(<element> ... . <template>)
(<element> <element> ... <template>)
(...) #(<element>
where an element is a template optionally followed by an ellipsis. An ellipsis is the identifier specified in the second form of syntaxrules, or the default identifier … (three consecutive periods) otherwise.
Semantics: An instance of syntaxrules produces a new macro transformer by specifying a sequence of hygienic rewrite rules. A use of a macro whose keyword is associated with a transformer specified by syntaxrules is matched against the patterns contained in the syntax rules, beginning with the leftmost syntax rule. When a match is found, the macro use is transcribed hygienically according to the template.
An identifier appearing within a pattern can be an underscore (_), a literal identifier listed in the list of pattern literals, or the ellipsis. All other identifiers appearing within a pattern are pattern variables.
The keyword at the beginning of the pattern in a syntax rule is not involved in the matching and is considered neither a pattern variable nor a literal identifier.
Pattern variables match arbitrary input elements and are used to refer to elements of the input in the template. It is an error for the same pattern variable to appear more than once in a pattern.
Underscores also match arbitrary input elements but are not pattern variables and so cannot be used to refer to those elements. If an underscore appears in the pattern literals list, then that takes precedence and underscores in the pattern match as literals. Multiple underscores can appear in a pattern.
Identifiers that appear in (pattern literal … ) are interpreted as literal identifiers to be matched against corresponding elements of the input. An element in the input matches a literal identifier if and only if it is an identifier and either both its occurrence in the macro expression and its occurrence in the macro definition have the same lexical binding, or the two identifiers are the same and both have no lexical binding.
A subpattern followed by ellipsis can match zero or more elements of the input, unless ellipsis appears in the pattern literals, in which case it is matched as a literal.
More formally, an input expression E matches a pattern P if and only if:
P is an underscore (_).
P is a nonliteral identifier; or
P is a literal identifier and E is an identifier with the same binding; or
P is a list (P_{1} … P_{n}) and E is a list of n elements that match P_{1} through P_{n}, respectively; or
P is an improper list (P_{1} P_{2} … P_{n} . P_{n + 1}) and E is a list or improper list of n or more elements that match P_{1} through P_{n}, respectively, and whose nth tail matches P_{n + 1}; or
P is of the form (P_{1} … P_{k} P_{e} ellipsis P_{m + 1} … P_{n}) where E is a proper list of n elements, the first k of which match P_{1} through P_{k}, respectively, whose next m − k elements each match P_{e}, whose remaining n − m elements match P_{m + 1} through P_{n}; or
P is of the form (P_{1} … P_{k} P_{e} ellipsis P_{m + 1} … P_{n} . P_{x}) where E is a list or improper list of n elements, the first k of which match P_{1} through P_{k}, whose next m − k elements each match P_{e}, whose remaining n − m elements match P_{m + 1} through P_{n}, and whose nth and final cdr matches P_{x}; or
P is a vector of the form #(P_{1} … P_{n}) and E is a vector of n elements that match P_{1} through P_{n}; or
P is of the form #(P_{1} … P_{k} P_{e} ellipsis P_{m + 1} … P_{n}) where E is a vector of n elements the first k of which match P_{1} through P_{k}, whose next m − k elements each match P_{e}, and whose remaining n − m elements match P_{m + 1} through P_{n}; or
P is a constant and E is equal to P in the sense of the equal? procedure.
It is an error to use a macro keyword, within the scope of its binding, in an expression that does not match any of the patterns.
When a macro use is transcribed according to the template of the matching syntax rule, pattern variables that occur in the template are replaced by the elements they match in the input. Pattern variables that occur in subpatterns followed by one or more instances of the identifier ellipsis are allowed only in subtemplates that are followed by as many instances of ellipsis. They are replaced in the output by all of the elements they match in the input, distributed as indicated. It is an error if the output cannot be built up as specified.
Identifiers that appear in the template but are not pattern variables or the identifier ellipsis are inserted into the output as literal identifiers. If a literal identifier is inserted as a free identifier then it refers to the binding of that identifier within whose scope the instance of syntaxrules appears. If a literal identifier is inserted as a bound identifier then it is in effect renamed to prevent inadvertent captures of free identifiers.
A template of the form (ellipsis template) is identical to template, except that ellipses within the template have no special meaning. That is, any ellipses contained within template are treated as ordinary identifiers. In particular, the template (ellipsis ellipsis) produces a single ellipsis. This allows syntactic abstractions to expand into code containing ellipses.
definesyntax belikebegin
(syntaxrules ()
(
((belikebegin name)definesyntax name
(syntaxrules ()
(... ...))
((name expr (begin expr (... ...))))))))
(
(belikebegin sequence)1 2 3 4) ;; => 4 (sequence
As an example, if let
and cond
are defined
as in section [derivedsection] then they
are hygienic (as required) and the following is not an error.
let ((=> #f))
(cond (#t => 'ok))) ;; => ok (
The macro transformer for cond recognizes => as a local variable, and hence an expression, and not as the base identifier =>, which the macro transformer treats as a syntactic keyword. Thus the example expands into
let ((=> #f))
(if #t (begin => 'ok))) (
instead of
let ((=> #f))
(let ((temp #t))
(if temp ('ok temp)))) (
which would result in an invalid procedure call.
(syntaxerror message args … )
syntax
syntaxerror behaves similarly to error ([exceptionsection]) except that implementations with an expansion pass separate from evaluation should signal an error as soon as syntaxerror is expanded. This can be used as a syntaxrules template for a pattern that is an invalid use of the macro, which can provide more descriptive error messages. message is a string literal, and args arbitrary expressions providing additional information. Applications cannot count on being able to catch syntax errors with exception handlers or guards.
definesyntax simplelet
(syntaxrules ()
(_ (head ... ((x . y) val) . tail)
((...)
body1 body2
(syntaxerror"expected an identifier but got"
. y)))
(x _ ((name val) ...) body1 body2 ...)
((lambda (name ...) body1 body2 ...)
((...)))) val
A Scheme program consists of one or more import declarations followed by a sequence of expressions and definitions. Import declarations specify the libraries on which a program or library depends; a subset of the identifiers exported by the libraries are made available to the program. Expressions are described in chapter [expressionchapter]. Definitions are either variable definitions, syntax definitions, or recordtype definitions, all of which are explained in this chapter. They are valid in some, but not all, contexts where expressions are allowed, specifically at the outermost level of a program and at the beginning of a body.
At the outermost level of a program,
(begin expression or definition_1 ...)
is equivalent to the
sequence of expressions and definitions in the begin
.
Similarly, in a body, (begin definition_1 ...)
is
equivalent to the sequence definition_{1} … . Macros can expand
into such begin forms. For the formal definition, see [sequencing].
Import declarations and definitions cause bindings to be created in the global environment or modify the value of existing global bindings. The initial environment of a program is empty, so at least one import declaration is needed to introduce initial bindings.
Expressions occurring at the outermost level of a program do not create any bindings. They are executed in order when the program is invoked or loaded, and typically perform some kind of initialization.
Programs and libraries are typically stored in files, although in some implementations they can be entered interactively into a running Scheme system. Other paradigms are possible. Implementations which store libraries in files should document the mapping from the name of a library to its location in the file system.
An import declaration takes the following form:
...) (import <importset>
An import declaration provides a way to import identifiers exported by a library. Each import set names a set of bindings from a library and possibly specifies local names for the imported bindings. It takes one of the following forms:
library name
(only import set identifier ...)
(except import set identifier ...)
(prefix import set identifier)
(rename import set (identifier_1 identifier_2) ...)
In the first form, all of the identifiers in the named library’s
export clauses are imported with the same names (or the exported names
if exported with rename
). The additional import set forms
modify this set as follows:
only
produces a subset of the given import set
including only the listed identifiers (after any renaming). It is an
error if any of the listed identifiers are not found in the original
set.
except
produces a subset of the given import set,
excluding the listed identifiers (after any renaming). It is an error if
any of the listed identifiers are not found in the original
set.
rename
modifies the given import set, replacing each
instance of identifier_{1} with identifier_{2}. It is an
error if any of the listed identifier_{1}s are not found in the
original set.
prefix
automatically renames all identifiers in the
given import set, prefixing each with the specified identifier.
In a program or library declaration, it is an error to import the same identifier more than once with different bindings, or to redefine or mutate an imported binding with a definition or with set!, or to refer to an identifier before it is imported. However, a REPL should permit these actions.
A variable definition binds one or more identifiers and specifies an initial value for each of them. The simplest kind of variable definition takes one of the following forms:
(define variable expression)
(define (variable formals) body)
Formals are either a sequence of zero or more variables, or a sequence of one or more variables followed by a spacedelimited period and another variable (as in a lambda expression). This form is equivalent to
define <variable>
(lambda (<formals>) <body>)) (
(define (variable . formal) body)
Formal is a single variable. This form is equivalent to
define <variable>
(lambda <formal> <body>)) (
At the outermost level of a program, a definition
define <variable> <expression>) (
has essentially the same effect as the assignment expression
set! <variable> <expression>) (
if variable is bound to a nonsyntax value. However, if variable is not bound, or is a syntactic keyword, then the definition will bind variable to a new location before performing the assignment, whereas it would be an error to perform a set! on an unbound variable.
define add3
(lambda (x) (+ x 3)))
(3) ;; => 6
(add3 define first car)
(1 2)) ;; => 1 (first '(
Definitions can occur at the beginning of a body (that is, the body
of a lambda
, let
, let*
,
letrec
, letrec*
, letvalues
,
let*values
, letsyntax
,
letrecsyntax
, parameterize
,
guard
, or caselambda
). Note that such a body
might not be apparent until after expansion of other syntax. Such
definitions are known as internal definitions as opposed to the
global definitions described above. The variables defined by internal
definitions are local to the body. That is, variable is bound rather
than assigned, and the region of the binding is the entire body. For
example,
let ((x 5))
(define foo (lambda (y) (bar x y)))
(define bar (lambda (a b) (+ (* a b) a)))
(+ x 3))) ;; => 45 (foo (
An expanded body containing internal definitions can always be converted into a completely equivalent letrec* expression. For example, the let expression in the above example is equivalent to
let ((x 5))
(letrec* ((foo (lambda (y) (bar x y)))
(lambda (a b) (+ (* a b) a))))
(bar (+ x 3)))) (foo (
Just as for the equivalent letrec* expression, it is an error if it is not possible to evaluate each expression of every internal definition in a body without assigning or referring to the value of the corresponding variable or the variable of any of the definitions that follow it in body.
It is an error to define the same identifier more than once in the same body.
Wherever an internal definition can occur,
(begin definition_1 ...)
is equivalent to the sequence of
definitions that form the body of the begin
.
Another kind of definition is provided by definevalues, which creates multiple definitions from a single expression returning multiple values. It is allowed wherever define is allowed.
(definevalues formals expression) syntax
It is an error if a variable appears more than once in the set of formals.
Semantics: Expression is evaluated, and the formals are bound to the return values in the same way that the formals in a lambda expression are matched to the arguments in a procedure call.
exactintegersqrt 17))
(definevalues (x y) (list x y) ;; => (4 1)
(
let ()
(values 1 2))
(definevalues (x y) (+ x y)) ;; => 3 (
Syntax definitions have this form:
definesyntax keyword transformer spec) (
Keyword is an identifier, and the transformer spec is an instance of
syntaxrules
. Like variable definitions, syntax definitions
can appear at the outermost level or nested within a
body
.
If the definesyntax occurs at the outermost level, then the global syntactic environment is extended by binding the keyword to the specified transformer, but previous expansions of any global binding for keyword remain unchanged. Otherwise, it is an internal syntax definition, and is local to the body in which it is defined. Any use of a syntax keyword before its corresponding definition is an error. In particular, a use that precedes an inner definition will not apply an outer definition.
let ((x 1) (y 2))
(definesyntax swap!
(syntaxrules ()
(
((swap! a b)let ((tmp a))
(set! a b)
(set! b tmp)))))
(
(swap! x y)list x y)) ;; => (2 1) (
Macros can expand into definitions in any context that permits them. However, it is an error for a definition to define an identifier whose binding has to be known in order to determine the meaning of the definition itself, or of any preceding definition that belongs to the same group of internal definitions. Similarly, it is an error for an internal definition to define an identifier whose binding has to be known in order to determine the boundary between the internal definitions and the expressions of the body it belongs to. For example, the following are errors:
define define 3)
(
begin (define begin list))
(
letsyntax
(syntaxrules ()
((foo (...) body ...)
((foo (proc args define proc
(lambda (args ...)
(...))))))
body let ((x 3))
(+ x y))
(foo (plus x y) (define foo x)
( (plus foo x)))
Recordtype definitions are used to introduce new data types, called record types. Like other definitions, they can appear either at the outermost level or in a body. The values of a record type are called records and are aggregations of zero or more fields, each of which holds a single location. A predicate, a constructor, and field accessors and mutators are defined for each record type.
(definerecordtype name ... TODO FIXME)
syntax
Syntax: name and pred are identifiers. The constructor is of the form
...) (<constructorename> <fieldname>
and each field is either of the form
(<fieldname> <accessorname>)
or of the form
(<fieldname> <accessorname> <modifiedname>)
It is an error for the same identifier to occur more than once as a field name. It is also an error for the same identifier to occur more than once as an accessor or mutator name.
The definerecordtype construct is generative: each use creates a new record type that is distinct from all existing types, including Scheme’s predefined types and other record types — even record types of the same name or structure.
An instance of definerecordtype is equivalent to the following definitions:
name is bound to a representation of the record type itself. This may be a runtime object or a purely syntactic representation. The representation is not utilized in this report, but it serves as a means to identify the record type for use by further language extensions.
constructor name is bound to a procedure that takes as many arguments as there are field names in the (constructor name … ) subexpression and returns a new record of type name. Fields whose names are listed with constructor name have the corresponding argument as their initial value. The initial values of all other fields are unspecified. It is an error for a field name to appear in constructor but not as a field name.
pred is bound to a predicate that returns #t
when
given a value returned by the procedure bound to constructor name and
#f
for everything else.
Each accessor name is bound to a procedure that takes a record of type name and returns the current value of the corresponding field. It is an error to pass an accessor a value which is not a record of the appropriate type.
Each modifier name is bound to a procedure that takes a record of type name and a value which becomes the new value of the corresponding field; an unspecified value is returned. It is an error to pass a modifier a first argument which is not a record of the appropriate type.
For instance, the following recordtype definition
definerecordtype <pare>
(
(kons x y)
pare?
(x kar setkar!) (y kdr))
defines kons to be a constructor, kar and kdr to be accessors, setkar! to be a modifier, and pare? to be a predicate for instances of <pare>.
1 2)) ;; => #t
(pare? (kons cons 1 2)) ;; => #f
(pare? (1 2)) ;; => 1
(kar (kons 1 2)) ;; => 2
(kdr (kons let ((k (kons 1 2)))
(3)
(setkar! k ;; => 3 (kar k))
Libraries provide a way to organize Scheme programs into reusable parts with explicitly defined interfaces to the rest of the program. This section defines the notation and semantics for libraries.
A library definition takes the following form:
(definelibrary <libraryname>...) <librarydeclaration>
library name is a list whose members are identifiers and exact
nonnegative integers. It is used to identify the library uniquely when
importing from other programs or libraries. Libraries whose first
identifier is scheme are reserved for use by this report and future
versions of this report. Libraries whose first identifier is srfi are
reserved for libraries implementing Scheme Requests for Implementation.
It is inadvisable, but not an error, for identifiers in library names to
contain any of the characters  '
? * < ” : > + [ ] /
or control characters after escapes are expanded.
A library declaration is any of:
(export export spec ...)
(import import set ...)
(begin command or definition ...)
(include filename_1 filename_2 ...)
(includeci filename_1 filename_2 ...)
(includelibrarydeclarations filename_1 filename_2 ...)
(condexpand ceclause_1 ceclause_2 ...)
An export
declaration specifies a list of identifiers
which can be made visible to other libraries or programs. An export spec
takes one of the following forms:
identifier
(rename identifier_1 identifier_2)
In an export spec, an identifier names a single binding defined
within or imported into the library, where the external name for the
export is the same as the name of the binding within the library. A
rename
spec exports the binding defined within or imported
into the library and named by identifier_{1} in each
(identifier_1 identifier_2)
pairing, using
identifier_{2} as the external name.
An import
declaration provides a way to import the
identifiers exported by another library. It has the same syntax and
semantics as an import declaration used in a program or at the REPL (see
section [import]).
The begin
, include
, and
includeci
declarations are used to specify the body of the
library. They have the same syntax and semantics as the corresponding
expression types. This form of begin is analogous to, but not the same
as, the two types of begin defined in section [sequencing].
The includelibrarydeclarations
declaration is similar
to include
except that the contents of the file are spliced
directly into the current library definition. This can be used, for
example, to share the same export
declaration among
multiple libraries as a simple form of library interface.
The condexpand
declaration has the same syntax and
semantics as the condexpand
expression type, except that
it expands to splicedin library declarations rather than expressions
enclosed in begin.
One possible implementation of libraries is as follows: After all
condexpand
library declarations are expanded, a new
environment is constructed for the library consisting of all imported
bindings. The expressions from all begin
,
include
and includeci
library declarations
are expanded in that environment in the order in which they occur in the
library. Alternatively, condexpand
and import
declarations may be processed in left to right order interspersed with
the processing of other declarations, with the environment growing as
imported bindings are added to it by each import
declaration.
When a library is loaded, its expressions are executed in textual order. If a library’s definitions are referenced in the expanded form of a program or library body, then that library must be loaded before the expanded program or library body is evaluated. This rule applies transitively. If a library is imported by more than one program or library, it may possibly be loaded additional times.
Similarly, during the expansion of a library (foo), if any syntax keywords imported from another library (bar) are needed to expand the library, then the library (bar) must be expanded and its syntax definitions evaluated before the expansion of (foo).
Regardless of the number of times that a library is loaded, each program or library that imports bindings from a library must do so from a single loading of that library, regardless of the number of import declarations in which it appears. That is, (import (only (foo) a)) followed by (import (only (foo) b)) has the same effect as (import (only (foo) a b)).
The following example shows how a program can be divided into libraries plus a relatively small main program . If the main program is entered into a REPL, it is not necessary to import the base library.
(definelibrary (example grid)
(export make rows cols ref eachset!))
(rename put!
(import (scheme base))begin
(;; Create an NxM grid.
define (make n m)
(let ((grid (makevector n)))
(do ((i 0 (+ i 1)))
(= i n) grid)
((let ((v (makevector m \sharpfalse{})))
(vectorset! grid i v)))))
(define (rows grid)
(vectorlength grid))
(define (cols grid)
(vectorlength (vectorref grid 0)))
(;; Return \sharpfalse{} if out of range.
define (ref grid n m)
(and (< 1 n (rows grid))
(< 1 m (cols grid))
(vectorref (vectorref grid n) m)))
(define (put! grid n m v)
(vectorset! (vectorref grid n) m v))
(define (each grid proc)
(do ((j 0 (+ j 1)))
(= j (rows grid)))
((do ((k 0 (+ k 1)))
(= k (cols grid)))
((
(proc j k (ref grid j k)))))))
(definelibrary (example life)
(export life)set!)
(import (except (scheme base) write)
(scheme
(example grid))begin
(define (lifecount grid i j)
(define (count i j)
(if (ref grid i j) 1 0))
(+ (count ( i 1) ( j 1))
( i 1) j)
(count ( i 1) (+ j 1))
(count ( j 1))
(count i (+ j 1))
(count i (+ i 1) ( j 1))
(count (+ i 1) j)
(count (+ i 1) (+ j 1))))
(count (define (lifealive? grid i j)
(case (lifecount grid i j)
(3) \sharptrue{})
((2) (ref grid i j))
((else \sharpfalse{})))
(define (lifeprint grid)
(display "\x1B;[1H\x1B;[J") ; clear vt100
(
(each gridlambda (i j v)
(display (if v "*" " "))
(= j ( (cols grid) 1))
(when (newline)))))
(define (life grid iterations)
(do ((i 0 (+ i 1))
(
(grid0 grid grid1)
(grid1 (make (rows grid) (cols grid))
grid0))= i iterations))
((
(each grid0lambda (j k v)
(let ((a (lifealive? grid0 j k)))
(set! grid1 j k a))))
(
(lifeprint grid1)))))
;; Main program.
(import (scheme base)
(only (example life) life)
(rename (prefix (example grid) grid)
(gridmake makegrid)))
;; Initialize a grid with a glider.
define grid (makegrid 24 24))
(1 1 \sharptrue{})
(gridset! grid 2 2 \sharptrue{})
(gridset! grid 3 0 \sharptrue{})
(gridset! grid 3 1 \sharptrue{})
(gridset! grid 3 2 \sharptrue{})
(gridset! grid
;; Run for 80 iterations.
80) (life grid
Implementations may provide an interactive session called a
REPL (ReadEvalPrint Loop), where import declarations,
expressions and definitions can be entered and evaluated one at a time.
For convenience and ease of use, the global Scheme environment in a REPL
must not be empty, but must start out with at least the bindings
provided by the base library. This library includes the core syntax of
Scheme and generally useful procedures that manipulate data. For
example, the variable abs is bound to a procedure of one argument that
computes the absolute value of a number, and the variable + is bound to
a procedure that computes sums. The full list of
(scheme base)
bindings can be found in Appendix [stdlibraries].
Implementations may provide an initial REPL environment which behaves as if all possible variables are bound to locations, most of which contain unspecified values. Top level REPL definitions in such an implementation are truly equivalent to assignments, unless the identifier is defined as a syntax keyword.
An implementation may provide a mode of operation in which the REPL reads its input from a file. Such a file is not, in general, the same as a program, because it can contain import declarations in places other than the beginning.
This chapter describes Scheme’s builtin procedures.
The procedures force, promise?, and makepromise are intimately associated with the expression types delay and delayforce, and are described with them in section [force]. In the same way, the procedure makeparameter is intimately associated with the expression type parameterize, and is described with it in section [makeparameter].
A program can use a global variable definition to bind any variable. It may subsequently alter any such binding by an assignment (see section [assignment]). These operations do not modify the behavior of any procedure defined in this report or imported from a library (see section [libraries]). Altering any global binding that has not been introduced by a definition has an unspecified effect on the behavior of the procedures defined in this chapter.
When a procedure is said to return a newly allocated object, it means that the locations in the object are fresh.
A predicate is a procedure that always returns a boolean value (#t or #f). An equivalence predicate is the computational analogue of a mathematical equivalence relation; it is symmetric, reflexive, and transitive. Of the equivalence predicates described in this section, eq? is the finest or most discriminating, equal? is the coarsest, and eqv? is slightly less discriminating than eq?.
(eqv? obj_{1} obj_{2})
procedure The eqv? procedure defines a useful equivalence relation on
objects. Briefly, it returns #t
if obj_{1}
and obj_{2} are normally regarded as the same object.
This relation is left slightly open to interpretation, but the following
partial specification of eqv? holds for all implementations of
Scheme.
The eqv? procedure returns #t
if:
obj_{1} and obj_{2} are both
#t
or both #f.
obj_{1} and obj_{2} are both symbols and are the same symbol according to the symbol=? procedure (section [symbolsection]).
obj_{1} and obj_{2} are both exact numbers and are numerically equal (in the sense of =).
obj_{1} and obj_{2} are both inexact numbers such that they are numerically equal (in the sense of =) and they yield the same results (in the sense of eqv?) when passed as arguments to any other procedure that can be defined as a finite composition of Scheme’s standard arithmetic procedures, provided it does not result in a NaN value.
obj_{1} and obj_{2} are both characters and are the same character according to the char=? procedure (section [charactersection]).
obj_{1} and obj_{2} are both the empty list.
obj_{1} and obj_{2} are pairs, vectors, bytevectors, records, or strings that denote the same location in the store (section [storagemodel]).
obj_{1} and obj_{2} are procedures whose location tags are equal (section [lambda]).
The eqv? procedure returns #f
if:
obj_{1} and obj_{2} are of different types (section [disjointness]).
one of obj_{1} and obj_{2} is
#t
but the other is #f.
obj_{1} and obj_{2} are symbols but are not the same symbol according to the symbol=? procedure (section [symbolsection]).
one of obj_{1} and obj_{2} is an exact number but the other is an inexact number.
obj_{1} and obj_{2} are both exact numbers and are numerically unequal (in the sense of =).
obj_{1} and obj_{2} are both inexact numbers such that either they are numerically unequal (in the sense of =), or they do not yield the same results (in the sense of eqv?) when passed as arguments to any other procedure that can be defined as a finite composition of Scheme’s standard arithmetic procedures, provided it does not result in a NaN value. As an exception, the behavior of eqv? is unspecified when both obj_{1} and obj_{2} are NaN.
obj_{1} and obj_{2} are characters for which the char=? procedure returns #f.
one of obj_{1} and obj_{2} is the empty list but the other is not.
obj_{1} and obj_{2} are pairs, vectors, bytevectors, records, or strings that denote distinct locations.
obj_{1} and obj_{2} are procedures that would behave differently (return different values or have different side effects) for some arguments.
eqv? 'a 'a) ;; => #t
(eqv? 'a 'b) ;; => #f
(eqv? 2 2) ;; => #t
(eqv? 2 2.0) ;; => #f
(eqv? '() '()) ;; => #t
(eqv? 100000000 100000000) ;; => #t
(eqv? 0.0 +nan.0) ;; => #f
(eqv? (cons 1 2) (cons 1 2)) ;; => #f
(eqv? (lambda () 1)
(lambda () 2)) ;; => #f
(let ((p (lambda (x) x)))
(eqv? p p)) ;; => #t
(eqv? #f 'nil) ;; => #f (
The following examples illustrate cases in which the above rules do not fully specify the behavior of eqv?. All that can be said about such cases is that the value returned by eqv? must be a boolean.
eqv? "" "") ;; => unspecified
(eqv? '#() '#()) ;; => unspecified
(eqv? (lambda (x) x)
(lambda (x) x)) ;; => unspecified
(eqv? (lambda (x) x)
(lambda (y) y)) ;; => unspecified
(eqv? 1.0e0 1.0f0) ;; => unspecified
(eqv? +nan.0 +nan.0) ;; => unspecified (
Note that (eqv? 0.0 0.0) will return #f
if negative
zero is distinguished, and #t
if negative zero is not
distinguished.
The next set of examples shows the use of eqv? with procedures that have local state. The gencounter procedure must return a distinct procedure every time, since each procedure has its own internal counter. The genloser procedure, however, returns operationally equivalent procedures each time, since the local state does not affect the value or side effects of the procedures. However, eqv? may or may not detect this equivalence.
define gencounter
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) n))))
(let ((g (gencounter)))
(eqv? g g)) ;; => #t
(eqv? (gencounter) (gencounter))
(;; => #f
define genloser
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) 27))))
(let ((g (genloser)))
(eqv? g g)) ;; => #t
(eqv? (genloser) (genloser))
(;; => unspecified
letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
(lambda () (if (eqv? f g) 'both 'g))))
(g (eqv? f g))
(;; => unspecified
letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
(lambda () (if (eqv? f g) 'g 'both))))
(g (eqv? f g))
(;; => #f
Since it is an error to modify constant objects (those returned by literal expressions), implementations may share structure between constants where appropriate. Thus the value of eqv? on constants is sometimes implementationdependent.
eqv? '(a) '(a)) ;; => unspecified
(eqv? "a" "a") ;; => unspecified
(eqv? '(b) (cdr '(a b))) ;; => unspecified
(let ((x '(a)))
(eqv? x x)) ;; => #t (
The above definition of eqv? allows implementations latitude in their treatment of procedures and literals: implementations may either detect or fail to detect that two procedures or two literals are equivalent to each other, and can decide whether or not to merge representations of equivalent objects by using the same pointer or bit pattern to represent both.
Note: If inexact numbers are represented as IEEE binary floatingpoint numbers, then an implementation of eqv? that simply compares equalsized inexact numbers for bitwise equality is correct by the above definition.
(eq? obj_{1} obj_{2})
procedure The eq? procedure is similar to eqv? except that in some
cases it is capable of discerning distinctions finer than those
detectable by eqv?. It must always return #f
when eqv? also
would, but may return #f
in some cases where eqv? would
return #t.
On symbols, booleans, the empty list, pairs, and records, and also on nonempty strings, vectors, and bytevectors, eq? and eqv? are guaranteed to have the same behavior. On procedures, eq? must return true if the arguments’ location tags are equal. On numbers and characters, eq?’s behavior is implementationdependent, but it will always return either true or false. On empty strings, empty vectors, and empty bytevectors, eq? may also behave differently from eqv?.
eq? 'a 'a) ;; => #t
(eq? '(a) '(a)) ;; => unspecified
(eq? (list 'a) (list 'a)) ;; => #f
(eq? "a" "a") ;; => unspecified
(eq? "" "") ;; => unspecified
(eq? '() '()) ;; => #t
(eq? 2 2) ;; => unspecified
(eq? #\A #\A) ;; => unspecified
(eq? car car) ;; => #t
(let ((n (+ 2 3)))
(eq? n n)) ;; => unspecified
(let ((x '(a)))
(eq? x x)) ;; => #t
(let ((x '#()))
(eq? x x)) ;; => #t
(let ((p (lambda (x) x)))
(eq? p p)) ;; => #t (
Rationale: It will usually be possible to implement eq? much more efficiently than eqv?, for example, as a simple pointer comparison instead of as some more complicated operation. One reason is that it is not always possible to compute eqv? of two numbers in constant time, whereas eq? implemented as pointer comparison will always finish in constant time.
(equal? obj_{1} obj_{2})
procedure The equal? procedure, when applied to pairs, vectors, strings
and bytevectors, recursively compares them, returning #t
when the unfoldings of its arguments into (possibly infinite) trees are
equal (in the sense of equal?) as ordered trees, and #f
otherwise. It returns the same as eqv? when applied to booleans,
symbols, numbers, characters, ports, procedures, and the empty list. If
two objects are eqv?, they must be equal? as well. In all other cases,
equal? may return either #t
or #f.
Even if its arguments are circular data structures, equal? must always terminate.
equal? 'a 'a) ;; => #t
(equal? '(a) '(a)) ;; => #t
(equal? '(a (b) c)
(;; => #t
'(a (b) c)) equal? "abc" "abc") ;; => #t
(equal? 2 2) ;; => #t
(equal? (makevector 5 'a)
(makevector 5 'a)) ;; => #t
(equal? '#1=(a b . #1#)
(2=(a b a b . #2#)) ;; => #t
'#equal? (lambda (x) x)
(lambda (y) y)) ;; => unspecified (
Note: A rule of thumb is that objects are generally equal? if they print the same.
It is important to distinguish between mathematical numbers, the Scheme numbers that attempt to model them, the machine representations used to implement the Scheme numbers, and notations used to write numbers. This report uses the types number, complex, real, rational, and integer to refer to both mathematical numbers and Scheme numbers.
Mathematically, numbers are arranged into a tower of subtypes in which each level is a subset of the level above it:
number
complex number
real number
rational number
integer
For example, 3 is an integer. Therefore 3 is also a rational, a real,
and a complex number. The same is true of the Scheme numbers that model
3. For Scheme numbers, these types are defined by the predicates
number?
, complex?
, real?
,
rational?
, and integer?
.
There is no simple relationship between a number’s type and its representation inside a computer. Although most implementations of Scheme will offer at least two different representations of 3, these different representations denote the same integer.
Scheme’s numerical operations treat numbers as abstract data, as independent of their representation as possible. Although an implementation of Scheme may use multiple internal representations of numbers, this ought not to be apparent to a casual programmer writing simple programs.
It is useful to distinguish between numbers that are represented exactly and those that might not be. For example, indexes into data structures must be known exactly, as must some polynomial coefficients in a symbolic algebra system. On the other hand, the results of measurements are inherently inexact, and irrational numbers may be approximated by rational and therefore inexact approximations. In order to catch uses of inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact from inexact numbers. This distinction is orthogonal to the dimension of type.
A Scheme number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations. A number is inexact if it was written as an inexact constant, if it was derived using inexact ingredients, or if it was derived using inexact operations. Thus inexactness is a contagious property of a number. In particular, an exact complex number has an exact real part and an exact imaginary part; all other complex numbers are inexact complex numbers.
If two implementations produce exact results for a computation that did not involve inexact intermediate results, the two ultimate results will be mathematically equal. This is generally not true of computations involving inexact numbers since approximate methods such as floatingpoint arithmetic may be used, but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result.
Rational operations such as + should always produce exact results when given exact arguments. If the operation is unable to produce an exact result, then it may either report the violation of an implementation restriction or it may silently coerce its result to an inexact value. However, (/ 3 4) must not return the mathematically incorrect value 0. See section [restrictions].
Except for exact
, the operations described in this
section must generally return inexact results when given any inexact
arguments. An operation may, however, return an exact result if it can
prove that the value of the result is unaffected by the inexactness of
its arguments. For example, multiplication of any number by an exact
zero may produce an exact zero result, even if the other argument is
inexact.
Specifically, the expression (* 0 +inf.0) may return 0, or +nan.0, or report that inexact numbers are not supported, or report that nonrational real numbers are not supported, or fail silently or noisily in other implementationspecific ways.
Implementations of Scheme are not required to implement the whole tower of subtypes given in section [numericaltypes], but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, implementations in which all numbers are real, or in which nonreal numbers are always inexact, or in which exact numbers are always integer, are still quite useful.
Implementations may also support only a limited range of numbers of any type, subject to the requirements of this section. The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type. For example, an implementation that uses IEEE binary doubleprecision floatingpoint numbers to represent all its inexact real numbers may also support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the IEEE binary double format. Furthermore, the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached.
An implementation of Scheme must support exact integers throughout
the range of numbers permitted as indexes of lists, vectors,
bytevectors, and strings or that result from computing the length of one
of these. The length
, vectorlength
,
bytevectorlength
, and stringlength
procedures must return an exact integer, and it is an error to use
anything but an exact integer as an index. Furthermore, any integer
constant within the index range, if expressed by an exact integer
syntax, must be read as an exact integer, regardless of any
implementation restrictions that apply outside this range. Finally, the
procedures listed below will always return exact integer results
provided all their arguments are exact integers and the mathematically
expected results are representable as exact integers within the
implementation:
 *
+ abs
ceiling denominator
exactintegersqrt expt
floor floor/
floorquotient floorremaindergcd lcm
max min
modulo numerator
quotient rationalize
remainder round
truncate
square
truncate/ truncatequotient truncateremainder
It is recommended, but not required, that implementations support exact integers and exact rationals of practically unlimited size and precision, and to implement the above procedures and the / procedure in such a way that they always return exact results when given exact arguments. If one of these procedures is unable to deliver an exact result when given exact arguments, then it may either report a violation of an implementation restriction or it may silently coerce its result to an inexact number; such a coercion can cause an error later. Nevertheless, implementations that do not provide exact rational numbers should return inexact rational numbers rather than reporting an implementation restriction.
An implementation may use floatingpoint and other approximate representation strategies for inexact numbers. This report recommends, but does not require, that implementations that use floatingpoint representations follow the IEEE 754 standard, and that implementations using other representations should match or exceed the precision achievable using these floatingpoint standards . In particular, the description of transcendental functions in IEEE 7542008 should be followed by such implementations, particularly with respect to infinities and NaNs.
Although Scheme allows a variety of written notations for numbers, any particular implementation may support only some of them. For example, an implementation in which all numbers are real need not support the rectangular and polar notations for complex numbers. If an implementation encounters an exact numerical constant that it cannot represent as an exact number, then it may either report a violation of an implementation restriction or it may silently represent the constant by an inexact number.
Implementations may provide more than one representation of floatingpoint numbers with differing precisions. In an implementation which does so, an inexact result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation. Although it is desirable for potentially inexact operations such as sqrt to produce exact answers when applied to exact arguments, if an exact number is operated upon so as to produce an inexact result, then the most precise representation available must be used. For example, the value of (sqrt 4) should be 2, but in an implementation that provides both single and double precision floating point numbers it may be the latter but must not be the former.
It is the programmer’s responsibility to avoid using inexact number objects with magnitude or significand too large to be represented in the implementation.
In addition, implementations may distinguish special numbers called positive infinity, negative infinity, NaN, and negative zero.
Positive infinity is regarded as an inexact real (but not rational) number that represents an indeterminate value greater than the numbers represented by all rational numbers. Negative infinity is regarded as an inexact real (but not rational) number that represents an indeterminate value less than the numbers represented by all rational numbers.
Adding or multiplying an infinite value by any finite real value results in an appropriately signed infinity; however, the sum of positive and negative infinities is a NaN. Positive infinity is the reciprocal of zero, and negative infinity is the reciprocal of negative zero. The behavior of the transcendental functions is sensitive to infinity in accordance with IEEE 754.
A NaN is regarded as an inexact real (but not rational) number so indeterminate that it might represent any real value, including positive or negative infinity, and might even be greater than positive infinity or less than negative infinity. An implementation that does not support nonreal numbers may use NaN to represent nonreal values like (sqrt 1.0) and (asin 2.0).
A NaN always compares false to any number, including a NaN. An arithmetic operation where one operand is NaN returns NaN, unless the implementation can prove that the result would be the same if the NaN were replaced by any rational number. Dividing zero by zero results in NaN unless both zeros are exact.
Negative zero is an inexact real value written 0.0 and is distinct (in the sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish negative zero. If it does, however, the behavior of the transcendental functions is sensitive to the distinction in accordance with IEEE 754. Specifically, in a Scheme implementing both complex numbers and negative zero, the branch cut of the complex logarithm function is such that (imagpart (log 1.00.0i)) is − π rather than π.
Furthermore, the negation of negative zero is ordinary zero and vice versa. This implies that the sum of two or more negative zeros is negative, and the result of subtracting (positive) zero from a negative zero is likewise negative. However, numerical comparisons treat negative zero as equal to zero.
Note that both the real and the imaginary parts of a complex number can be infinities, NaNs, or negative zero.
The syntax of the written representations for numbers is described formally in section [numbersyntax]. Note that case is not significant in numerical constants.
A number can be written in binary, octal, decimal, or hexadecimal by the use of a radix prefix. The radix prefixes are #b (binary), #o (octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a number is assumed to be expressed in decimal.
A numerical constant can be specified to be either exact or inexact by a prefix. The prefixes are #e for exact, and #i for inexact. An exactness prefix can appear before or after any radix prefix that is used. If the written representation of a number has no exactness prefix, the constant is inexact if it contains a decimal point or an exponent. Otherwise, it is exact.
In systems with inexact numbers of varying precisions it can be useful to specify the precision of a constant. For this purpose, implementations may accept numerical constants written with an exponent marker that indicates the desired precision of the inexact representation. If so, the letter s, f, d, or l, meaning short, single, double, or long precision, respectively, can be used in place of e. The default precision has at least as much precision as double, but implementations may allow this default to be set by the user.
3.14159265358979F0
;; Round to single  3.141593
0.6L0
;; Extend to long  .600000000000000
The numbers positive infinity, negative infinity, and NaN are written +inf.0, inf.0 and +nan.0 respectively. NaN may also be written nan.0. The use of signs in the written representation does not necessarily reflect the underlying sign of the NaN value, if any. Implementations are not required to support these numbers, but if they do, they must do so in general conformance with IEEE 754. However, implementations are not required to support signaling NaNs, nor to provide a way to distinguish between different NaNs.
There are two notations provided for nonreal complex numbers: the rectangular notation a+bi, where a is the real part and b is the imaginary part; and the polar notation r@θ, where r is the magnitude and θ is the phase (angle) in radians. These are related by the equation a + *b**i = rcos θ + (rsinθ)i. All of a, b, r, and θ* are real numbers.
The reader is referred to section [typeconventions] for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines. The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number. Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy; the inexact constants were chosen so that this is likely to be true in implementations that use IEEE binary doubles to represent inexact numbers.
(number? obj) procedure
(complex? obj) procedure
(real? obj) procedure
(rational? obj) procedure
(integer? obj) procedure
These numerical type predicates can be applied to any kind of
argument, including nonnumbers. They return #t
if the
object is of the named type, and otherwise they return #f. In general,
if a type predicate is true of a number then all higher type predicates
are also true of that number. Consequently, if a type predicate is false
of a number, then all lower type predicates are also false of that
number.
If z is a complex number, then (real? z) is true if and only if (zero? (imagpart z)) is true. If x is an inexact real number, then (integer? x) is true if and only if (= x (round x)).
The numbers +inf.0, inf.0, and +nan.0 are real but not rational.
complex? 3+4i) ;; => #t
(complex? 3) ;; => #t
(real? 3) ;; => #t
(real? 2.5+0i) ;; => #t
(real? 2.5+0.0i) ;; => #f
(real? #e1e10) ;; => #t
(real? +inf.0) ;; => #t
(real? +nan.0) ;; => #t
(rational? inf.0) ;; => #f
(rational? 3.5) ;; => #t
(rational? 6/10) ;; => #t
(rational? 6/3) ;; => #t
(integer? 3+0i) ;; => #t
(integer? 3.0) ;; => #t
(integer? 8/4) ;; => #t (
Note: The behavior of these type predicates on inexact numbers is unreliable, since any inaccuracy might affect the result.
Note: In many implementations the complex?
procedure will be the same as number?
, but unusual
implementations may represent some irrational numbers exactly or may
extend the number system to support some kind of noncomplex
numbers.
(exact? z) procedure
(inexact? z) procedure
These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of these predicates is true.
exact? 3.0) ;; => #f
(exact? #e3.0) ;; => #t
(inexact? 3.) ;; => #t (
(exactinteger? z) procedure
Returns #t
if z is both exact and an integer;
otherwise returns #f.
32) ;; => #t{}
(exactinteger? 32.0) ;; => #f
(exactinteger? 32/5) ;; => #f (exactinteger?
(finite? z) inexact library procedure
The finite? procedure returns #t
on all real numbers
except +inf.0, inf.0, and +nan.0, and on complex numbers if their real
and imaginary parts are both finite. Otherwise it returns #f.
finite? 3) ;; => #t
(finite? +inf.0) ;; => #f
(finite? 3.0+inf.0i) ;; => #f (
(infinite? z) inexact library procedure
The infinite? procedure returns #t
on the real numbers
+inf.0 and inf.0, and on complex numbers if their real or imaginary
parts or both are infinite. Otherwise it returns #f.
infinite? 3) ;; => #f
(infinite? +inf.0) ;; => #t
(infinite? +nan.0) ;; => #f
(infinite? 3.0+inf.0i) ;; => #t (
(nan? z) inexact library procedure
The nan? procedure returns #t
on +nan.0, and on complex
numbers if their real or imaginary parts or both are +nan.0. Otherwise
it returns #f.
nan? +nan.0) ;; => #t
(nan? 32) ;; => #f
(nan? +nan.0+5.0i) ;; => #t
(nan? 1+2i) ;; => #f (
(= **z_{1} z_{2} z_{3} … ) procedure
(< **x_{1} x_{2} x_{3} … ) procedure
(> **x_{1} x_{2} x_{3} … ) procedure
(<= **x_{1} x_{2} x_{3} … ) procedure
(>= **x_{1} x_{2} x_{3} … ) procedure
These procedures return #t
if their arguments are
(respectively): equal, monotonically increasing, monotonically
decreasing, monotonically nondecreasing, or monotonically
nonincreasing, and #f
otherwise. If any of the arguments
are +nan.0, all the predicates return #f. They do not distinguish
between inexact zero and inexact negative zero.
These predicates are required to be transitive.
Note: The implementation approach of converting all arguments to inexact numbers if any argument is inexact is not transitive. For example, let big be (expt 2 1000), and assume that big is exact and that inexact numbers are represented by 64bit IEEE binary floating point numbers. Then (= ( big 1) (inexact big)) and (= (inexact big) (+ big 1)) would both be true with this approach, because of the limitations of IEEE representations of large integers, whereas (= ( big 1) (+ big 1)) is false. Converting inexact values to exact numbers that are the same (in the sense of =) to them will avoid this problem, though special care must be taken with infinities.
Note: While it is not an error to compare inexact numbers
using these predicates, the results are unreliable because a small
inaccuracy can affect the result; this is especially true of
=
and zero?
. When in doubt, consult a
numerical analyst.
(zero? z) procedure
(positive? x) procedure
(negative? x) procedure
(odd? n) procedure
(even? n) procedure
These numerical predicates test a number for a particular property,
returning #t
or #f. See note above.
(max **x_{1} x_{2} … ) procedure
(min **x_{1} x_{2} … ) procedure
These procedures return the maximum or minimum of their arguments.
max 3 4) ;; => 4 ; exact
(max 3.9 4) ;; => 4.0 ; inexact (
Note: If any argument is inexact, then the result will also be inexact (unless the procedure can prove that the inaccuracy is not large enough to affect the result, which is possible only in unusual implementations). If min or max is used to compare numbers of mixed exactness, and the numerical value of the result cannot be represented as an inexact number without loss of accuracy, then the procedure may report a violation of an implementation restriction.
(+ z_{1} … ) procedure (* z_{1} … ) procedure These procedures return the sum or product of their arguments.
+ 3 4) ;; => 7
(+ 3) ;; => 3
(+) ;; => 0
(* 4) ;; => 4
(*) ;; => 1 (
( z) procedure
( **z_{1} z_{2} … ) procedure
(/ z) procedure
(/ **z_{1} z_{2} … ) procedure
With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument.
It is an error if any argument of / other than the first is an exact zero. If the first argument is an exact zero, an implementation may return an exact zero unless one of the other arguments is a NaN.
 3 4) ;; => 1
( 3 4 5) ;; => 6
( 3) ;; => 3
(/ 3 4 5) ;; => 3/20
(/ 3) ;; => 1/3 (
(abs x) procedure
The abs procedure returns the absolute value of its argument.
abs 7) ;; => 7 (
(floor/ **n_{1} n_{2}) procedure
(floorquotient **n_{1} n_{2}) procedure
(floorremainder **n_{1} n_{2}) procedure
(truncate/ **n_{1} n_{2}) procedure
(truncatequotient **n_{1} n_{2}) procedure
(truncateremainder **n_{1} n_{2}) procedure
These procedures implement numbertheoretic (integer) division. It is an error if n_{2} is zero. The procedures ending in / return two integers; the other procedures return an integer. All the procedures compute a quotient n_{q} and remainder n_{r} such that ${\\hbox{$n_1$\\/}} = {\\hbox{$n_2$\\/}} {\\hbox{$n_q$\\/}} + {\\hbox{$n_r$\\/}}$. For each of the division operators, there are three procedures defined as follows:
{n} \vrii{n}) ;; => \vr{n_q} \vr{n_r}
(<operator>/ \vri{n} \vrii{n}) ;; => \vr{n_q}
(<operator>quotient \vri{n} \vrii{n}) ;; => \vr{n_r} (<operator>remainder \vri
The remainder n_{r} is determined by the choice of integer n_{q}: ${\\hbox{$n_r$\\/}} = {\\hbox{$n_1$\\/}}  {\\hbox{$n_2$\\/}} {\\hbox{$n_q$\\/}}$. Each set of operators uses a different choice of n_{q}:
floor  ${\\hbox{$n_q$\\/}} = \\lfloor{\\hbox{$n_1$\\/}} / {\\hbox{$n_2$\\/}}\\rfloor$ 
truncate  ${\\hbox{$n_q$\\/}} = \\text{truncate}({\\hbox{$n_1$\\/}} / {\\hbox{$n_2$\\/}})$ 
For any of the operators, and for integers n_{1} and n_{2} with n_{2} not equal to 0,
= \vri{n} (+ (* \vrii{n} (<operator>quotient \vri{n} \vrii{n}))
({n} \vrii{n})))
(<operator>remainder \vri;; => #t
provided all numbers involved in that computation are exact.
Examples:
5 2) ;; => 2 1
(floor/ 5 2) ;; => 3 1
(floor/ 5 2) ;; => 3 1
(floor/ 5 2) ;; => 2 1
(floor/ 5 2) ;; => 2 1
(truncate/ 5 2) ;; => 2 1
(truncate/ 5 2) ;; => 2 1
(truncate/ 5 2) ;; => 2 1
(truncate/ 5.0 2) ;; => 2.0 1.0 (truncate/ 
(quotient **n_{1} n_{2}) procedure
(remainder **n_{1} n_{2}) procedure
(modulo **n_{1} n_{2}) procedure
The quotient and remainder procedures are equivalent to truncatequotient and truncateremainder, respectively, and modulo is equivalent to floorremainder.
Note: These procedures are provided for backward compatibility with earlier versions of this report.
(gcd **n_{1} … ) procedure
(lcm **n_{1} … ) procedure
These procedures return the greatest common divisor or least common multiple of their arguments. The result is always nonnegative.
gcd 32 36) ;; => 4
(gcd) ;; => 0
(lcm 32 36) ;; => 288
(lcm 32.0 36) ;; => 288.0 ; inexact
(lcm) ;; => 1 (
(numerator q) procedure
(denominator q) procedure
These procedures return the numerator or denominator of their argument; the result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1.
numerator (/ 6 4)) ;; => 3
(denominator (/ 6 4)) ;; => 2
(denominator
(inexact (/ 6 4))) ;; => 2.0 (
(floor x) procedure
(ceiling x) procedure
(truncate x) procedure
(round x) procedure
These procedures return integers. The floor procedure returns the largest integer not larger than x. The ceiling procedure returns the smallest integer not smaller than x, truncate returns the integer closest to x whose absolute value is not larger than the absolute value of x, and round returns the closest integer to x, rounding to even when x is halfway between two integers.
Rationale: The round procedure rounds to even for consistency with the default rounding mode specified by the IEEE 754 IEEE floatingpoint standard.
Note: If the argument to one of these procedures is inexact, then the result will also be inexact. If an exact value is needed, the result can be passed to the exact procedure. If the argument is infinite or a NaN, then it is returned.
floor 4.3) ;; => 5.0
(ceiling 4.3) ;; => 4.0
(truncate 4.3) ;; => 4.0
(round 4.3) ;; => 4.0
(
floor 3.5) ;; => 3.0
(ceiling 3.5) ;; => 4.0
(truncate 3.5) ;; => 3.0
(round 3.5) ;; => 4.0 ; inexact
(
round 7/2) ;; => 4 ; exact
(round 7) ;; => 7 (
(rationalize x y) procedure
The rationalize procedure returns the simplest rational number differing from x by no more than y. A rational number r_{1} is simpler than another rational number r_{2} if r_{1} = p_{1}/q_{1} and r_{2} = p_{2}/q_{2} (in lowest terms) and p_{1} ≤ p_{2} and q_{1} ≤ q_{2}. Thus 3/5 is simpler than 4/7. Although not all rationals are comparable in this ordering (consider 2/7 and 3/5), any interval contains a rational number that is simpler than every other rational number in that interval (the simpler 2/5 lies between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of all.
rationalize
(exact .3) 1/10) ;; => 1/3 ; exact
(rationalize .3 1/10) ;; => #i1/3 ; inexact (
(exp z) inexact library procedure
(log z) inexact library procedure
(log **z_{1} z_{2}) inexact library procedure
(sin z) inexact library procedure
(cos z) inexact library procedure
(tan z) inexact library procedure
(asin z) inexact library procedure
(acos z) inexact library procedure
(atan z) inexact library procedure
(atan y x) inexact library procedure
These procedures compute the usual transcendental functions. The log
procedure computes the natural logarithm of z (not the base ten
logarithm) if a single argument is given, or the
basez_{2} logarithm of z_{1} if two
arguments are given. The asin, acos, and atan procedures compute arcsine
(sin^{−1}), arccosine (cos^{−1}), and arctangent
(tan^{−1}), respectively. The twoargument variant of atan
computes (angle (makerectangular x y))
(see below), even
in implementations that don’t support complex numbers.
In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. The value of log z is defined to be the one whose imaginary part lies in the range from − π (inclusive if 0.0 is distinguished, exclusive otherwise) to π (inclusive). The value of log 0 is mathematically undefined. With log defined this way, the values of sin^{−1}z, cos^{−1}z, and tan^{−1}z are according to the following formulæ: $$\\sin^{ 1}z =  i\\log\\left( iz + \\sqrt{1  z^{2}} \\right)$$ cos^{−1}z = π/2 − sin^{−1}z tan^{−1}z = (log(1+iz)−log(1−iz))/(2i)
However, (log 0.0) returns inf.0 (and (log 0.0) returns inf.0+πi) if the implementation supports infinities (and 0.0).
The range of (atan y x) is as in the following table. The asterisk (*) indicates that the entry applies to implementations that distinguish minus zero.
y condition  x condition  range of result r  

y = 0.0  x > 0.0  0.0  
*  y = + 0.0  x > 0.0  + 0.0 
*  y = − 0.0  x > 0.0  − 0.0 
y > 0.0  x > 0.0  $0.0 \< r \< \\frac{\\pi}{2}$  
y > 0.0  x = 0.0  $\\frac{\\pi}{2}$  
y > 0.0  x < 0.0  $\\frac{\\pi}{2} \< r \< \\pi$  
y = 0.0  x < 0  π  
*  y = + 0.0  x < 0.0  π 
*  y = − 0.0  x < 0.0  − π 
y < 0.0  x < 0.0  $ \\pi \< r \<  \\frac{\\pi}{2}$  
y < 0.0  x = 0.0  $ \\frac{\\pi}{2}$  
y < 0.0  x > 0.0  $ \\frac{\\pi}{2} \< r \< 0.0$  
y = 0.0  x = 0.0  undefined  
*  y = + 0.0  x = + 0.0  + 0.0 
*  y = − 0.0  x = + 0.0  − 0.0 
*  y = + 0.0  x = − 0.0  π 
*  y = − 0.0  x = − 0.0  − π 
*  y = + 0.0  x = 0  $\\frac{\\pi}{2}$ 
*  y = − 0.0  x = 0  $ \\frac{\\pi}{2}$ 
The above specification follows , which in turn cites ; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions. When it is possible, these procedures produce a real result from a real argument.
(square z) procedure Returns the square of z. This is equivalent to (* z z).
42) ;; => 1764
(square 2.0) ;; => 4.0 (square
(sqrt z) inexact library procedure Returns the principal square root of z. The result will have either a positive real part, or a zero real part and a nonnegative imaginary part.
sqrt 9) ;; => 3
(sqrt 1) ;; => +i (
(exactintegersqrt k) procedure Returns two nonnegative exact integers s and r where $\\hbox{\\it{}k\\/} = s^2 + r$ and $\\hbox{\\it{}k\\/} \< (s+1)^2$.
exactintegersqrt 4) ;; => 2 0
(exactintegersqrt 5) ;; => 2 1 (
(expt **z_{1} z_{2}) procedure
Returns z_{1} raised to the power z_{2}. For nonzero z_{1}, this is z_{1}^{z2} = e^{z2log z1} The value of 0^{z} is 1 if (zero? z), 0 if (realpart z) is positive, and an error otherwise. Similarly for 0.0^{z}, with inexact results.
(makerectangular **x_{1} x_{2}) complex library procedure
(makepolar **x_{3} x_{4}) complex library procedure
(realpart z) complex library procedure
(imagpart z) complex library procedure
(magnitude z) complex library procedure
(angle z) complex library procedure
Let x_{1}, x_{2}, x_{3}, and x_{4} be real numbers and z be a complex number such that $${\\hbox{$z$\\/}} = {\\hbox{$x_1$\\/}} + {\\hbox{$x_2$\\/}}\\hbox{$i$} = {\\hbox{$x_3$\\/}} \\cdot e^{i x_4}$$ Then all of
makerectangular \vri{x} \vrii{x}) ;; => \vr{z}
(makepolar \vriii{x} \vriv{x}) ;; => \vr{z}
(realpart \vr{z}) ;; => \vri{x}
(imagpart \vr{z}) ;; => \vrii{x}
(magnitude \vr{z}) ;; => $\vriii{x}$
(angle \vr{z}) ;; => $x_{angle}$ (
are true, where − π ≤ x_{angle} ≤ π with $x_{angle} = {\\hbox{$x_4$\\/}} + 2\\pi n$ for some integer n.
The makepolar procedure may return an inexact complex number even if its arguments are exact. The realpart and imagpart procedures may return exact real numbers when applied to an inexact complex number if the corresponding argument passed to makerectangular was exact.
Rationale: The magnitude procedure is the same as
abs
for a real argument, but abs is in the base library,
whereas magnitude is in the optional complex library.
(inexact z) procedure
(exact z) procedure
The procedure inexact returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the argument. For inexact arguments, the result is the same as the argument. For exact complex numbers, the result is a complex number whose real and imaginary parts are the result of applying inexact to the real and imaginary parts of the argument, respectively. If an exact argument has no reasonably close inexact equivalent (in the sense of =), then a violation of an implementation restriction may be reported.
The procedure exact returns an exact representation of z. The value returned is the exact number that is numerically closest to the argument. For exact arguments, the result is the same as the argument. For inexact nonintegral real arguments, the implementation may return a rational approximation, or may report an implementation violation. For inexact complex arguments, the result is a complex number whose real and imaginary parts are the result of applying exact to the real and imaginary parts of the argument, respectively. If an inexact argument has no reasonably close exact equivalent, (in the sense of =), then a violation of an implementation restriction may be reported.
These procedures implement the natural onetoone correspondence between exact and inexact integers throughout an implementationdependent range. See section [restrictions].
Note: These procedures were known in R^{5}RS as exact>inexact and inexact>exact, respectively, but they have always accepted arguments of any exactness. The new names are clearer and shorter, as well as being compatible with R^{6}RS.
(number>string z) procedure
(number>string z radix) procedure
It is an error if radix is not one of 2, 8, 10, or 16.
The procedure numberstring takes a number and a radix and returns as a string an external representation of the given number in the given radix such that
let ((number \vr{number})
({radix}))
(radix \vreqv? number
(string>number (number>string number
(
radix) radix)))
is true. It is an error if no possible result makes this expression true. If omitted, radix defaults to 10.
If z is inexact, the radix is 10, and the above expression can be satisfied by a result that contains a decimal point, then the result contains a decimal point and is expressed using the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the above expression true ; otherwise the format of the result is unspecified.
The result returned by numberstring never contains an explicit radix prefix.
Note: The error case can occur only when z is not a complex number or is a complex number with a nonrational real or imaginary part.
Rationale: If z is an inexact number and the radix is 10, then the above expression is normally satisfied by a result containing a decimal point. The unspecified case allows for infinities, NaNs, and unusual representations.
(string>number string) procedure
(string>number string radix) procedure
Returns a number of the maximally precise representation expressed by the given *string. It is an error if radi**x* is not 2, 8, 10, or 16.
If supplied, radix is a
default radix that will be overridden if an explicit radix prefix is
present in *strin**g* (e.g.
"#o177"
). If
radix is not supplied, then
the default radix is 10. If *strin**g*
is not a syntactically valid notation for a number, or would result in a
number that the implementation cannot represent, then string>number
returns #f. An error is never signaled due to the content of
*strin**g*.
string>number "100") ;; => 100
(string>number "100" 16) ;; => 256
(string>number "1e2") ;; => 100.0 (
Note: The domain of string>number may be restricted by
implementations in the following ways. If all numbers supported by an
implementation are real, then string>number is permitted to return
#f whenever *strin**g* uses the polar
or rectangular notations for complex numbers. If all numbers are
integers, then string>number may return #f
whenever the
fractional notation is used. If all numbers are exact, then
string>number may return #f
whenever an exponent marker
or explicit exactness prefix is used. If all inexact numbers are
integers, then string>number may return #f
whenever a
decimal point is used.
The rules used by a particular implementation for string>number
must also be applied to read and to the routine that reads programs, in
order to maintain consistency between internal numeric processing, I/O,
and the processing of programs. As a consequence, the
R^{5}RS permission to return #f
when
string has an explicit radix prefix has been withdrawn.
The standard boolean objects for true and false are written as
#t
and #f. Alternatively, they can be written #true and
#false, respectively. What really matters, though, are the objects that
the Scheme conditional expressions (if, cond, and, or, when, unless, do)
treat as true or false. The phrase “a true value” (or sometimes just
“true”) means any object treated as true by the conditional expressions,
and the phrase “a false value” (or “false”) means any object treated as
false by the conditional expressions.
Of all the Scheme values, only #f
counts as false in
conditional expressions. All other Scheme values, including #t, count as
true.
Note: Unlike some other dialects of Lisp, Scheme
distinguishes #f
and the empty list from each other and
from the symbol nil
.
Boolean constants evaluate to themselves, so they do not need to be quoted in programs.
#t ;; => #t
#f ;; => #f
#f ;; => #f '
(not obj) procedure
The not procedure returns #t
if obj is false,
and returns #f otherwise.
not #t) ;; => #f
(not 3) ;; => #f
(not (list 3)) ;; => #f
(not #f) ;; => #t
(not '()) ;; => #f
(not (list)) ;; => #f
(not 'nil) ;; => #f (
(boolean? obj) procedure
The boolean? predicate returns #t
if obj is
either #t
or #f
and returns #f
otherwise.
boolean? #f) ;; => #t
(boolean? 0) ;; => #f
(boolean? '()) ;; => #f (
(boolean=? **boolean_{1} boolean_{2} boolean_{3} … ) procedure
Returns #t
if all the arguments are #t
or
all are #f.
A pair (sometimes called a dotted pair) is a record structure with two fields called the car and cdr fields (for historical reasons). Pairs are created by the procedure cons. The car and cdr fields are accessed by the procedures car and cdr. The car and cdr fields are assigned by the procedures setcar! and setcdr!.
Pairs are used primarily to represent lists. A list can be defined recursively as either the empty list or a pair whose cdr is a list. More precisely, the set of lists is defined as the smallest set X such that
The empty list is in X.
If list is in X, then any pair whose cdr field contains list is also in X.
The objects in the car fields of successive pairs of a list are the elements of the list. For example, a twoelement list is a pair whose car is the first element and whose cdr is a pair whose car is the second element and whose cdr is the empty list. The length of a list is the number of elements, which is the same as the number of pairs.
The empty list is a special object of its own type. It is not a pair, it has no elements, and its length is zero.
Note: The above definitions imply that all lists have finite length and are terminated by the empty list.
The most general notation (external representation) for Scheme pairs is the “dotted” notation (c_{1} . c_{2}) where c_{1} is the value of the car field and c_{2} is the value of the cdr field. For example (4 . 5) is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the external representation of a pair, not an expression that evaluates to a pair.
A more streamlined notation can be used for lists: the elements of
the list are simply enclosed in parentheses and separated by spaces. The
empty list is written ()
. For example,
(a b c d e)
and
. (b . (c . (d . (e . ()))))) (a
are equivalent notations for a list of symbols.
A chain of pairs not ending in the empty list is called an improper list. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists:
. d) (a b c
is equivalent to
. (b . (c . d))) (a
Whether a given pair is a list depends upon what is stored in the cdr
field. When the setcdr!
procedure is used, an object can
be a list one moment and not the next:
define x (list 'a 'b 'c))
(define y x)
(;; => (a b c)
y list? y) ;; => #t
(setcdr! x 4) ;; => unspecified
(;; => (a . 4)
x eqv? x y) ;; => #t
(;; => (a . 4)
y list? y) ;; => #f
(setcdr! x x) ;; => unspecified
(list? x) ;; => #f (
Within literal expressions and representations of objects read by the
read
procedure, the forms ’
datum,
`datum,
,datum, and
,@datum denote twoelement lists whose first elements are the symbols
quote,
quasiquote,
unquote, and
unquotesplicing`,
respectively. The second element in each case is datum. This convention
is supported so that arbitrary Scheme programs can be represented as
lists. That is, according to Scheme’s grammar, every expression is also
a datum (see section [datum]). Among other things,
this permits the use of the read procedure to parse Scheme programs. See
section [externalreps].
(pair? obj) procedure
The pair? predicate returns #t
if obj is a
pair, and otherwise returns #f.
pair? '(a . b)) ;; => #t
(pair? '(a b c)) ;; => #t
(pair? '()) ;; => #f
(pair? '#(a b)) ;; => #f (
(cons obj_{1} obj_{2}) procedure
Returns a newly allocated pair whose car is obj_{1} and whose cdr is obj_{2}. The pair is guaranteed to be different (in the sense of eqv?) from every existing object.
cons 'a '()) ;; => (a)
(cons '(a) '(b c d)) ;; => ((a) b c d)
(cons "a" '(b c)) ;; => ("a" b c)
(cons 'a 3) ;; => (a . 3)
(cons '(a b) 'c) ;; => ((a b) . c) (
(car pair) procedure
Returns the contents of the car field of pair. Note that it is an error to take the car of the empty list.
car '(a b c)) ;; => a
(car '((a) b c d)) ;; => (a)
(car '(1 . 2)) ;; => 1
(car '()) ;; => error (
(cdr pair) procedure
Returns the contents of the cdr field of pair. Note that it is an error to take the cdr of the empty list.
cdr '((a) b c d)) ;; => (b c d)
(cdr '(1 . 2)) ;; => 2
(cdr '()) ;; => error (
(setcar! pair obj) procedure
Stores obj in the car field of pair.
define (f) (list 'notaconstantlist))
(define (g) '(constantlist))
(setcar! (f) 3) ;; => unspecified
(setcar! (g) 3) ;; => error (
(setcdr! pair obj) procedure
Stores obj in the cdr field of pair.
(cadr pair)
procedure
(caar pair) procedure
(cadr pair) procedure
(cdar pair) procedure
(cddr pair) procedure
These procedures are compositions of car and cdr as follows:
define (caar x) (car (car x)))
(define (cadr x) (car (cdr x)))
(define (cdar x) (cdr (car x)))
(define (cddr x) (cdr (cdr x))) (
(caaar pair) cxr library procedure
(caadr pair) cxr library procedure
(cdddar pair) cxr library procedure
(cddddr pair) cxr library procedure
These twentyfour procedures are further compositions of car and cdr on the same principles. For example, caddr could be defined by
define caddr (lambda (x) (car (cdr (cdr x))))) (
Arbitrary compositions up to four deep are provided.
(null? obj) procedure
Returns #t
if obj is the empty list, otherwise
returns #f.
(list? obj) procedure
Returns #t
if obj is a list. Otherwise, it
returns #f. By definition, all lists have finite length and are
terminated by the empty list.
list? '(a b c)) ;; => #t
(list? '()) ;; => #t
(list? '(a . b)) ;; => #f
(let ((x (list 'a)))
(setcdr! x x)
(list? x)) ;; => #f (
(makelist k) procedure
(makelist k fill) procedure
Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.
2 3) ;; => (3 3) (makelist
(list **obj … ) procedure
Returns a newly allocated list of its arguments.
list 'a (+ 3 4) 'c) ;; => (a 7 c)
(list) ;; => () (
(length list) procedure
Returns the length of list.
length '(a b c)) ;; => 3
(length '(a (b) (c d e))) ;; => 3
(length '()) ;; => 0 (
(append list … ) procedure
The last argument, if there is one, can be of any type.
Returns a list consisting of the elements of the first list followed by the elements of the other lists. If there are no arguments, the empty list is returned. If there is exactly one argument, it is returned. Otherwise the resulting list is always newly allocated, except that it shares structure with the last argument. An improper list results if the last argument is not a proper list.
append '(x) '(y)) ;; => (x y)
(append '(a) '(b c d)) ;; => (a b c d)
(append '(a (b)) '((c))) ;; => (a (b) (c))
(
append '(a b) '(c . d)) ;; => (a b c . d)
(append '() 'a) ;; => a (
(reverse list) procedure
Returns a newly allocated list consisting of the elements of list in reverse order.
reverse '(a b c)) ;; => (c b a)
(reverse '(a (b c) d (e (f)))) ;; => ((e (f)) d (b c) a) (
(listtail list k**) procedure
It is an error if list has fewer than k elements.
Returns the sublist of list obtained by omitting the first k elements. The listtail procedure could be defined by
define listtail
(lambda (x k)
(if (zero? k)
(
xlisttail (cdr x) ( k 1))))) (
(listref list k**) procedure
The list argument can be circular, but it is an error if list has k or fewer elements.
Returns the kth element of list. (This is the same
as the car of (listtail list k)
.)
listref '(a b c d) 2) ;; => c
(listref '(a b c d)
(exact (round 1.8))) ;; => c (
(listset! list k obj) procedure
It is an error if k is not a valid index of list.
The listset! procedure stores obj in element k of list.
let ((ls (list 'one 'two 'five!)))
(2 'three)
(listset! ls ;; => (one two three)
ls)
0 1 2) 1 "oops") ;; => error ; constant list (listset! '(
(memq obj list) procedure
(memv obj list) procedure
(member obj list) procedure
(member obj list compare) procedure
These procedures return the first sublist of list whose car
is obj, where the sublists of list are the nonempty
lists returned by (listtail list k)
for k less
than the length of list. If obj does not occur in
list, then #f
(not the empty list) is returned.
The memq procedure uses eq? to compare obj with the elements of
list, while memv uses eqv? and member uses compare, if
given, and equal? otherwise.
memq 'a '(a b c)) ;; => (a b c)
(memq 'b '(a b c)) ;; => (b c)
(memq 'a '(b c d)) ;; => #f
(memq (list 'a) '(b (a) c)) ;; => #f
(member (list 'a)
(;; => ((a) c)
'(b (a) c)) member "B"
("a" "b" "c")
'(stringci=?) ;; => ("b" "c")
memq 101 '(100 101 102)) ;; => unspecified
(memv 101 '(100 101 102)) ;; => (101 102) (
(assq obj alist) procedure
(assv obj alist) procedure
(assoc obj alist) procedure
(assoc obj alist compare) procedure
It is an error if alist (for “association list”) is not a list of pairs.
These procedures find the first pair in alist whose car
field is obj, and returns that pair. If no pair in
alist has obj as its car, then #f
(not
the empty list) is returned. The assq procedure uses eq? to compare
obj with the car fields of the pairs in alist, while
assv uses eqv? and assoc uses compare if given and equal?
otherwise.
define e '((a 1) (b 2) (c 3)))
(assq 'a e) ;; => (a 1)
(assq 'b e) ;; => (b 2)
(assq 'd e) ;; => #f
(assq (list 'a) '(((a)) ((b)) ((c))))
(;; => #f
assoc (list 'a) '(((a)) ((b)) ((c))))
(;; => ((a))
assoc 2.0 '((1 1) (2 4) (3 9)) =)
(;; => (2 4)
assq 5 '((2 3) (5 7) (11 13)))
(;; => unspecified
assv 5 '((2 3) (5 7) (11 13)))
(;; => (5 7)
Rationale: Although they are often used as predicates, memq,
memv, member, assq, assv, and assoc do not have question marks in their
names because they return potentially useful values rather than just
#t
or #f.
(listcopy obj) procedure
Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of eqv?) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in the sense of eqv?. An obj which is not a list is returned unchanged. It is an error if obj is a circular list.
define a '(1 8 2 8)) ; a may be immutable
(define b (listcopy a))
(setcar! b 3) ; b is mutable
(;; => (3 8 2 8)
b ;; => (1 8 2 8) a
Symbols are objects whose usefulness rests on the fact that two symbols are identical (in the sense of eqv?) if and only if their names are spelled the same way. For instance, they can be used the way enumerated values are used in other languages.
The rules for writing a symbol are exactly the same as the rules for writing an identifier; see sections [syntaxsection] and [identifiersyntax].
It is guaranteed that any symbol that has been returned as part of a literal expression, or read using the read procedure, and subsequently written out using the write procedure, will read back in as the identical symbol (in the sense of eqv?).
Note: Some implementations have values known as “uninterned symbols,” which defeat write/read invariance, and also violate the rule that two symbols are the same if and only if their names are spelled the same. This report does not specify the behavior of implementationdependent extensions.
(symbol? obj) procedure
Returns #t
if obj is a symbol, otherwise
returns #f.
symbol? 'foo) ;; => #t
(symbol? (car '(a b))) ;; => #t
(symbol? "bar") ;; => #f
(symbol? 'nil) ;; => #t
(symbol? '()) ;; => #f
(symbol? #f) ;; => #f (
(symbol=? **symbol_{1} symbol_{2} symbol_{3} … ) procedure
Returns #t
if all the arguments all have the same names
in the sense of string=?.
Note: The definition above assumes that none of the arguments are uninterned symbols.
(symbol>string symbol) procedure
Returns the name of symbol as a string, but without adding
escapes. It is an error to apply mutation procedures like
stringset!
to strings returned by this procedure.
symbol>string 'flyingfish)
(;; => "flyingfish"
symbol>string 'Martin) ;; => "Martin"
(symbol>string
(string>symbol "Malvina"))
(;; => "Malvina"
(string>symbol string) procedure
Returns the symbol whose name is string. This procedure can create symbols with names containing special characters that would require escaping when written, but does not interpret escapes in its input.
string>symbol "mISSISSIppi") ;; => mISSISSIppi
(eqv? 'bitBlt (string>symbol "bitBlt")) ;; => #t
(eqv? 'LollyPop
(string>symbol
(symbol>string 'LollyPop))) ;; => #t
(string=? "K. Harper, M.D."
(symbol>string
(string>symbol "K. Harper, M.D."))) ;; => #t (
Characters are objects that represent printed characters such as letters and digits. All Scheme implementations must support at least the ASCII character repertoire: that is, Unicode characters U+0000 through U+007F. Implementations may support any other Unicode characters they see fit, and may also support nonUnicode characters as well. Except as otherwise specified, the result of applying any of the following procedures to a nonUnicode character is implementationdependent.
Characters are written using the notation #``'
character
or #``'
character name or
#``'
xhex scalar value.
The following character names must be supported by all implementations with the given values. Implementations may add other names provided they cannot be interpreted as hex scalar values preceded by x.
; U+0007  
; U+0008  
; U+007F  
; U+001B  
; the linefeed character, U+000A  
; the null character, U+0000  
; the return character, U+000D  
; the preferred way to write a space  
; the tab character, U+0009 
Here are some additional examples:
; lower case letter  
; upper case letter  
; left parenthesis  
; the space character  
; λ (if character is supported)  
; ι (if character and name are supported) 
Case is significant in #``'
character, and in
#``'
⟨character name⟩, but not in
#``'
xhex scalar value. If character in
#``'
character is alphabetic, then any character immediately
following character cannot be one that can appear in an identifier. This
rule resolves the ambiguous case where, for example, the sequence of
characters “#' space
” could be taken to be either a
representation of the space character or a representation of the
character “#' s
” followed by a representation of the symbol
“pace
.”
Characters written in the #``'
notation are
selfevaluating. That is, they do not have to be quoted in programs.
Some of the procedures that operate on characters ignore the
difference between upper case and lower case. The procedures that ignore
case have “ci
” (for “case insensitive”) embedded in their
names.
(char? obj) procedure
Returns #t
if obj is a character, otherwise
returns #f.
(char=? char_{1} char_{2} char_{3} … ) procedure
(char<? char_{1} char_{2} char_{3} … ) procedure
(char>? char_{1} char_{2} char_{3} … ) procedure
(char<=? char_{1} char_{2} char_{3} … ) procedure
(char>=? char_{1} char_{2} char_{3} … ) procedure
These procedures return #t
if the results of passing
their arguments to charinteger are respectively equal, monotonically
increasing, monotonically decreasing, monotonically nondecreasing, or
monotonically nonincreasing.
These predicates are required to be transitive.
(charci=? char_{1} char_{2} char_{3} … ) char library procedure
(charci<? char_{1} char_{2} char_{3} … ) char library procedure
(charci>? char_{1} char_{2} char_{3} … ) char library procedure
(charci<=? char_{1} char_{2} char_{3} … ) char library procedure
(charci>=? char_{1} char_{2} char_{3} … ) char library procedure
These procedures are similar to char=? et cetera, but they treat
upper case and lower case letters as the same. For example,
(charci=? #'
A #'
a) returns #t.
Specifically, these procedures behave as if charfoldcase were applied to their arguments before they were compared.
(charalphabetic? char) char library procedure
(charnumeric? char) char library procedure
(charwhitespace? char) char library procedure
(charuppercase? letter) char library procedure
(charlowercase? letter) char library procedure
These procedures return #t
if their arguments are
alphabetic, numeric, whitespace, upper case, or lower case characters,
respectively, otherwise they return #f.
Specifically, they must return #t
when applied to
characters with the Unicode properties Alphabetic, Numeric_Type=Decimal,
White_Space, Uppercase, and Lowercase respectively, and #f
when applied to any other Unicode characters. Note that many Unicode
characters are alphabetic but neither upper nor lower case.
(digitvalue char) char library procedure
This procedure returns the numeric value (0 to 9) of its argument if
it is a numeric digit (that is, if charnumeric? returns #t), or
#f
on any other character.
#\3) ;; => 3
(digitvalue #\x0664) ;; => 4
(digitvalue #\x0AE6) ;; => 0
(digitvalue #\x0EA6) ;; => #f (digitvalue
(char>integer char) procedure
(integer>char n) procedure
Given a Unicode character, charinteger returns an exact integer
between 0 and #xD7FF
or between #xE000
and
#x10FFFF
which is equal to the Unicode scalar value of that
character. Given a nonUnicode character, it returns an exact integer
greater than #x10FFFF
. This is true independent of whether
the implementation uses the Unicode representation internally.
Given an exact integer that is the value returned by a character when charinteger is applied to it, integerchar returns that character.
(charupcase char) char library procedure
(chardowncase char) char library procedure
(charfoldcase char) char library procedure
The charupcase procedure, given an argument that is the lowercase part of a Unicode casing pair, returns the uppercase member of the pair, provided that both characters are supported by the Scheme implementation. Note that languagesensitive casing pairs are not used. If the argument is not the lowercase member of such a pair, it is returned.
The chardowncase procedure, given an argument that is the uppercase part of a Unicode casing pair, returns the lowercase member of the pair, provided that both characters are supported by the Scheme implementation. Note that languagesensitive casing pairs are not used. If the argument is not the uppercase member of such a pair, it is returned.
The charfoldcase procedure applies the Unicode simple casefolding algorithm to its argument and returns the result. Note that languagesensitive folding is not used. If the character that results from folding is not supported by the implementation, the argument is returned. See UAX #44 (part of the Unicode Standard) for details.
Note that many Unicode lowercase characters do not have uppercase equivalents.
Strings are sequences of characters. Strings are written as sequences
of characters enclosed within quotation marks (“). Within a string
literal, various escape sequences represent characters other than
themselves. Escape sequences always start with a backslash
('
):
'
a : alarm, U+0007
'
b : backspace, U+0008
'
t : character tabulation, U+0009
'
n : linefeed, U+000A
'
r : return, U+000D
' ``"
: double quote, U+0022
' ``'
: backslash, U+005C
'
 : vertical line, U+007C
'
intraline whitespaceline ending
intraline whitespace : nothing
'
xhex scalar value; : specified character (note the
terminating semicolon).
The result is unspecified if any other character in a string occurs after a backslash.
Except for a line ending, any character outside of an escape sequence
stands for itself in the string literal. A line ending which is preceded
by '
intraline whitespace expands to nothing (along with any
trailing intraline whitespace), and can be used to indent strings for
improved legibility. Any other line ending has the same effect as
inserting a '
n character into the string.
Examples:
"The word \"recursion\" has many meanings."
"Another example:\ntwo lines of text"
"Here's text \
containing just one line"
"\x03B1; is named GREEK SMALL LETTER ALPHA."
The length of a string is the number of characters that it contains. This number is an exact, nonnegative integer that is fixed when the string is created. The valid indexes of a string are the exact nonnegative integers less than the length of the string. The first character of a string has index 0, the second has index 1, and so on.
Some of the procedures that operate on strings ignore the difference between upper and lower case. The names of the versions that ignore case end with “ci” (for “case insensitive”).
Implementations may forbid certain characters from appearing in
strings. However, with the exception of #' null
, ASCII
characters must not be forbidden. For example, an implementation might
support the entire Unicode repertoire, but only allow characters U+0001
to U+00FF (the Latin1 repertoire without #' null
) in
strings.
It is an error to pass such a forbidden character to makestring, string, stringset!, or stringfill!, as part of the list passed to liststring, or as part of the vector passed to vectorstring (see section [vectortostring]), or in UTF8 encoded form within a bytevector passed to utf8string (see section [utf8tostring]). It is also an error for a procedure passed to stringmap (see section [stringmap]) to return a forbidden character, or for readstring (see section [readstring]) to attempt to read one.
(string? obj) procedure
Returns #t
if obj is a string, otherwise
returns #f.
(makestring k) procedure
(makestring **k char) procedure
The makestring procedure returns a newly allocated string of length k. If char is given, then all the characters of the string are initialized to char, otherwise the contents of the string are unspecified.
(string char … ) procedure
Returns a newly allocated string composed of the arguments. It is analogous to list.
(stringlength string) procedure
Returns the number of characters in the given string.
(stringref string k**) procedure
It is an error if k is not a valid index of string.
The stringref procedure returns character k of string using zeroorigin indexing. There is no requirement for this procedure to execute in constant time.
(stringset! string k char) procedure
It is an error if k is not a valid index of string.
The stringset! procedure stores char in element k of string. There is no requirement for this procedure to execute in constant time.
define (f) (makestring 3 #\*))
(define (g) "***")
(stringset! (f) 0 #\?) ;; => unspecified
(stringset! (g) 0 #\?) ;; => error
(stringset! (symbol>string 'immutable)
(0
#\?) ;; => error
(string=? string_{1} string_{2} string_{3} … ) procedure
Returns #t
if all the strings are the same length and
contain exactly the same characters in the same positions, otherwise
returns #f.
(stringci=? string_{1} string_{2} string_{3} … ) char library procedure
Returns #t
if, after casefolding, all the strings are
the same length and contain the same characters in the same positions,
otherwise returns #f. Specifically, these procedures behave as if
stringfoldcase were applied to their arguments before comparing
them.
(string<? string_{1} string_{2} string_{3} … ) procedure
(stringci<? string_{1} string_{2} string_{3} … ) char library procedure
(string>? string_{1} string_{2} string_{3} … ) procedure
(stringci>? string_{1} string_{2} string_{3} … ) char library procedure
(string<=? string_{1} string_{2} string_{3} … ) procedure
(stringci<=? string_{1} string_{2} string_{3} … ) char library procedure
(string>=? string_{1} string_{2} string_{3} … ) procedure
(stringci>=? string_{1} string_{2} string_{3} … ) char library procedure
These procedures return #t
if their arguments are
(respectively): monotonically increasing, monotonically decreasing,
monotonically nondecreasing, or monotonically nonincreasing.
These predicates are required to be transitive.
These procedures compare strings in an implementationdefined way. One approach is to make them the lexicographic extensions to strings of the corresponding orderings on characters. In that case, string<? would be the lexicographic ordering on strings induced by the ordering char<? on characters, and if the two strings differ in length but are the same up to the length of the shorter string, the shorter string would be considered to be lexicographically less than the longer string. However, it is also permitted to use the natural ordering imposed by the implementation’s internal representation of strings, or a more complex localespecific ordering.
In all cases, a pair of strings must satisfy exactly one of string<?, string=?, and string>?, and must satisfy string<=? if and only if they do not satisfy string>? and string>=? if and only if they do not satisfy string<?.
The “ci
” procedures behave as if they applied
stringfoldcase to their arguments before invoking the corresponding
procedures without “ci
”.
(stringupcase string) char library procedure
(stringdowncase string) char library procedure
(stringfoldcase string) char library procedure
These procedures apply the Unicode full string uppercasing, lowercasing, and casefolding algorithms to their arguments and return the result. In certain cases, the result differs in length from the argument. If the result is equal to the argument in the sense of string=?, the argument may be returned. Note that languagesensitive mappings and foldings are not used.
The Unicode Standard prescribes special treatment of the Greek letter Σ, whose normal lowercase form is σ but which becomes ς at the end of a word. See UAX #44 (part of the Unicode Standard) for details. However, implementations of stringdowncase are not required to provide this behavior, and may choose to change Σ to σ in all cases.
(substring string start end) procedure
The substring procedure returns a newly allocated string formed from the characters of string beginning with index start and ending with index end. This is equivalent to calling stringcopy with the same arguments, but is provided for backward compatibility and stylistic flexibility.
(stringappend **string … ) procedure
Returns a newly allocated string whose characters are the concatenation of the characters in the given strings.
(string>list string) procedure
(string>list string start) procedure
(string>list string start end) procedure
(list>string list) procedure
It is an error if any element of list is not a character.
The stringlist procedure returns a newly allocated list of the characters of string between start and end. liststring returns a newly allocated string formed from the elements in the list list. In both procedures, order is preserved. stringlist and liststring are inverses so far as equal? is concerned.
(stringcopy string) procedure
(stringcopy string start) procedure
(stringcopy string start end) procedure
Returns a newly allocated copy of the part of the given string between start and end.
(stringcopy! to at from) procedure
(stringcopy! to at from start) procedure
(stringcopy! to at from start end) procedure
It is an error if at is less than zero or greater than the length of to. It is also an error if ( (stringlength to) at) is less than ( end start).
Copies the characters of string from between start and end to string to, starting at at. The order in which characters are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary string and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
define a "12345")
(define b (stringcopy "abcde"))
(1 a 0 2)
(stringcopy! b ;; => "a12de" b
(stringfill! string fill) procedure
(stringfill! string fill start) procedure
(stringfill! string fill start end) procedure
It is an error if fill is not a character.
The stringfill! procedure stores fill in the elements of string between start and end.
Vectors are heterogeneous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time needed to access a randomly chosen element is typically less for the vector than for the list.
The length of a vector is the number of elements that it contains. This number is a nonnegative integer that is fixed when the vector is created. The valid indexes of a vector are the exact nonnegative integers less than the length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than the length of the vector.
Vectors are written using the notation #(obj ...)
. For
example, a vector of length 3 containing the number zero in element 0,
the list (2 2 2 2) in element 1, and the string “Anna” in element 2 can
be written as follows:
0 (2 2 2 2) "Anna") #(
Vector constants are selfevaluating, so they do not need to be quoted in programs.
(vector? obj) procedure
Returns #t
if obj is a vector; otherwise
returns #f.
(makevector k) procedure
(makevector k fill) procedure
Returns a newly allocated vector of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.
(vector obj … ) procedure
Returns a newly allocated vector whose elements contain the given arguments. It is analogous to list.
vector 'a 'b 'c) ;; => #(a b c) (
(vectorlength vector) procedure
Returns the number of elements in vector as an exact integer.
(vectorref vector k) procedure
It is an error if k is not a valid index of vector.
The vectorref procedure returns the contents of element k of vector.
vectorref '#(1 1 2 3 5 8 13 21)
(5) ;; => 8
vectorref '#(1 1 2 3 5 8 13 21)
(exact
(round (* 2 (acos 1))))) ;; => 13 (
(vectorset! vector k obj) procedure
It is an error if k is not a valid index of vector.
The vectorset! procedure stores obj in element k of vector.
let ((vec (vector 0 '(2 2 2 2) "Anna")))
(vectorset! vec 1 '("Sue" "Sue"))
(;; => #(0 ("Sue" "Sue") "Anna")
vec)
vectorset! '#(0 1 2) 1 "doe") ;; => error ; constant vector (
(vector>list vector) procedure
(vector>list vector start) procedure
(vector>list vector start end) procedure
(list>vector list) procedure
The vector>list procedure returns a newly allocated list of the objects contained in the elements of vector between start and end. The list>vector procedure returns a newly created vector initialized to the elements of the list list.
In both procedures, order is preserved.
vector>list '#(dah dah didah)) ;; => (dah dah didah)
(vector>list '#(dah dah didah) 1 2) ;; => (dah)
(list>vector '(dididit dah)) ;; => #(dididit dah) (
(vector>string vector) procedure
(vector>string vector start) procedure
(vector>string vector start end) procedure
(string>vector string) procedure
(string>vector string start) procedure
(string>vector string start end) procedure
It is an error if any element of vector between start and end is not a character.
The vector>string procedure returns a newly allocated string of the objects contained in the elements of vector between start and end. The string>vector procedure returns a newly created vector initialized to the elements of the string string between start and end.
In both procedures, order is preserved.
"ABC") ;; => #(#\A #\B #\C)
(string>vector
(vector>string#\1 #\2 #\3) ;; => "123" #(
(vectorcopy vector) procedure
(vectorcopy vector start) procedure
(vectorcopy vector start end) procedure
Returns a newly allocated copy of the elements of the given vector between start and end. The elements of the new vector are the same (in the sense of eqv?) as the elements of the old.
define a #(1 8 2 8)) ; a may be immutable
(define b (vectorcopy a))
(vectorset! b 0 3) ; b is mutable
(;; => #(3 8 2 8)
b define c (vectorcopy b 1 3))
(;; => #(8 2) c
(vectorcopy! to at from) procedure
(vectorcopy! to at from start) procedure
(vectorcopy! to at from start end) procedure
It is an error if at is less than zero or greater than the length of to. It is also an error if ( (vectorlength to) at) is less than ( end start).
Copies the elements of vector from between start and end to vector to, starting at at. The order in which elements are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary vector and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
define a (vector 1 2 3 4 5))
(define b (vector 10 20 30 40 50))
(1 a 0 2)
(vectorcopy! b ;; => #(10 1 2 40 50) b
(vectorappend **vector … ) procedure
Returns a newly allocated vector whose elements are the concatenation of the elements of the given vectors.
;; => #(a b c d e f) (vectorappend #(a b c) #(d e f))
(vectorfill! vector fill) procedure
(vectorfill! vector fill start) procedure
(vectorfill! vector fill start end) procedure
The vectorfill! procedure stores fill in the elements of vector between start and end.
define a (vector 1 2 3 4 5))
(vectorfill! a 'smash 2 4)
(;; => #(1 2 smash smash 5) a
Bytevectors represent blocks of binary data. They are fixedlength sequences of bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A bytevector is typically more spaceefficient than a vector containing the same values.
The length of a bytevector is the number of elements that it contains. This number is a nonnegative integer that is fixed when the bytevector is created. The valid indexes of a bytevector are the exact nonnegative integers less than the length of the bytevector, starting at index zero as with vectors.
Bytevectors are written using the notation
#u8(byte ...)
. For example, a bytevector of length 3
containing the byte 0 in element 0, the byte 10 in element 1, and the
byte 5 in element 2 can be written as follows:
0 10 5) #u8(
Bytevector constants are selfevaluating, so they do not need to be quoted in programs.
(bytevector? obj) procedure
Returns #t
if obj is a bytevector. Otherwise,
#f
is returned.
(makebytevector k) procedure
(makebytevector k byte) procedure
The makebytevector procedure returns a newly allocated bytevector of length k. If byte is given, then all elements of the bytevector are initialized to byte, otherwise the contents of each element are unspecified.
makebytevector 2 12) ;; => #u8(12 12) (
(bytevector **byte … ) procedure
Returns a newly allocated bytevector containing its arguments.
1 3 5 1 3 5) ;; => #u8(1 3 5 1 3 5)
(bytevector ;; => #u8() (bytevector)
(bytevectorlength bytevector) procedure
Returns the length of bytevector in bytes as an exact integer.
(bytevectoru8ref bytevector k) procedure
It is an error if k is not a valid index of bytevector.
Returns the kth byte of bytevector.
bytevectoru8ref '#u8(1 1 2 3 5 8 13 21)
(5) ;; => 8
(bytevectoru8set! bytevector k byte) procedure
It is an error if k is not a valid index of bytevector.
Stores byte as the kth byte of bytevector.
let ((bv (bytevector 1 2 3 4)))
(bytevectoru8set! bv 1 3)
(;; => #u8(1 3 3 4) bv)
(bytevectorcopy bytevector) procedure
(bytevectorcopy bytevector start) procedure
(bytevectorcopy bytevector start end) procedure
Returns a newly allocated bytevector containing the bytes in bytevector between start and end.
define a #u8(1 2 3 4 5))
(bytevectorcopy a 2 4)) ;; => #u8(3 4) (
(bytevectorcopy! to at from) procedure
(bytevectorcopy! to at from start) procedure
(bytevectorcopy! to at from start end) procedure
It is an error if at is less than zero or greater than the length of to. It is also an error if ( (bytevectorlength to) at) is less than ( end start).
Copies the bytes of bytevector from between start and end to bytevector to, starting at at. The order in which bytes are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary bytevector and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
define a (bytevector 1 2 3 4 5))
(define b (bytevector 10 20 30 40 50))
(bytevectorcopy! b 1 a 0 2)
(;; => #u8(10 1 2 40 50) b
Note: This procedure appears in R^{6}RS, but places the source before the destination, contrary to other such procedures in Scheme.
(bytevectorappend **bytevector … ) procedure
Returns a newly allocated bytevector whose elements are the concatenation of the elements in the given bytevectors.
0 1 2) #u8(3 4 5)) ;; => #u8(0 1 2 3 4 5) (bytevectorappend #u8(
(utf8>string bytevector) procedure
(utf8>string bytevector start) procedure
(utf8>string bytevector start end) procedure
(string>utf8 string) procedure
(string>utf8 string start) procedure
(string>utf8 string start end) procedure
It is an error for bytevector to contain invalid UTF8 byte sequences.
These procedures translate between strings and bytevectors that encode those strings using the UTF8 encoding. The utf8string procedure decodes the bytes of a bytevector between start and end and returns the corresponding string; the stringutf8 procedure encodes the characters of a string between start and end and returns the corresponding bytevector.
utf8>string #u8(#x41)) ;; => "A"
(string>utf8 "λ") ;; => #u8(#xCE #xBB) (
This section describes various primitive procedures which control the flow of program execution in special ways. Procedures in this section that invoke procedure arguments always do so in the same dynamic environment as the call of the original procedure. The procedure? predicate is also described here.
(procedure? obj) procedure Returns #t
if
obj is a procedure, otherwise returns #f.
procedure? car) ;; => #t
(procedure? 'car) ;; => #f
(procedure? (lambda (x) (* x x)))
(;; => #t
procedure? '(lambda (x) (* x x)))
(;; => #f
callwithcurrentcontinuation procedure?)
(;; => #t
(apply proc arg_{1} … args) procedure
The apply procedure calls proc with the elements of the list
(append (list *arg<sub>1</sub>* … ) *args*)
as
the actual arguments.
+ (list 3 4)) ;; => 7
(apply
define compose
(lambda (f g)
(lambda args
(
(f (apply g args)))))
sqrt *) 12 75) ;; => 30 ((compose
(map proc list_{1} list_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are lists and return a single value.
The map procedure applies proc elementwise to the elements of the lists and returns a list of the results, in order. If more than one list is given and not all lists have the same length, map terminates when the shortest list runs out. The lists can be circular, but it is an error if all of them are circular. It is an error for proc to mutate any of the lists. The dynamic order in which proc is applied to the elements of the lists is unspecified. If multiple returns occur from map, the values returned by earlier returns are not mutated.
cadr '((a b) (d e) (g h))) ;; => (b e h)
(map
lambda (n) (expt n n))
(map (1 2 3 4 5)) ;; => (1 4 27 256 3125)
'(
+ '(1 2 3) '(4 5 6 7)) ;; => (5 7 9)
(map
let ((count 0))
(lambda (ignored)
(map (set! count (+ count 1))
(
count);; => (1 2) \var{or} (2 1) '(a b)))
(stringmap proc string_{1} string_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are strings and return a single character.
The stringmap procedure applies proc elementwise to the elements of the strings and returns a string of the results, in order. If more than one string is given and not all strings have the same length, stringmap terminates when the shortest string runs out. The dynamic order in which proc is applied to the elements of the strings is unspecified. If multiple returns occur from stringmap, the values returned by earlier returns are not mutated.
charfoldcase "AbdEgH") ;; => "abdegh"
(stringmap
(stringmaplambda (c)
(integer>char (+ 1 (char>integer c))))
("HAL") ;; => "IBM"
(stringmaplambda (c k)
(if (eqv? k #\u) charupcase chardowncase)
((
c))"studlycaps xxx"
"ululululul") ;; => "StUdLyCaPs"
(vectormap proc vector_{1} vector_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are vectors and return a single value.
The vectormap procedure applies proc elementwise to the elements of the vectors and returns a vector of the results, in order. If more than one vector is given and not all vectors have the same length, vectormap terminates when the shortest vector runs out. The dynamic order in which proc is applied to the elements of the vectors is unspecified. If multiple returns occur from vectormap, the values returned by earlier returns are not mutated.
cadr '#((a b) (d e) (g h))) ;; => #(b e h)
(vectormap
lambda (n) (expt n n))
(vectormap (1 2 3 4 5)) ;; => #(1 4 27 256 3125)
'#(
+ '#(1 2 3) '#(4 5 6 7)) ;; => #(5 7 9)
(vectormap
let ((count 0))
(
(vectormaplambda (ignored)
(set! count (+ count 1))
(
count);; => #(1 2) \var{or} #(2 1) '#(a b)))
(foreach proc list_{1} list_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are lists.
The arguments to foreach are like the arguments to map, but foreach calls proc for its side effects rather than for its values. Unlike map, foreach is guaranteed to call proc on the elements of the lists in order from the first element(s) to the last, and the value returned by foreach is unspecified. If more than one list is given and not all lists have the same length, foreach terminates when the shortest list runs out. The lists can be circular, but it is an error if all of them are circular.
It is an error for proc to mutate any of the lists.
let ((v (makevector 5)))
(foreach (lambda (i)
(vectorset! v i (* i i)))
(0 1 2 3 4))
'(;; => #(0 1 4 9 16) v)
(stringforeach proc string_{1} string_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are strings.
The arguments to stringforeach are like the arguments to stringmap, but stringforeach calls proc for its side effects rather than for its values. Unlike stringmap, stringforeach is guaranteed to call proc on the elements of the strings in order from the first element(s) to the last, and the value returned by stringforeach is unspecified. If more than one string is given and not all strings have the same length, stringforeach terminates when the shortest string runs out. It is an error for proc to mutate any of the strings.
let ((v '()))
(
(stringforeachlambda (c) (set! v (cons (char>integer c) v)))
("abcde")
;; => (101 100 99 98 97) v)
(vectorforeach proc vector_{1} vector_{2} … ) procedure
It is an error if proc does not accept as many arguments as there are vectors.
The arguments to vectorforeach are like the arguments to vectormap, but vectorforeach calls proc for its side effects rather than for its values. Unlike vectormap, vectorforeach is guaranteed to call proc on the elements of the vectors in order from the first element(s) to the last, and the value returned by vectorforeach is unspecified. If more than one vector is given and not all vectors have the same length, vectorforeach terminates when the shortest vector runs out. It is an error for proc to mutate any of the vectors.
let ((v (makelist 5)))
(
(vectorforeachlambda (i) (listset! v i (* i i)))
(0 1 2 3 4))
'#(;; => (0 1 4 9 16) v)
(callwithcurrentcontinuation proc) procedure
(call/cc proc) procedure
It is an error if proc does not accept one argument.
The procedure callwithcurrentcontinuation (or its equivalent
abbreviation call/cc) packages the current continuation (see the
rationale below) as an “escape procedure” and passes it as an argument
to proc. The escape procedure is a Scheme procedure that, if it
is later called, will abandon whatever continuation is in effect at that
later time and will instead use the continuation that was in effect when
the escape procedure was created. Calling the escape procedure will
cause the invocation of before and after thunks
installed using dynamicwind
.
The escape procedure accepts the same number of arguments as the
continuation to the original call to
callwithcurrentcontinuation
. Most continuations take
only one value. Continuations created by the callwithvalues procedure
(including the initialization expressions of definevalues, letvalues,
and let*values expressions), take the number of values that the
consumer expects. The continuations of all nonfinal expressions within
a sequence of expressions, such as in lambda, caselambda, begin, let,
let*, letrec, letrec*, letvalues, let*values, letsyntax,
letrecsyntax, parameterize, guard, case, cond, when, and unless
expressions, take an arbitrary number of values because they discard the
values passed to them in any event. The effect of passing no values or
more than one value to continuations that were not created in one of
these ways is unspecified.
The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It can be stored in variables or data structures and can be called as many times as desired. However, like the raise and error procedures, it never returns to its caller.
The following examples show only the simplest ways in which callwithcurrentcontinuation is used. If all real uses were as simple as these examples, there would be no need for a procedure with the power of callwithcurrentcontinuation.
callwithcurrentcontinuation
(lambda (exit)
(foreach (lambda (x)
(if (negative? x)
(
(exit x)))54 0 37 3 245 19))
'(#t)) ;; => 3
define listlength
(lambda (obj)
(callwithcurrentcontinuation
(lambda (return)
(letrec ((r
(lambda (obj)
(cond ((null? obj) 0)
(pair? obj)
((+ (r (cdr obj)) 1))
(else (return #f))))))
(
(r obj))))))
1 2 3 4)) ;; => 4
(listlength '(
. c)) ;; => #f (listlength '(a b
Rationale:
A common use of callwithcurrentcontinuation is for structured, nonlocal exits from loops or procedure bodies, but in fact callwithcurrentcontinuation is useful for implementing a wide variety of advanced control structures. In fact, raise and guard provide a more structured mechanism for nonlocal exits.
Whenever a Scheme expression is evaluated there is a continuation wanting the result of the expression. The continuation represents an entire (default) future for the computation. If the expression is evaluated at the REPL, for example, then the continuation might take the result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions specified by user code, as in a continuation that will take the result, multiply it by the value stored in a local variable, add seven, and give the answer to the REPL’s continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and programmers do not think much about them. On rare occasions, however, a programmer needs to deal with continuations explicitly. The callwithcurrentcontinuation procedure allows Scheme programmers to do that by creating a procedure that acts just like the current continuation.
(values obj …) procedure
Delivers all of its arguments to its continuation. The
values
procedure might be defined as follows:
define (values . things)
(callwithcurrentcontinuation
(lambda (cont) (apply cont things)))) (
(callwithvalues producer consumer) procedure
Calls its producer argument with no arguments and a
continuation that, when passed some values, calls the consumer
procedure with those values as arguments. The continuation for the call
to consumer is the continuation of the call to
callwithvalues
.
callwithvalues (lambda () (values 4 5))
(lambda (a b) b))
(;; => 5
callwithvalues * ) ;; => 1 (
(dynamicwind before thunk after) procedure
Calls thunk without arguments, returning the result(s) of
this call. Before and after are called, also without
arguments, as required by the following rules. Note that, in the absence
of calls to continuations captured using
callwithcurrentcontinuation
, the three arguments are
called once each, in order. Before is called whenever execution
enters the dynamic extent of the call to thunk and
after is called whenever it exits that dynamic extent. The
dynamic extent of a procedure call is the period between when the call
is initiated and when it returns. The before and after
thunks are called in the same dynamic environment as the call to
dynamicwind. In Scheme, because of callwithcurrentcontinuation, the
dynamic extent of a call is not always a single, connected time period.
It is defined as follows:
The dynamic extent is entered when execution of the body of the called procedure begins.
The dynamic extent is also entered when execution is not within the dynamic extent and a continuation is invoked that was captured (using callwithcurrentcontinuation) during the dynamic extent.
It is exited when the called procedure returns.
It is also exited when execution is within the dynamic extent and a continuation is invoked that was captured while not within the dynamic extent.
If a second call to dynamicwind occurs within the dynamic extent of the call to thunk and then a continuation is invoked in such a way that the afters from these two invocations of dynamicwind are both to be called, then the after associated with the second (inner) call to dynamicwind is called first.
If a second call to dynamicwind occurs within the dynamic extent of the call to thunk and then a continuation is invoked in such a way that the befores from these two invocations of dynamicwind are both to be called, then the before associated with the first (outer) call to dynamicwind is called first.
If invoking a continuation requires calling the before from one call to dynamicwind and the after from another, then the after is called first.
The effect of using a captured continuation to enter or exit the dynamic extent of a call to before or after is unspecified.
let ((path '())
(#f))
(c let ((add (lambda (s)
(set! path (cons s path)))))
(dynamicwind
(lambda () (add 'connect))
(lambda ()
(callwithcurrentcontinuation
(add (lambda (c0)
(set! c c0)
(
'talk1))))lambda () (add 'disconnect)))
(if (< (length path) 4)
(
(c 'talk2)reverse path))))
(;; => (connect talk1 disconnect connect talk2 disconnect)
This section describes Scheme’s exceptionhandling and exceptionraising procedures. For the concept of Scheme exceptions, see section [errorsituations]. See also [guard] for the guard syntax.
Exception handlers are oneargument procedures that determine the action the program takes when an exceptional situation is signaled. The system implicitly maintains a current exception handler in the dynamic environment.
The program raises an exception by invoking the current exception handler, passing it an object encapsulating information about the exception. Any procedure accepting one argument can serve as an exception handler and any object can be used to represent an exception.
(withexceptionhandler handler thunk) procedure
It is an error if handler does not accept one argument. It is also an error if thunk does not accept zero arguments.
The withexceptionhandler procedure returns the results of invoking thunk. Handler is installed as the current exception handler in the dynamic environment used for the invocation of thunk.
callwithcurrentcontinuation
(lambda (k)
(withexceptionhandler
(lambda (x)
(display "condition: ")
(write x)
(newline)
(
(k 'exception))lambda ()
(+ 1 (raise 'anerror))))))
(;; => exception and prints condition: anerror
withexceptionhandler
(lambda (x)
(display "something went wrong\n"))
(lambda ()
(+ 1 (raise 'anerror))))
(;; prints something went wrong
After printing, the second example then raises another exception.
(raise obj) procedure
Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as that of the call to raise, except that the current exception handler is the one that was in place when the handler being called was installed. If the handler returns, a secondary exception is raised in the same dynamic environment as the handler. The relationship between obj and the object raised by the secondary exception is unspecified.
(raisecontinuable obj) procedure
Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as the call to raisecontinuable, except that: (1) the current exception handler is the one that was in place when the handler being called was installed, and (2) if the handler being called returns, then it will again become the current exception handler. If the handler returns, the values it returns become the values returned by the call to raisecontinuable.
withexceptionhandler
(lambda (con)
(cond
(string? con)
((display con))
(else
(display "a warning has been issued")))
(42)
lambda ()
(+ (raisecontinuable "should be a number")
(23)))
;; prints: should be a number
;; => 65
(error **message obj …) procedure
Message should be a string.
Raises an exception as if by calling raise on a newly allocated
implementationdefined object which encapsulates the information
provided by message, as well as any objs, known as the
irritants. The procedure errorobject? must return
#t
on such objects.
define (nulllist? l)
(cond ((pair? l) #f)
(null? l) #t)
((else
(error
("nulllist?: argument out of domain"
l))))
(errorobject? obj) procedure
Returns #t
if obj is an object created by error
or one of an implementationdefined set of objects. Otherwise, it
returns #f. The objects used to signal errors, including those which
satisfy the predicates fileerror? and readerror?, may or may not
satisfy errorobject?.
(errorobjectmessage errorobject) procedure
Returns the message encapsulated by errorobject.
(errorobjectirritants errorobject) procedure
Returns a list of the irritants encapsulated by errorobject.
(readerror? obj) procedure
(fileerror? obj) procedure
Error type predicates. Returns #t
if obj is an
object raised by the read procedure or by the inability to open an input
or output port on a file, respectively. Otherwise, it returns #f.
(environment list_{1} … ) eval library procedure
This procedure returns a specifier for the environment that results by starting with an empty environment and then importing each list, considered as an import set, into it. (See section [libraries] for a description of import sets.) The bindings of the environment represented by the specifier are immutable, as is the environment itself.
(schemereportenvironment version) r5rs library procedure
If version is equal to 5, corresponding to R^{5}RS, schemereportenvironment returns a specifier for an environment that contains only the bindings defined in the R^{5}RS library. Implementations must support this value of version.
Implementations may also support other values of version, in which case they return a specifier for an environment containing bindings corresponding to the specified version of the report. If version is neither 5 nor another value supported by the implementation, an error is signaled.
The effect of defining or assigning (through the use of eval) an identifier bound in a schemereportenvironment (for example car) is unspecified. Thus both the environment and the bindings it contains may be immutable.
(nullenvironment version) r5rs library procedure
If version is equal to 5, corresponding to R^{5}RS, the nullenvironment procedure returns a specifier for an environment that contains only the bindings for all syntactic keywords defined in the R^{5}RS library. Implementations must support this value of version.
Implementations may also support other values of version, in which case they return a specifier for an environment containing appropriate bindings corresponding to the specified version of the report. If version is neither 5 nor another value supported by the implementation, an error is signaled.
The effect of defining or assigning (through the use of eval) an identifier bound in a schemereportenvironment (for example car) is unspecified. Thus both the environment and the bindings it contains may be immutable.
(interactionenvironment) repl library procedure
This procedure returns a specifier for a mutable environment that
contains an implementationdefined set of bindings, typically a superset
of those exported by (scheme base)
. The intent is that this
procedure will return the environment in which the implementation would
evaluate expressions entered by the user into a REPL.
(eval exprordef environmentspecifier) eval library procedure
If exprordef is an expression, it is evaluated in the specified environment and its values are returned. If it is a definition, the specified identifier(s) are defined in the specified environment, provided the environment is not immutable. Implementations may extend eval to allow other objects.
eval '(* 7 3) (environment '(scheme base)))
(;; => 21
let ((f (eval '(lambda (f x) (f x x))
(nullenvironment 5))))
(+ 10))
(f ;; => 20
eval '(define foo 32)
(
(environment '(scheme base)));; => error is signaled
Ports represent input and output devices. To Scheme, an input port is a Scheme object that can deliver data upon command, while an output port is a Scheme object that can accept data. Whether the input and output port types are disjoint is implementationdependent.
Different port types operate on different data. Scheme implementations are required to support textual ports and binary ports, but may also provide other port types.
A textual port supports reading or writing of individual characters from or to a backing store containing characters using readchar and writechar below, and it supports operations defined in terms of characters, such as read and write.
A binary port supports reading or writing of individual bytes from or to a backing store containing bytes using readu8 and writeu8 below, as well as operations defined in terms of bytes. Whether the textual and binary port types are disjoint is implementationdependent.
Ports can be used to access files, devices, and similar things on the host system on which the Scheme program is running.
(callwithport port proc) procedure
It is an error if proc does not accept one argument.
The callwithport procedure calls proc with port as an argument. If proc returns, then the port is closed automatically and the values yielded by the proc are returned. If proc does not return, then the port must not be closed automatically unless it is possible to prove that the port will never again be used for a read or write operation.
Rationale: Because Scheme’s escape procedures have unlimited extent, it is possible to escape from the current continuation but later to resume it. If implementations were permitted to close the port on any escape from the current continuation, then it would be impossible to write portable code using both callwithcurrentcontinuation and callwithport.
(callwithinputfile string proc) file library procedure
(callwithoutputfile string proc) file library procedure
It is an error if proc does not accept one argument.
These procedures obtain a textual port obtained by opening the named file for input or output as if by openinputfile or openoutputfile. The port and proc are then passed to a procedure equivalent to callwithport.
(inputport? obj) procedure
(outputport? obj) procedure
(textualport? obj) procedure
(binaryport? obj) procedure
(port? obj) procedure
These procedures return #t
if obj is an input
port, output port, textual port, binary port, or any kind of port,
respectively. Otherwise they return #f.
(inputportopen? port) procedure
(outputportopen? port) procedure
Returns #t
if port is still open and capable of
performing input or output, respectively, and #f
otherwise.
(currentinputport) procedure
(currentoutputport) procedure
(currenterrorport) procedure
Returns the current default input port, output port, or error port (an output port), respectively. These procedures are parameter objects, which can be overridden with parameterize (see section [makeparameter]). The initial bindings for these are implementationdefined textual ports.
(withinputfromfile string thunk) file library procedure
(withoutputtofile string thunk) file library procedure
The file is opened for input or output as if by openinputfile or
openoutputfile, and the new port is made to be the value returned by
currentinputport or currentoutputport (as used by
(read)
, (write obj)
, and so forth). The
thunk is then called with no arguments. When the thunk
returns, the port is closed and the previous default is restored. It is
an error if thunk does not accept zero arguments. Both
procedures return the values yielded by thunk. If an escape
procedure is used to escape from the continuation of these procedures,
they behave exactly as if the current input or output port had been
bound dynamically with parameterize.
(openinputfile string) file library procedure
(openbinaryinputfile string) file library procedure
Takes a string for an existing file and returns a textual input port or binary input port that is capable of delivering data from the file. If the file does not exist or cannot be opened, an error that satisfies fileerror? is signaled.
(openoutputfile string) file library procedure
(openbinaryoutputfile string) file library procedure
Takes a string naming an output file to be created and returns a textual output port or binary output port that is capable of writing data to a new file by that name.
If a file with the given name already exists, the effect is unspecified. If the file cannot be opened, an error that satisfies fileerror? is signaled.
(closeport port) procedure
(closeinputport port) procedure
(closeoutputport port) procedure
Closes the resource associated with port, rendering the port incapable of delivering or accepting data. It is an error to apply the last two procedures to a port which is not an input or output port, respectively. Scheme implementations may provide ports which are simultaneously input and output ports, such as sockets; the closeinputport and closeoutputport procedures can then be used to close the input and output sides of the port independently.
These routines have no effect if the port has already been closed.
(openinputstring string) procedure
Takes a string and returns a textual input port that delivers characters from the string. If the string is modified, the effect is unspecified.
(openoutputstring) procedure
Returns a textual output port that will accumulate characters for retrieval by getoutputstring.
(getoutputstring port) procedure
It is an error if port was not created with openoutputstring.
Returns a string consisting of the characters that have been output to the port so far in the order they were output. If the result string is modified, the effect is unspecified.
(parameterizecurrentoutputport
((
(openoutputstring)))display "piece")
(display " by piece ")
(display "by piece.")
(newline)
(currentoutputport)))
(getoutputstring (;; => "piece by piece by piece.\n"
(openinputbytevector bytevector) procedure
Takes a bytevector and returns a binary input port that delivers bytes from the bytevector.
(openoutputbytevector) procedure
Returns a binary output port that will accumulate bytes for retrieval by getoutputbytevector.
(getoutputbytevector port) procedure
It is an error if port was not created with openoutputbytevector.
Returns a bytevector consisting of the bytes that have been output to the port so far in the order they were output.
If port is omitted from any input procedure, it defaults to the value returned by (currentinputport). It is an error to attempt an input operation on a closed port.
(read) read library procedure
(read port) read library procedure
The read procedure converts external representations of Scheme objects into the objects themselves. That is, it is a parser for the nonterminal datum (see sections [datum] and [listsection]). It returns the next object parsable from the given textual input port, updating port to point to the first character past the end of the external representation of the object.
Implementations may support extended syntax to represent record types or other types that do not have datum representations.
If an end of file is encountered in the input before any characters are found that can begin an object, then an endoffile object is returned. The port remains open, and further attempts to read will also return an endoffile object. If an end of file is encountered after the beginning of an object’s external representation, but the external representation is incomplete and therefore not parsable, an error that satisfies readerror? is signaled.
(readchar) procedure
(readchar port) procedure
Returns the next character available from the textual input port, updating the port to point to the following character. If no more characters are available, an endoffile object is returned.
(peekchar) procedure
(peekchar port) procedure
Returns the next character available from the textual input port, but without updating the port to point to the following character. If no more characters are available, an endoffile object is returned.
Note: The value returned by a call to peekchar is the same as the value that would have been returned by a call to readchar with the same port. The only difference is that the very next call to readchar or peekchar on that port will return the value returned by the preceding call to peekchar. In particular, a call to peekchar on an interactive port will hang waiting for input whenever a call to readchar would have hung.
(readline) procedure
(readline port) procedure
Returns the next line of text available from the textual input port, updating the port to point to the following character. If an end of line is read, a string containing all of the text up to (but not including) the end of line is returned, and the port is updated to point just past the end of line. If an end of file is encountered before any end of line is read, but some characters have been read, a string containing those characters is returned. If an end of file is encountered before any characters are read, an endoffile object is returned. For the purpose of this procedure, an end of line consists of either a linefeed character, a carriage return character, or a sequence of a carriage return character followed by a linefeed character. Implementations may also recognize other end of line characters or sequences.
(eofobject? obj) procedure
Returns #t
if obj is an endoffile object,
otherwise returns #f. The precise set of endoffile objects will vary
among implementations, but in any case no endoffile object will ever
be an object that can be read in using read.
(eofobject) procedure
Returns an endoffile object, not necessarily unique.
(charready?) procedure
(charready? port) procedure
Returns #t
if a character is ready on the textual input
port and returns #f
otherwise. If charready
returns #t
then the next readchar operation on the given
port is guaranteed not to hang. If the port is at end
of file then charready? returns #t.
Rationale: The charready? procedure exists to make it
possible for a program to accept characters from interactive ports
without getting stuck waiting for input. Any input editors associated
with such ports must ensure that characters whose existence has been
asserted by charready? cannot be removed from the input. If
charready? were to return #f
at end of file, a port at end
of file would be indistinguishable from an interactive port that has no
ready characters.
(readstring k) procedure
(readstring k port) procedure
Reads the next k characters, or as many as are available before the end of file, from the textual input port into a newly allocated string in lefttoright order and returns the string. If no characters are available before the end of file, an endoffile object is returned.
(readu8) procedure
(readu8 port) procedure
Returns the next byte available from the binary input port, updating the port to point to the following byte. If no more bytes are available, an endoffile object is returned.
(peeku8) procedure
(peeku8 port) procedure
Returns the next byte available from the binary input port, but without updating the port to point to the following byte. If no more bytes are available, an endoffile object is returned.
(u8ready?) procedure (u8ready? port) procedure
Returns #t
if a byte is ready on the binary input
port and returns #f otherwise. If u8ready? returns
#t
then the next readu8 operation on the given
port is guaranteed not to hang. If the port is at end
of file then u8ready? returns #t.
(readbytevector k) procedure
(readbytevector k port) procedure
Reads the next k bytes, or as many as are available before the end of file, from the binary input port into a newly allocated bytevector in lefttoright order and returns the bytevector. If no bytes are available before the end of file, an endoffile object is returned.
(readbytevector! bytevector) procedure
(readbytevector! bytevector port) procedure
(readbytevector! bytevector port start) procedure
(readbytevector! bytevector port start end) procedure
Reads the next end − start bytes, or as many as are available before the end of file, from the binary input port into bytevector in lefttoright order beginning at the start position. If end is not supplied, reads until the end of bytevector has been reached. If start is not supplied, reads beginning at position 0. Returns the number of bytes read. If no bytes are available, an endoffile object is returned.
If port is omitted from any output procedure, it defaults to the value returned by (currentoutputport). It is an error to attempt an output operation on a closed port.
(write obj) write library procedure
(write obj port) write library procedure
Writes a representation of obj to the given textual output
port. Strings that appear in the written representation are
enclosed in quotation marks, and within those strings backslash and
quotation mark characters are escaped by backslashes. Symbols that
contain nonASCII characters are escaped with vertical lines. Character
objects are written using the #'
notation.
If obj contains cycles which would cause an infinite loop using the normal written representation, then at least the objects that form part of the cycle must be represented using datum labels as described in section [labelsection]. Datum labels must not be used if there are no cycles.
Implementations may support extended syntax to represent record types or other types that do not have datum representations.
The write procedure returns an unspecified value.
(writeshared obj) write library procedure
(writeshared obj port) write library procedure
The writeshared procedure is the same as write, except that shared structure must be represented using datum labels for all pairs and vectors that appear more than once in the output.
(writesimple obj) write library procedure
(writesimple obj port) write library procedure
The writesimple procedure is the same as write, except that shared structure is never represented using datum labels. This can cause writesimple not to terminate if obj contains circular structure.
(display obj) write library procedure
(display obj port) write library procedure
Writes a representation of obj to the given textual output port. Strings that appear in the written representation are output as if by writestring instead of by write. Symbols are not escaped. Character objects appear in the representation as if written by writechar instead of by write.
The display representation of other objects is unspecified. However, display must not loop forever on selfreferencing pairs, vectors, or records. Thus if the normal write representation is used, datum labels are needed to represent cycles as in write.
Implementations may support extended syntax to represent record types or other types that do not have datum representations.
The display procedure returns an unspecified value.
Rationale: The write procedure is intended for producing machinereadable output and display for producing humanreadable output.
(newline) procedure
(newline port) procedure
Writes an end of line to textual output port. Exactly how this is done differs from one operating system to another. Returns an unspecified value.
(writechar char) procedure
(writechar char port) procedure
Writes the character char (not an external representation of the character) to the given textual output port and returns an unspecified value.
(writestring string) procedure
(writestring string port) procedure
(writestring string port start) procedure
(writestring string port start end) procedure
Writes the characters of string from start to end in lefttoright order to the textual output port.
(writeu8 byte) procedure
(writeu8 byte port) procedure
Writes the byte to the given binary output port and returns an unspecified value.
(writebytevector bytevector) procedure
(writebytevector bytevector port) procedure
(writebytevector bytevector port start) procedure
(writebytevector bytevector port start end) procedure
Writes the bytes of bytevector from start to end in lefttoright order to the binary output port.
(flushoutputport) procedure
(flushoutputport port) procedure
Flushes any buffered output from the buffer of outputport to the underlying file or device and returns an unspecified value.
Questions of system interface generally fall outside of the domain of this report. However, the following operations are important enough to deserve description here.
(load filename) load library procedure
(load filename environmentspecifier) load library procedure
It is an error if filename is not a string.
An implementationdependent operation is used to transform filename into the name of an existing file containing Scheme source code. The load procedure reads expressions and definitions from the file and evaluates them sequentially in the environment specified by environmentspecifier. If environmentspecifier is omitted, (interactionenvironment) is assumed.
It is unspecified whether the results of the expressions are printed. The load procedure does not affect the values returned by currentinputport and currentoutputport. It returns an unspecified value.
Rationale: For portability, load must operate on source files. Its operation on other kinds of files necessarily varies among implementations.
(fileexists? filename) file library procedure
It is an error if filename is not a string.
The fileexists? procedure returns #t
if the named file
exists at the time the procedure is called, and #f
otherwise.
(deletefile filename) file library procedure
It is an error if filename is not a string.
The deletefile procedure deletes the named file if it exists and can be deleted, and returns an unspecified value. If the file does not exist or cannot be deleted, an error that satisfies fileerror? is signaled.
(commandline) processcontext library procedure
Returns the command line passed to the process as a list of strings. The first string corresponds to the command name, and is implementationdependent. It is an error to mutate any of these strings.
(exit) processcontext library procedure
(exit obj) processcontext library procedure
Runs all outstanding dynamicwind after procedures, terminates the running program, and communicates an exit value to the operating system. If no argument is supplied, or if obj is #t, the exit procedure should communicate to the operating system that the program exited normally. If obj is #f, the exit procedure should communicate to the operating system that the program exited abnormally. Otherwise, exit should translate obj into an appropriate exit value for the operating system, if possible.
The exit procedure must not signal an exception or return to its continuation.
Note: Because of the requirement to run handlers, this procedure is not just the operating system’s exit procedure.
(emergencyexit) processcontext library procedure
(emergencyexit obj) processcontext library procedure
Terminates the program without running any outstanding dynamicwind after procedures and communicates an exit value to the operating system in the same manner as exit.
Note: The emergencyexit procedure corresponds to the _exit procedure in Windows and Posix.
(getenvironmentvariable name) processcontext library procedure
Many operating systems provide each running process with an
environment consisting of environment variables. (This
environment is not to be confused with the Scheme environments that can
be passed to eval: see section [environments].) Both the name and value of an
environment variable are strings. The procedure getenvironmentvariable
returns the value of the environment variable name, or
#f
if the named environment variable is not found. It may
use locale information to encode the name and decode the value of the
environment variable. It is an error if getenvironmentvariable can’t
decode the value. It is also an error to mutate the resulting
string.
"PATH") ;; => "/usr/local/bin:/usr/bin:/bin" (getenvironmentvariable
(getenvironmentvariables) processcontext library procedure Returns the names and values of all the environment variables as an alist, where the car of each entry is the name of an environment variable and the cdr is its value, both as strings. The order of the list is unspecified. It is an error to mutate any of these strings or the alist itself.
;; => (("USER" . "root") ("HOME" . "/")) (getenvironmentvariables)
(currentsecond) time library procedure Returns an inexact number representing the current time on the International Atomic Time (TAI) scale. The value 0.0 represents midnight on January 1, 1970 TAI (equivalent to 8.000082 seconds before midnight Universal Time) and the value 1.0 represents one TAI second later. Neither high accuracy nor high precision are required; in particular, returning Coordinated Universal Time plus a suitable constant might be the best an implementation can do.
As of 2018, a TAIUTC offset table can be found at .
(currentjiffy) time library procedure Returns the number of jiffies as an exact integer that have elapsed since an arbitrary, implementationdefined epoch. A jiffy is an implementationdefined fraction of a second which is defined by the return value of the jiffiespersecond procedure. The starting epoch is guaranteed to be constant during a run of the program, but may vary between runs.
Rationale: Jiffies are allowed to be implementationdependent so that currentjiffy can execute with minimum overhead. It should be very likely that a compactly represented integer will suffice as the returned value. Any particular jiffy size will be inappropriate for some implementations: a microsecond is too long for a very fast machine, while a much smaller unit would force many implementations to return integers which have to be allocated for most calls, rendering currentjiffy less useful for accurate timing measurements.
(jiffiespersecond) time library procedure
Returns an exact integer representing the number of jiffies per SI second. This value is an implementationspecified constant.
define (timelength)
(let ((list (makelist 100000))
(
(start (currentjiffy)))length list)
(/ ( (currentjiffy) start)
( (jiffiespersecond))))
(features) procedure
Returns a list of the feature identifiers which condexpand treats as true. It is an error to modify this list. Here is an example of what features might return:
(features) \ev
(r7rs ratios exactcomplex fullunicode
gnulinux littleendian
fantasticscheme
fantasticscheme1.0 spaceshipcontrolsystem)
This section gives syntax definitions for the derived expression types in terms of the primitive expression types (literal, variable, call, lambda, if, and set!), except for quasiquote.
Conditional derived syntax types:
definesyntax cond
(syntaxrules (else =>)
(cond (else result1 result2 ...))
((begin result1 result2 ...))
(cond (test => result))
((let ((temp test))
(if temp (result temp))))
(cond (test => result) clause1 clause2 ...)
((let ((temp test))
(if temp
(
(result temp)cond clause1 clause2 ...))))
(cond (test)) test)
((cond (test) clause1 clause2 ...)
((let ((temp test))
(if temp
(
tempcond clause1 clause2 ...))))
(cond (test result1 result2 ...))
((if test (begin result1 result2 ...)))
(cond (test result1 result2 ...)
((...)
clause1 clause2 if test
(begin result1 result2 ...)
(cond clause1 clause2 ...)))))
(
definesyntax case
(syntaxrules (else =>)
(case (key ...)
((...)
clauses let ((atomkey (key ...)))
(case atomkey clauses ...)))
(case key
((else => result))
(
(result key))case key
((else result1 result2 ...))
(begin result1 result2 ...))
(case key
((...) => result))
((atoms if (memv key '(atoms ...))
(
(result key)))case key
((...) result1 result2 ...))
((atoms if (memv key '(atoms ...))
(begin result1 result2 ...)))
(case key
((...) => result)
((atoms ...)
clause clauses if (memv key '(atoms ...))
(
(result key)case key clause clauses ...)))
(case key
((...) result1 result2 ...)
((atoms ...)
clause clauses if (memv key '(atoms ...))
(begin result1 result2 ...)
(case key clause clauses ...)))))
(
definesyntax and
(syntaxrules ()
(and) #t)
((and test) test)
((and test1 test2 ...)
((if test1 (and test2 ...) #f))))
(
definesyntax or
(syntaxrules ()
(or) #f)
((or test) test)
((or test1 test2 ...)
((let ((x test1))
(if x x (or test2 ...))))))
(
definesyntax when
(syntaxrules ()
(...)
((when test result1 result2 if test
(begin result1 result2 ...)))))
(
definesyntax unless
(syntaxrules ()
(...)
((unless test result1 result2 if (not test)
(begin result1 result2 ...))))) (
Binding constructs:
definesyntax let
(syntaxrules ()
(let ((name val) ...) body1 body2 ...)
((lambda (name ...) body1 body2 ...)
((...))
val let tag ((name val) ...) body1 body2 ...)
((letrec ((tag (lambda (name ...)
((...)))
body1 body2
tag)...))))
val
definesyntax let*
(syntaxrules ()
(let* () body1 body2 ...)
((let () body1 body2 ...))
(let* ((name1 val1) (name2 val2) ...)
((...)
body1 body2 let ((name1 val1))
(let* ((name2 val2) ...)
(...))))) body1 body2
The following letrec macro uses the symbol <undefined> in place of an expression which returns something that when stored in a location makes it an error to try to obtain the value stored in the location. (No such expression is defined in Verbatim.) A trick is used to generate the temporary names needed to avoid specifying the order in which the values are evaluated. This could also be accomplished by using an auxiliary macro.
definesyntax letrec
(syntaxrules ()
(letrec ((var1 init1) ...) body ...)
((letrec "generate_temp_names"
(...)
(var1
()...)
((var1 init1) ...))
body letrec "generate_temp_names"
((
()...)
(temp1 ...)
((var1 init1) ...)
body let ((var1 <undefined>) ...)
(let ((temp1 init1) ...)
(set! var1 temp1)
(...
...)))
body letrec "generate_temp_names"
((...)
(x y ...)
(temp ...)
((var1 init1) ...)
body letrec "generate_temp_names"
(...)
(y ...)
(newtemp temp ...)
((var1 init1) ...))))
body
definesyntax letrec*
(syntaxrules ()
(letrec* ((var1 init1) ...) body1 body2 ...)
((let ((var1 <undefined>) ...)
(set! var1 init1)
(...
let () body1 body2 ...)))))
(
definesyntax letvalues
(syntaxrules ()
(letvalues (binding ...) body0 body1 ...)
((letvalues "bind"
(...) () (begin body0 body1 ...)))
(binding
letvalues "bind" () tmps body)
((let tmps body))
(
letvalues "bind" ((b0 e0)
((...) tmps body)
binding letvalues "mktmp" b0 e0 ()
(...) tmps body))
(binding
letvalues "mktmp" () e0 args
((
bindings tmps body)callwithvalues
(lambda () e0)
(lambda args
(letvalues "bind"
(
bindings tmps body))))
letvalues "mktmp" (a . b) e0 (arg ...)
((...) body)
bindings (tmp letvalues "mktmp" b e0 (arg ... x)
(... (a x)) body))
bindings (tmp
letvalues "mktmp" a e0 (arg ...)
((...) body)
bindings (tmp callwithvalues
(lambda () e0)
(lambda (arg ... . x)
(letvalues "bind"
(... (a x)) body))))))
bindings (tmp
definesyntax let*values
(syntaxrules ()
(let*values () body0 body1 ...)
((let () body0 body1 ...))
(
let*values (binding0 binding1 ...)
((...)
body0 body1 letvalues (binding0)
(let*values (binding1 ...)
(...)))))
body0 body1
definesyntax definevalues
(syntaxrules ()
(
((definevalues () expr)define dummy
(callwithvalues (lambda () expr)
(lambda args #f))))
(
((definevalues (var) expr)define var expr))
(... varn) expr)
((definevalues (var0 var1 begin
(define var0
(callwithvalues (lambda () expr)
(list))
define var1
(let ((v (cadr var0)))
(setcdr! var0 (cddr var0))
(...
v)) define varn
(let ((v (cadr var0)))
(set! var0 (car var0))
(
v))))... . varn) expr)
((definevalues (var0 var1 begin
(define var0
(callwithvalues (lambda () expr)
(list))
define var1
(let ((v (cadr var0)))
(setcdr! var0 (cddr var0))
(...
v)) define varn
(let ((v (cdr var0)))
(set! var0 (car var0))
(
v))))
((definevalues var expr)define var
(callwithvalues (lambda () expr)
(list)))))
definesyntax begin
(syntaxrules ()
(begin exp ...)
((lambda () exp ...))))) ((
The following alternative expansion for begin does not make use of the ability to write more than one expression in the body of a lambda expression. In any case, note that these rules apply only if the body of the begin contains no definitions.
definesyntax begin
(syntaxrules ()
(begin exp)
((exp)
begin exp1 exp2 ...)
((callwithvalues
(lambda () exp1)
(lambda args
(begin exp2 ...)))))) (
The following syntax definition of do uses a trick to expand the
variable clauses. As with letrec above, an auxiliary macro would also
work. The expression (if #f
#f) is used to obtain an
unspecific value.
definesyntax do
(syntaxrules ()
(do ((var init step ...) ...)
((...)
(test expr ...)
command letrec
(
((looplambda (var ...)
(if test
(begin
(if #f #f)
(...)
expr begin
(
command...
do "step" var step ...)
(loop (...))))))
...)))
(loop init do "step" x)
((
x)do "step" x y)
(( y)))
Here is a possible implementation of delay, force and delayforce. We define the expression
(delayforce <expression>)
to have the same meaning as the procedure call
#f (lambda () <expression>)) (makepromise
as follows
definesyntax delayforce
(syntaxrules ()
(
((delayforce expression)#f (lambda () expression))))) (makepromise
and we define the expression
(delay <expression>)
to have the same meaning as:
#t <expression>)) (delayforce (makepromise
as follows
definesyntax delay
(syntaxrules ()
(
((delay expression)#t expression))))) (delayforce (makepromise
where makepromise is defined as follows:
define makepromise
(lambda (done? proc)
(list (cons done? proc)))) (
Finally, we define force to call the procedure expressions in promises iteratively using a trampoline technique following until a nonlazy result (i.e. a value created by delay instead of delayforce) is returned, as follows:
define (force promise)
(if (promisedone? promise)
(
(promisevalue promise)let ((promise* ((promisevalue promise))))
(
(unless (promisedone? promise)
(promiseupdate! promise* promise))force promise)))) (
with the following promise accessors:
define promisedone?
(lambda (x) (car (car x))))
(define promisevalue
(lambda (x) (cdr (car x))))
(define promiseupdate!
(lambda (new old)
(setcar! (car old) (promisedone? new))
(setcdr! (car old) (promisevalue new))
(setcar! new (car old)))) (
The following implementation of makeparameter and parameterize is suitable for an implementation with no threads. Parameter objects are implemented here as procedures, using two arbitrary unique objects <paramset!> and <paramconvert>:
define (makeparameter init . o)
(let* ((converter
(if (pair? o) (car o) (lambda (x) x)))
(
(value (converter init)))lambda args
(cond
(null? args)
((
value)eq? (car args) <paramset!>)
((set! value (cadr args)))
(eq? (car args) <paramconvert>)
((
converter)else
(error "bad parameter syntax")))))) (
Then parameterize uses dynamicwind to dynamically rebind the associated value:
definesyntax parameterize
(syntaxrules ()
("step")
((parameterize (...)
((param value p old new)
()
body)let ((p param) ...)
(let ((old (p)) ...
(...)
(new ((p <paramconvert>) value)) dynamicwind
(lambda () (p <paramset!> new) ...)
(lambda () . body)
(lambda () (p <paramset!> old) ...)))))
("step")
((parameterize (
args. rest)
((param value)
body)"step")
(parameterize (. args)
((param value p old new)
rest
body))...) . body)
((parameterize ((param value) "step")
(parameterize (
()...)
((param value) body))))
The following implementation of guard depends on an auxiliary macro, here called guardaux.
definesyntax guard
(syntaxrules ()
(guard (var clause ...) e1 e2 ...)
((call/cc
((lambda (guardk)
(withexceptionhandler
(lambda (condition)
(call/cc
((lambda (handlerk)
(
(guardklambda ()
(let ((var condition))
(
(guardaux
(handlerklambda ()
(raisecontinuable condition)))
(...))))))))
clause lambda ()
(callwithvalues
(lambda () e1 e2 ...)
(lambda args
(
(guardklambda ()
(values args)))))))))))))
(apply
definesyntax guardaux
(syntaxrules (else =>)
(else result1 result2 ...))
((guardaux reraise (begin result1 result2 ...))
(=> result))
((guardaux reraise (test let ((temp test))
(if temp
(
(result temp)
reraise)))=> result)
((guardaux reraise (test ...)
clause1 clause2 let ((temp test))
(if temp
(
(result temp)...))))
(guardaux reraise clause1 clause2
((guardaux reraise (test))or test reraise))
(...)
((guardaux reraise (test) clause1 clause2 let ((temp test))
(if temp
(
temp...))))
(guardaux reraise clause1 clause2 ...))
((guardaux reraise (test result1 result2 if test
(begin result1 result2 ...)
(
reraise))
((guardaux reraise...)
(test result1 result2 ...)
clause1 clause2 if test
(begin result1 result2 ...)
(...)))))
(guardaux reraise clause1 clause2
definesyntax caselambda
(syntaxrules ()
(caselambda (params body0 ...) ...)
((lambda args
(let ((len (length args)))
(letrecsyntax
(syntaxrules ::: ()
((cl (
((cl)error "no matching clause"))
(. body) . rest)
((cl ((p :::) if (= len (length '(p :::)))
(lambda (p :::)
(apply (. body)
args). rest)))
(cl . tail) . body)
((cl ((p ::: . rest)
if (>= len (length '(p :::)))
(
(applylambda (p ::: . tail)
(. body)
args). rest))))))
(cl ...) ...))))))) (cl (params body0
This definition of condexpand does not interact with the features procedure. It requires that each feature identifier provided by the implementation be explicitly mentioned.
definesyntax condexpand
(;; Extend this to mention all feature ids and libraries
syntaxrules (and or not else r7rs library verbatim base)
(
((condexpand)"Unfulfilled condexpand"))
(syntaxerror else body ...))
((condexpand (begin body ...))
(and) body ...) moreclauses ...)
((condexpand ((begin body ...))
(and req1 req2 ...) body ...)
((condexpand ((...)
moreclauses
(condexpand
(req1
(condexpandand req2 ...) body ...)
((...))
moreclauses ...))
moreclauses or) body ...) moreclauses ...)
((condexpand ((...))
(condexpand moreclauses or req1 req2 ...) body ...)
((condexpand ((...)
moreclauses
(condexpand
(req1begin body ...))
(else
(
(condexpandor req2 ...) body ...)
((...))))
moreclauses not req) body ...)
((condexpand ((...)
moreclauses
(condexpand
(req...))
(condexpand moreclauses else body ...)))
(...)
((condexpand (r7rs body ...)
moreclauses begin body ...))
(;; Add clauses here for each
;; supported feature identifier.
;; Samples:
;; ((condexpand (exactclosed body ...)
;; moreclauses ...)
;; (begin body ...))
;; ((condexpand (ieeefloat body ...)
;; moreclauses ...)
;; (begin body ...))
((condexpand ((library (verbatim base))...)
body ...)
moreclauses begin body ...))
(;; Add clauses here for each library
...)
((condexpand (featureid body ...)
moreclauses ...))
(condexpand moreclauses ...))
((condexpand ((library (name ...)
body ...)
moreclauses ...)))) (condexpand moreclauses
This section lists the exports provided by the standard libraries. The libraries are factored so as to separate features which might not be supported by all implementations, or which might be expensive to load.
The scheme library prefix is used for all standard libraries, and is reserved for use by future standards.
The (scheme base)
library exports many of the procedures
and syntax bindings that are traditionally associated with Scheme. The
division between the base library and the other standard libraries is
based on use, not on construction. In particular, some facilities that
are typically implemented as primitives by a compiler or the runtime
system rather than in terms of other standard procedures or syntax are
not part of the base library, but are defined in separate libraries. By
the same token, some exports of the base library are implementable in
terms of other exports. They are redundant in the strict sense of the
word, but they capture common patterns of usage, and are therefore
provided as convenient abbreviations.
*
+

...
/
<
<=
=
=>
>
>=
_
abs
and
append
applyassoc
assq
assv
begin
binaryport?
boolean=?
boolean?
bytevector
bytevectorappendbytevectorcopy
bytevectorcopy!
bytevectorlength
bytevectoru8ref
bytevectoru8set!
bytevector?
caar
cadr
callwithcurrentcontinuation
callwithport
callwithvalues
call/cc
car
case
cdar
cddr
cdr
ceiling
char>integer
charready?
char<=?
char<?
char=?
char>=?
char>?
char?
closeinputport
closeoutputport
closeport
complex?
cond
condexpandcons
currenterrorport
currentinputport
currentoutputport
define
definerecordtype
definesyntax
definevalues
denominator
do
dynamicwind
else
eofobject
eofobject?
eq?
equal?
eqv?
error
errorobjectirritants
errorobjectmessage
errorobject?even?
exact
exactintegersqrt
exactinteger?exact?
expt
features
fileerror?floor
floorquotient
floorremainder
floor/flushoutputport
foreach
gcd
getoutputbytevector
getoutputstringguard
if
include
includeciinexact
inexact?
inputportopen?inputport?
integer>char
integer?
lambda
lcm
length
let
let*
let*values
letsyntax
letvalues
letrec
letrec*
letrecsyntax
list
list>string
list>vector
listcopylistref
listset!listtail
list?
makebytevector
makelist
makeparametermakestring
makevector
mapmax
member
memq
memv
min
modulo
negative?
newline
not
null?
number>string
number?
numerator
odd?
openinputbytevector
openinputstring
openoutputbytevector
openoutputstringor
outputportopen?outputport?
pair?
parameterizepeekchar
peeku8port?
positive?
procedure?
quasiquote
quote
quotient
raise
raisecontinuable
rational?
rationalize
readbytevector
readbytevector!readchar
readerror?
readline
readstring
readu8real?
remainder
reverse
round
set!
setcar!
setcdr!
squarestring
string>list
string>number
string>symbol
string>utf8
string>vectorstringappend
stringcopy
stringcopy!stringfill!
stringforeachstringlength
stringmapstringref
stringset!
string<=?
string<?
string=?
string>=?
string>?
string?
substring
symbol>string
symbol=?
symbol?
syntaxerrorsyntaxrules
textualport?
truncate
truncatequotient
truncateremainder
truncate/
u8ready?
unlessunquote
unquotesplicing
utf8>string
values
vector
vector>list
vector>string
vectorappend
vectorcopy
vectorcopy!vectorfill!
vectorforeachvectorlength
vectormapvectorref
vectorset!
vector?
whenwithexceptionhandler
writebytevectorwritechar
writestring
writeu8zero?
The (scheme caselambda)
library exports the
caselambda
syntax.
caselambda
The (scheme char)
library provides the procedures for
dealing with characters that involve potentially large tables when
supporting all of Unicode.
charalphabetic?
charci<=?
charci<?
charci=?
charci>=?
charci>?
chardowncase
charfoldcase
charlowercase?
charnumeric?
charupcase
charuppercase?
charwhitespace?
digitvaluestringci<=?
stringci<?
stringci=?
stringci>=?
stringci>?
stringdowncase
stringfoldcase
stringupcase
The (scheme complex)
library exports procedures which
are typically only useful with nonreal numbers.
angle imagpart
magnitude makepolar
makerectangular realpart
The (scheme cxr)
library exports twentyfour procedures
which are the compositions of from three to four car and cdr operations.
For example caddar could be defined by
define caddar
(lambda (x) (car (cdr (cdr (car x)))))) (
The procedures car and cdr themselves and the four twolevel compositions are included in the base library. See section [listsection].
caaaar caaadr
caaar caadar
caaddr caadr
cadaar cadadr
cadar caddar
cadddr caddr
cdaaar cdaadr
cdaar cdadar
cdaddr cdadr
cddaar cddadr
cddar cdddar
cddddr cdddr
The (scheme eval)
library exports procedures for
evaluating Scheme data as programs.
environment
eval
The (scheme file)
library provides procedures for
accessing files.
callwithinputfile
callwithoutputfile
deletefile
fileexists?
openbinaryinputfile
openbinaryoutputfile
openinputfile
openoutputfile
withinputfromfile
withoutputtofile
The (scheme inexact)
library exports procedures which
are typically only useful with inexact values.
acos
asin
atan
cos
exp
finite?
infinite?
log
nan?
sin
sqrt
tan
The (scheme lazy)
library exports procedures and syntax
keywords for lazy evaluation.
delay delayforceforce makepromise
promise?
The (scheme load)
library exports procedures for loading
Scheme expressions from files.
load
The (scheme processcontext)
library exports procedures
for accessing with the program’s calling context.
commandline emergencyexit
exit
getenvironmentvariable getenvironmentvariables
The (scheme read)
library provides procedures for
reading Scheme objects.
read
The (scheme repl)
library exports the
interactionenvironment procedure.
interactionenvironment
The (scheme time)
library provides access to
timerelated values.
currentjiffy currentsecond
jiffiespersecond
The (scheme write)
library provides procedures for
writing Scheme objects.
display write
writeshared writesimple
The (scheme r5rs)
library provides the identifiers
defined by R^{5}RS, except that transcripton and
transcriptoff are not present. Note that the exact and inexact
procedures appear under their R^{5}RS names
inexact>exact and exact>inexact respectively. However, if an
implementation does not provide a particular library such as the complex
library, the corresponding identifiers will not appear in this library
either.
+  ... / \< \<= = => \> \>= _ abs acos and angle append apply asin
\* assoc assq assv atan begin boolean? caaaar caaadr caaar caadar caaddr
caadr caar cadaar cadadr cadar caddar cadddr caddr cadr
callwithcurrentcontinuation callwithinputfile
callwithoutputfile callwithvalues car case cdaaar cdaadr cdaar
cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr
cdr ceiling char>integer charalphabetic? charci\<=? charci\<?
charci=? charci>=? charci>? chardowncase charlowercase?
charready? charupcase charuppercase?
charnumeric? char=? char>=? char>? char?
charwhitespace? char\<=? char\<? closeinputport closeoutputport complex? cond cons cos
currentinputport currentoutputport define definesyntax delay
denominator display do dynamicwind else eofobject? eq? equal? eqv?
eval even? exact>inexact exact? exp expt floor foreach force gcd if
imagpart inexact>exact inexact? inputport? integer>char integer?
interactionenvironment lambda lcm length let let\* letsyntax letrec
letrecsyntax list list>string list>vector listref listtail list?
load log magnitude makepolar makerectangular makestring makevector
max member memq memv min modulo negative? newline not
map nullenvironment null? number>string number? numerator odd?
openinputfile openoutputfile or outputport? pair? peekchar
procedure? quasiquote quote quotient rational? rationalize
positive? read readchar realpart real? remainder reverse round
schemereportenvironment set! setcar! setcdr! sin sqrt string
string>list string>number string>symbol stringappend stringci\<=?
stringci>=? stringci>? stringcopy
stringci\<? stringci=? stringfill! stringlength stringref stringset! string\<=? string\<?
string>=? string>? string? substring symbol>string symbol?
string=? syntaxrules tan truncate values vector vector>list vectorfill!
vectorlength vectorref vectorset! vector? withinputfromfile
withoutputtofile write writechar zero?
An implementation may provide any or all of the feature identifiers listed below for use by condexpand and features, but must not provide a feature identifier if it does not provide the corresponding feature.
r7rs
All R^{7}RS Scheme implementations have this feature.
exactclosed
The algebraic operations +, , *, and expt where the second argument is a nonnegative integer produce exact values given exact inputs.
exactcomplex
Exact complex numbers are provided.
ieeefloat
Inexact numbers are IEEE 754 binary floating point values.
fullunicode
All Unicode characters present in Unicode version 6.0 are supported as Scheme characters.
ratios
/ with exact arguments produces an exact result when the divisor is nonzero.
posix
This implementation is running on a POSIX system.
windows
This implementation is running on Windows.
unix
,darwin
,gnulinux
,bsd
,freebsd
,solaris
, …
Operating system flags (perhaps more than one).
i386
,x8664
,ppc
,sparc
,jvm
,clr
,llvm
, …
CPU architecture flags.
ilp32
,lp64
,ilp64
, …
C memory model flags.
bigendian
,littleendian
Byte order flags.
The name of this implementation.
The name and version of this implementation.
This section enumerates the incompatibilities between this report and the “Revised^{5} report” .
This list is not authoritative, but is believed to be correct and complete.
Case sensitivity is now the default in symbols and character names. This means that code written under the assumption that symbols could be written FOO or Foo in some contexts and foo in other contexts can either be changed, be marked with the new #!foldcase directive, or be included in a library using the includeci library declaration. All standard identifiers are entirely in lower case.
The syntaxrules construct now recognizes *_* (underscore) as a wildcard, which means it cannot be used as a syntax variable. It can still be used as a literal.
The R^{5}RS procedures exact>inexact and inexact>exact have been renamed to their R^{6}RS names, inexact and exact, respectively, as these names are shorter and more correct. The former names are still available in the R^{5}RS library.
The guarantee that string comparison (with string<? and the related predicates) is a lexicographical extension of character comparison (with char<? and the related predicates) has been removed.
Support for the # character in numeric literals is no longer required.
Support for the letters s, f, d, and l as exponent markers is no longer required.
Implementations of stringnumber are no longer permitted to return #f when the argument contains an explicit radix prefix, and must be compatible with read and the syntax of numbers in programs.
The procedures transcripton and transcriptoff have been removed.
This section enumerates the additional differences between this report and the “Revised^{5} report” .
This list is not authoritative, but is believed to be correct and complete.
Various minor ambiguities and unclarities in R^{5}RS have been cleaned up.
Libraries have been added as a new program structure to improve encapsulation and sharing of code. Some existing and new identifiers have been factored out into separate libraries. Libraries can be imported into other libraries or main programs, with controlled exposure and renaming of identifiers. The contents of a library can be made conditional on the features of the implementation on which it is to be used. There is an R^{5}RS compatibility library.
The expressions types include, includeci, and condexpand have been added to the base library; they have the same semantics as the corresponding library declarations.
Exceptions can now be signaled explicitly with raise, raisecontinuable or error, and can be handled with withexceptionhandler and the guard syntax. Any object can specify an error condition; the implementationdefined conditions signaled by error have a predicate to detect them and accessor functions to retrieve the arguments passed to error. Conditions signaled by read and by filerelated procedures also have predicates to detect them.
New disjoint types supporting access to multiple fields can be generated with the definerecordtype of SRFI 9
Parameter objects can be created with makeparameter, and dynamically rebound with parameterize. The procedures currentinputport and currentoutputport are now parameter objects, as is the newly introduced currenterrorport.
Support for promises has been enhanced based on SRFI 45 .
Bytevectors, vectors of exact integers in the range from 0 to 255 inclusive, have been added as a new disjoint type. A subset of the vector procedures is provided. Bytevectors can be converted to and from strings in accordance with the UTF8 character encoding. Bytevectors have a datum representation and evaluate to themselves.
Vector constants evaluate to themselves.
The procedure readline is provided to make lineoriented textual input simpler.
The procedure flushoutputport is provided to allow minimal control of output port buffering.
Ports can now be designated as textual or binary ports, with new procedures for reading and writing binary data. The new predicates inputportopen? and outputportopen? return whether a port is open or closed. The new procedure closeport now closes a port; if the port has both input and output sides, both are closed.
String ports have been added as a way to read and write characters to and from strings, and bytevector ports to read and write bytes to and from bytevectors.
There are now I/O procedures specific to strings and bytevectors.
The write procedure now generates datum labels when applied to circular objects. The new procedure writesimple never generates labels; writeshared generates labels for all shared and circular structure. The display procedure must not loop on circular objects.
The R^{6}RS procedure eofobject has been added. Eofobjects are now required to be a disjoint type.
Syntax definitions are now allowed wherever variable definitions are.
The syntaxrules construct now allows the ellipsis symbol to be specified explicitly instead of the default …, allows template escapes with an ellipsisprefixed list, and allows tail patterns to follow an ellipsis pattern.
The syntaxerror syntax has been added as a way to signal immediate and more informative errors when a macro is expanded.
The letrec* binding construct has been added, and internal define is specified in terms of it.
Support for capturing multiple values has been enhanced with definevalues, letvalues, and let*values. Standard expression types which contain a sequence of expressions now permit passing zero or more than one value to the continuations of all nonfinal expressions of the sequence.
The case conditional now supports =>
syntax
analogous to cond not only in regular clauses but in the else clause as
well.
To support dispatching on the number of arguments passed to a procedure, caselambda has been added in its own library.
The convenience conditionals when and unless have been added.
The behavior of eqv? on inexact numbers now conforms to the R^{6}RS definition.
When applied to procedures, eq? and eqv? are permitted to return different answers.
The R^{6}RS procedures boolean=? and symbol=? have been added.
Positive infinity, negative infinity, NaN, and negative inexact
zero have been added to the numeric tower as inexact values with the
written representations +inf.0
, inf.0
,
+nan.0
, and 0.0 respectively. Support for them is not
required. The representation nan.0
is synonymous with
+nan.0
.
The log procedure now accepts a second argument specifying the logarithm base.
The procedures map and foreach are now required to terminate on the shortest argument list.
The procedures member and assoc now take an optional third argument specifying the equality predicate to be used.
The numeric procedures finite?, infinite?, nan?, exactinteger?, square, and exactintegersqrt have been added.
The  and / procedures and the character and string comparison predicates are now required to support more than two arguments.
The forms #true
and #false
are now
supported as well as #t
and #f
.
The procedures makelist, listcopy, listset!, stringmap, stringforeach, string>vector, vectorappend, vectorcopy, vectormap, vectorforeach, vector>string, vectorcopy!, and stringcopy! have been added to round out the sequence operations.
Some string and vector procedures support processing of part of a string or vector using optional start and end arguments.
Some list procedures are now defined on circular lists.
Implementations may provide any subset of the full Unicode repertoire that includes ASCII, but implementations must support any such subset in a way consistent with Unicode. Various character and string procedures have been extended accordingly, and case conversion procedures added for strings. String comparison is no longer required to be consistent with character comparison, which is based solely on Unicode scalar values. The new digitvalue procedure has been added to obtain the numerical value of a numeric character.
There are now two additional comment syntaxes: #;
to
skip the next datum, and # ... #
for nestable block
comments.
Data prefixed with datum labels #<n>=
can be
referenced with #<n>#
, allowing for reading and
writing of data with shared structure.
Strings and symbols now allow mnemonic and numeric escape sequences, and the list of named characters has been extended.
The procedures fileexists? and deletefile are available in the
(scheme file)
library.
An interface to the system environment, command line, and process
exit status is available in the (scheme processcontext)
library.
Procedures for accessing timerelated values are available in the
(scheme time)
library.
A less irregular set of integer division operators is provided with new and clearer names.
The load procedure now accepts a second argument specifying the environment to load into.
The callwithcurrentcontinuation procedure now has the synonym call/cc.
The semantics of readevalprint loops are now partly prescribed, requiring the redefinition of procedures, but not syntax keywords, to have retroactive effect.
The formal semantics now handles dynamicwind.
This section enumerates the incompatibilities between R^{7}RS and the “Revised^{6} report” and its accompanying Standard Libraries document.
This list is not authoritative, and is possibly incomplete.
R^{7}RS libraries begin with the keyword definelibrary rather than library in order to make them syntactically distinguishable from R^{6}RS libraries. In R^{7}RS terms, the body of an R^{6}RS library consists of a single export declaration followed by a single import declaration, followed by commands and definitions. In R^{7}RS, commands and definitions are not permitted directly within the body: they have to be wrapped in a begin library declaration.
There is no direct R^{6}RS equivalent of the include, includeci, includelibrarydeclarations, or condexpand library declarations. On the other hand, the R^{7}RS library syntax does not support phase or version specifications.
The grouping of standardized identifiers into libraries is different from the R^{6}RS approach. In particular, procedures which are optional in R^{5}RS either expressly or by implication, have been removed from the base library. Only the base library itself is an absolute requirement.
No form of identifier syntax is provided.
Internal syntax definitions are allowed, but uses of a syntax form cannot appear before its definition; the even/odd example given in R^{6}RS is not allowed.
The R^{6}RS exception system was incorporated asis, but the condition types have been left unspecified. In particular, where R^{6}RS requires a condition of a specified type to be signaled, R^{7}RS says only “it is an error”, leaving the question of signaling open.
Full Unicode support is not required. Normalization is not provided. Character comparisons are defined by Unicode, but string comparisons are implementationdependent. NonUnicode characters are permitted.
The full numeric tower is optional as in R^{5}RS, but optional support for IEEE infinities, NaN, and 0.0 was adopted from R^{6}RS. Most clarifications on numeric results were also adopted, but the semantics of the R^{6}RS procedures real?, rational?, and integer? were not adopted. (Note that the R^{5}RS/R^{7}RS semantics are available in R^{6}RS using realvalued?, rationalvalued?, and integervalued?). The R^{6}RS division operators div, mod, divandmod, div0, mod0 and div0andmod0 are not provided.
When a result is unspecified, it is still required to be a single value. However, nonfinal expressions in a body can return any number of values.
The semantics of map and foreach have been changed to use the SRFI 1 early termination behavior. Likewise, assoc and member take an optional equal? argument as in SRFI 1, instead of the separate assp and memp procedures of R^{6}RS.
The R^{6}RS quasiquote clarifications have been adopted, with the exception of multipleargument unquote and unquotesplicing.
The R^{6}RS method of specifying mantissa widths was not adopted.
String ports are compatible with SRFI 6 rather than R^{6}RS.
R^{6}RSstyle bytevectors are included, but only the unsigned byte (u8) procedures have been provided. The lexical syntax uses #u8 for compatibility with SRFI 4 , rather than the R^{6}RS #vu8 style.
The utility macros when and unless are provided, but their result is left unspecified.
The remaining features of the Standard Libraries document were left to future standardization efforts.
The Scheme community website at http://schemers.org contains additional resources for learning and programming, job and event postings, and Scheme user group information.
A bibliography of Schemerelated research at http://library.readscheme.org links to technical papers and theses related to the Scheme language, including both classic papers and recent research.
Online Scheme discussions are held using IRC on the #scheme channel at irc.freenode.net and on the Usenet discussion group comp.lang.scheme.
The procedure integratesystem integrates the system y_{k}^{′} = f_{k}(y_{1},y_{2},…,y_{n}), k = 1, …, n of differential equations with the method of RungeKutta.
The parameter systemderivative
is a function that takes
a system state (a vector of values for the state variables
y_{1}, …, y_{n}) and produces
a system derivative (the values
y_{1}^{′}, …, y_{n}^{′}).
The parameter initialstate
provides an initial system
state, and h
is an initial guess for the length of the
integration step.
The value returned by integratesystem is an infinite stream of system states.
define (integratesystem systemderivative
(
initialstate
h)let ((next (rungekutta4 systemderivative h)))
(letrec ((states
(cons initialstate
(
(delay (mapstreams next
states))))) states)))
The procedure rungekutta4 takes a function, f
, that
produces a system derivative from a system state. It produces a function
that takes a system state and produces a new system state.
define (rungekutta4 f h)
(let ((*h (scalevector h))
(2))
(*2 (scalevector / 1 2)))
(*1/2 (scalevector (/ 1 6))))
(*1/6 (scalevector (lambda (y)
(;; y is a system state
let* ((k0 (*h (f y)))
(
(k1 (*h (f (addvectors y (*1/2 k0)))))
(k2 (*h (f (addvectors y (*1/2 k1)))))
(k3 (*h (f (addvectors y k2)))))
(addvectors y
(*1/6 (addvectors k0
(*2 k1)
(*2 k2)
k3)))))))
define (elementwise f)
(lambda vectors
(
(generatevectorvectorlength (car vectors))
(lambda (i)
(
(apply flambda (v) (vectorref v i))
(map (
vectors))))))
define (generatevector size proc)
(let ((ans (makevector size)))
(letrec ((loop
(lambda (i)
(cond ((= i size) ans)
(else
(vectorset! ans i (proc i))
(+ i 1)))))))
(loop (0))))
(loop
define addvectors (elementwise +))
(
define (scalevector s)
(lambda (x) (* x s)))) (elementwise (
The mapstreams procedure is analogous to map: it applies its first argument (a procedure) to all the elements of its second argument (a stream).
define (mapstreams f s)
(cons (f (head s))
( (delay (mapstreams f (tail s)))))
Infinite streams are implemented as pairs whose car holds the first element of the stream and whose cdr holds a promise to deliver the rest of the stream.
define head car)
(define (tail stream)
(force (cdr stream))) (
The following illustrates the use of integratesystem in integrating the system $$C {dv_C \\over dt} = i_L  {v_C \\over R}$$ $$L {di_L \\over dt} = v_C$$ which models a damped oscillator.
define (dampedoscillator R L C)
(lambda (state)
(let ((Vc (vectorref state 0))
(vectorref state 1)))
(Il (vector ( 0 (+ (/ Vc (* R C)) (/ Il C)))
(/ Vc L)))))
(
define thestates
(
(integratesystem10000 1000 .001)
(dampedoscillator 1 0)
'#(.01))
Harold Abelson and Gerald Jay Sussman with Julie Sussman. Structure and Interpretation of Computer Programs, second edition. MIT Press, Cambridge, 1996.
Alan Bawden and Jonathan Rees. Syntactic closures. In Proceedings of the 1988 ACM Symposium on Lisp and Functional Programming, pages 86–95.
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. http://www.ietf.org/rfc/rfc2119.txt, 1997.
Robert G. Burger and R. Kent Dybvig. Printing floatingpoint numbers quickly and accurately. In Proceedings of the ACM SIGPLAN ’96 Conference on Programming Language Design and Implementation, pages 108–116.
William Clinger. How to read floating point numbers accurately. In Proceedings of the ACM SIGPLAN ’90 Conference on Programming Language Design and Implementation, pages 92–101. Proceedings published as SIGPLAN Notices 25(6), June 1990.
William Clinger. Proper Tail Recursion and Space Efficiency. In Proceedings of the 1998 ACM Conference on Programming Language Design and Implementation, June 1998.
William Clinger. SRFI 6: Basic String Ports. http://srfi.schemers.org/srfi6/, 1999.
William Clinger, editor. The revised revised report on Scheme, or an uncommon Lisp. MIT Artificial Intelligence Memo 848, August 1985. Also published as Computer Science Department Technical Report 174, Indiana University, June 1985.
William Clinger and Jonathan Rees. Macros that work. In Proceedings of the 1991 ACM Conference on Principles of Programming Languages, pages 155–162.
William Clinger and Jonathan Rees, editors. The revised^{4} report on the algorithmic language Scheme. In ACM Lisp Pointers 4(3), pages 1–55, 1991.
Mark Davis. Unicode Standard Annex #44, Unicode Character Database. http://unicode.org/reports/tr44/, 2010.
R. Kent Dybvig, Robert Hieb, and Carl Bruggeman. Syntactic abstraction in Scheme. Lisp and Symbolic Computation 5(4):295–326, 1993.
Marc Feeley. SRFI 4: Homogeneous Numeric Vector Datatypes. http://srfi.schemers.org/srfi4/, 1999.
Carol Fessenden, William Clinger, Daniel P. Friedman, and Christopher Haynes. Scheme 311 version 4 reference manual. Indiana University Computer Science Technical Report 137, February 1983. Superseded by .
D. Friedman, C. Haynes, E. Kohlbecker, and M. Wand. Scheme 84 interim reference manual. Indiana University Computer Science Technical Report 153, January 1985.
Martin Gardner. Mathematical Games: The fantastic combinations of John Conway’s new solitaire game “Life.” In Scientific American, 223:120–123, October 1970.
IEEE Standard 7542008. IEEE Standard for FloatingPoint Arithmetic. IEEE, New York, 2008.
IEEE Standard 11781990. IEEE Standard for the Scheme Programming Language. IEEE, New York, 1991.
Richard Kelsey. SRFI 9: Defining Record Types. http://srfi.schemers.org/srfi9/, 1999.
Richard Kelsey, William Clinger, and Jonathan Rees, editors. The revised^{5} report on the algorithmic language Scheme. HigherOrder and Symbolic Computation, 11(1):7105, 1998.
Eugene E. Kohlbecker Jr. Syntactic Extensions in the Programming Language Lisp. PhD thesis, Indiana University, August 1986.
Eugene E. Kohlbecker Jr., Daniel P. Friedman, Matthias Felleisen, and Bruce Duba. Hygienic macro expansion. In Proceedings of the 1986 ACM Conference on Lisp and Functional Programming, pages 151–161.
John McCarthy. Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I. Communications of the ACM 3(4):184–195, April 1960.
MIT Department of Electrical Engineering and Computer Science. Scheme manual, seventh edition. September 1984.
Peter Naur et al. Revised report on the algorithmic language Algol 60. Communications of the ACM 6(1):1–17, January 1963.
Paul Penfield, Jr. Principal values and branch cuts in complex APL. In APL ’81 Conference Proceedings, pages 248–256. ACM SIGAPL, San Francisco, September 1981. Proceedings published as APL Quote Quad 12(1), ACM, September 1981.
Jonathan A. Rees and Norman I. Adams IV. T: A dialect of Lisp or, lambda: The ultimate software tool. In Conference Record of the 1982 ACM Symposium on Lisp and Functional Programming, pages 114–122.
Jonathan A. Rees, Norman I. Adams IV, and James R. Meehan. The T manual, fourth edition. Yale University Computer Science Department, January 1984.
Jonathan Rees and William Clinger, editors. The revised^{3} report on the algorithmic language Scheme. In ACM SIGPLAN Notices 21(12), pages 37–79, December 1986.
Olin Shivers. SRFI 1: List Library. http://srfi.schemers.org/srfi1/, 1999.
Guy Lewis Steele Jr. and Gerald Jay Sussman. The revised report on Scheme, a dialect of Lisp. MIT Artificial Intelligence Memo 452, January 1978.
Guy Lewis Steele Jr. Rabbit: a compiler for Scheme. MIT Artificial Intelligence Laboratory Technical Report 474, May 1978.
Michael Sperber, R. Kent Dybvig, Mathew Flatt, and Anton van Straaten, editors. The revised^{6} report on the algorithmic language Scheme. Cambridge University Press, 2010.
Guy Lewis Steele Jr. Common Lisp: The Language, second edition. Digital Press, Burlington MA, 1990.
Gerald Jay Sussman and Guy Lewis Steele Jr. Scheme: an interpreter for extended lambda calculus. MIT Artificial Intelligence Memo 349, December 1975.
Joseph E. Stoy. Denotational Semantics: The ScottStrachey Approach to Programming Language Theory. MIT Press, Cambridge, 1977.
Texas Instruments, Inc. TI Scheme Language Reference Manual. Preliminary version 1.0, November 1985.
Andre van Tonder. SRFI 45: Primitives for Expressing Iterative Lazy Algorithms. http://srfi.schemers.org/srfi45/, 2002.
Martin Gasbichler, Eric Knauel, Michael Sperber and Richard Kelsey. How to Add Threads to a Sequential Language Without Getting Tangled Up. Proceedings of the Fourth Workshop on Scheme and Functional Programming, November 2003.
International Earth Rotation Service. Historical table of TAIUTC
offsets. http://maia.usno.navy.mil/ser7/taiutc.dat #
(scheme base)
_
TODO (missing in r7rs?)
...
It is called ellipsis. It signify that a pattern must be repeated.
=>
TODO
else
Used in cond
and case
form as in the last
clause as a fallback.
(* number ...)
Multiplication procedure.
(+ number ...)
Addition procedure.
( number ...)
Substraction procedure.
(/ number ...)
Division procedure. Raise 'numericaloverflow
condition
in case where denominator is zero.
(< number number ...)
Less than procedure. Return a boolean.
(<= number number ...)
Less than or equal procedure. Return a boolean.
(= number number ...)
Return #t
if the numbers passed as parameters are equal.
And #f
otherwise.
(> number number ...)
Greater than procedure. Return a boolean.
(>= number number ...)
Greater than or equal. Return a boolean.
(abs number)
Return the absolute value of NUMBER
.
(and test1 ...)
The test
expressions are evaluated from left to right,
and if any expression evaluates to #f
, then #f
is returned. Any remaining expressions are not evaluated. If all the
expressions evaluate to true values, the values of the last expression
are returned. If there are no expressions, then #t
is
returned.
(append lst ...)
Return the list made of the list passed as parameters in the same order.
(apply proc arg1 ... args)
The apply procedure calls proc with the elements of the list
(append (list arg1 ...) args)
as the actual arguments.
(assoc obj alist)
Return the first pair which car
is equal to
OBJ
according to the predicate equal?
. Or it
returns #f
.
(assq obj alist)
Return the first pair which car
is equal to
OBJ
according to the predicate eq?
. Or it
returns #f
.
(assv obj alist)
Return the first pair which car
is equal to
OBJ
according to the predicate eqv?
. Or it
returns #f
.
begin
syntaxThere is two uses of begin
.
(begin expressionordefinition ...)
This form of begin can appear as part of a body, or at the outermost level of a program, or at the REPL, or directly nested in a begin that is itself of this form. It causes the contained expressions and definitions to be evaluated exactly as if the enclosing begin construct were not present.
TODO: example
(begin expression1 expression2 ...)
This form of begin can be used as an ordinary expression. The expressions are evaluated sequentially from left to right, and the values of the last expression are returned. This expression type is used to sequence side effects such as assignments or input and output.
TODO: example
binaryport?
TODO: not implemented
(boolean=? obj ...)
Return #t
if the scheme objects passed as arguments are
the same boolean. Otherwise it return #f
.
(boolean? obj)
Return #t
if OBJ
is a boolean. Otherwise
#f
.
(bytevector byte ...)
Returns a newly allocated bytevector containing its arguments.
(bytevectorappend bytevector ...)
Returns a newly allocated bytevector whose elements arethe concatenation of the elements in the given bytevectors.
(bytevectorcopy bytevector [start [end]])
Returns a newly allocated bytevector containing the bytes in bytevector between start and end.
(bytevectorcopy! to at from [start [end]])
Copies the bytes of bytevector from
between
start
and end
to bytevector TO
,
starting at at
. The order in which bytes are copied is
unspecified, except that if the source and destination overlap, copying
takes place as if the source is first copied into a temporary bytevector
and then into the destination. This can be achieved without allocating
storage by making sure to copy in the correct direction in such
circumstances.
(bytevectorlength bytevector)
Returns the length of bytevector in bytes as an exact integer.
bytevectoru8ref
Returns the K
th byte of BYTEVECTOR
. It is
an error if K
is not a valid index of
BYTEVECTOR
.
bytevectoru8set!
Stores BYTE
as the K
th byte of
BYTEVECTOR
.
It is an error if K
is not a valid index of
BYTEVECTOR
.
(bytevector? obj)
Returns #t
if OBJ
is a bytevector.
Otherwise, #f
is returned.
caar
TODO
cadr
TODO
(callwithcurrentcontinuation proc)
It is an error if proc does not accept one argument.
The procedure callwithcurrentcontinuation (or its equivalent abbreviation call/cc) packages the current continuation (see the rationale below) as an “escape procedure” and passes it as an argument to proc. The escape procedure is a Scheme procedure that, if it is later called, will abandon whatever continuation is in effect at that later time and will instead use the continuation that was in effect when the escape procedure was created. Calling the escape procedure will cause the invocation of before and after thunks installed using dynamicwind.
The escape procedure accepts the same number of arguments as the continuation to the original call to callwithcurrentcontinuation. Most continuations take only one value. Continuations created by the callwithvalues procedure (including the initialization expressions of definevalues, letvalues, and letvalues expressions), take the number of values that the consumer expects. The continuations of all nonfinal expressions within a sequence of expressions, such as in lambda, caselambda, begin, let, let, letrec, letrec, letvalues, letvalues, letsyntax, letrecsyntax, parameterize, guard, case, cond, when, and unless expressions, take an arbitrary number of values because they discard the values passed to them in any event. The effect of passing no values or more than one value to continuations that were not created in one of these ways is unspecified.
The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It can be stored in variables or data structures and can be called as many times as desired. However, like the raise and error procedures, it never returns to its caller.
TODO: example
(callwithport port proc)
The callwithport
procedure calls PROC
with PORT
as an argument. If PROC
returns,
then the PORT
is closed automatically and the values
yielded by the PROC
are returned. If PROC
does
not return, then the PORT
must not be closed automatically
unless it is possible to prove that the port will never again be used
for a read or write operation.
It is an error if PROC
does not accept one argument.
(callwithvalues producer consumer)
Calls its producer argument with no arguments and a continuation
that, when passed some values, calls the consumer procedure with those
values as arguments. The continuation for the call to consumer is the
continuation of the call to callwithvalues
.
(call/cc proc)
Abbreviation for callwithcontinuation
.
(car pair)
Returns the contents of the car field of pair. Note that it is an
error to take the car
of the empty list.
(case <key> <clause1> <clause2> ...)
syntaxTODO
cdar
TODO
cddr
TODO
cdr
Returns the contents of the cdr
field of pair. Note that
it is an error to take the cdr
of the empty list.
(ceiling x)
The ceiling procedure returns the smallest integer not smaller than x.
(char>integer char)
Given a Unicode character, char>integer
returns an
exact integer between 0 and #xD7FF or between #xE000 and #x10FFFF which
is equal to the Unicode scalar value of that character. Given a
nonUnicode character, it returns an exact integer greater than
#x10FFFF.
(charready? [port])
Returns #t if a character is ready on the textual input port and returns #f otherwise. If charready returns #t then the next readchar operation on the given port is guaranteed not to hang. If the port is at end of file then charready? returns #t.
char<=?
TODO
char<?
TODO
char=?
TODO
char>=?
TODO
char>?
TODO
char?
Returns #t if obj is a character, otherwise returns #f.
(closeinputport port)
Closes the resource associated with port, rendering the port incapable of delivering or accepting data.
(closeoutputport port)
Closes the resource associated with port, rendering the port incapable of delivering or accepting data.
(closeport port)
Closes the resource associated with port, rendering the port incapable of delivering or accepting data.
(complex? obj)
Returns #t if obj is a complex number, otherwise returns #f.
(cond <clause1> ...)
TODO
condexpand
TODO: not implemented
(cons obj1 obj2)
Returns a newly allocated pair whose car is obj1 and whose cdr is obj2. The pair is guaranteed to be different (in the sense of eqv?) from every existing object.
(currenterrorport [port])
Returns the current default error port (an output port). That
procedure is also a parameter object, which can be overridden with
parameterize
.
(currentinputport [port])
Returns the current default input port. That procedure is also a
parameter object, which can be overridden with
parameterize
.
currentoutputport
Returns the current default output port. That procedure is also a
parameter object, which can be overridden with
parameterize
.
(define <name> <expr>)
TODO
(define (<name> <variable> ...) <expr> ...)
TODO
definerecordtype
syntaxTODO
definesyntax
TODO
(definevalues var1 ... expr)
syntaxcreates multiple definitions from a single expression returning multiple values. It is allowed wherever define is allowed.
(denominator q)
Return the denominator of their argument; the result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1.
do
TODO
(dynamicwind before thunk after)
TODO
(eofobject)
Returns an endoffile object, not necessarily unique.
(eofobject? obj)
Returns #t if obj is an endoffile object, otherwise returns #f. A endoffile object will ever be an object that can be read in using read.
(eq? obj1 obj2)
The eq? procedure is similar to eqv? except that in some cases it is capable of discerning distinctions finer than those detectable by eqv?. It must always return #f when eqv? also would, but may return #f in some cases where eqv? would return #t.
On symbols, booleans, the empty list, pairs, and records, and also on nonempty strings, vectors, and bytevectors, eq? and eqv? are guaranteed to have the same behavior. On procedures, eq? must return true if the arguments’ location tags are equal. On numbers and characters, eq?’s behavior is implementationdependent, but it will always return either true or false. On empty strings, empty vectors, and empty bytevectors, eq? may also behave differently from eqv?.
(equal? obj1 obj2)
The equal? procedure, when applied to pairs, vectors, strings and bytevectors, recursively compares them, returning #t when the unfoldings of its arguments into (possibly infinite) trees are equal (in the sense of equal?) as ordered trees, and #f otherwise. It returns the same as eqv? when applied to booleans, symbols, numbers, characters, ports, procedures, and the empty list. If two objects are eqv?, they must be equal? as well. In all other cases, equal? may return either #t or #f.
Even if its arguments are circular data structures, equal? must always terminate.
(eqv? obj1 obj2)
The eqv? procedure defines a useful equivalence relation on objects. Briefly, it returns #t if obj1 and obj2 are normally regarded as the same object.
TODO: complete based on r7rs small and guile.
(error [who] message . irritants)
Raises an exception as if by calling raise on a newly allocated implementationdefined object which encapsulates the information provided by message, as well as any objs, known as the irritants. The procedure errorobject? must return #t on such objects.
(errorobjectirritants error)
Returns a list of the irritants encapsulated by error.
(errorobjectmessage error)
Returns the message encapsulated by error.
(errorobject? obj)
Returns #t if obj is an object created by error
or one
of an implementationdefined set of objects. Otherwise, it returns
#f. The objects used to signal errors, including those which satisfy the
predicates fileerror?
and readerror?
, may or
may not satisfy errorobject?
.
(even? number)
Return #t
if NUMBER
is even. Otherwise
#f
.
(exact z)
TODO: FIXME
The procedure exact returns an exact representation of z. The value
returned is the exact number that is numerically closest to the
argument. For exact arguments, the result is the same as the argument.
For inexact nonintegral real arguments, the implementation may return a
rational approximation, or may report an implementation violation. For
inexact complex arguments, the result is a complex number whose real and
imaginary parts are the result of applying exact to the real and
imaginary parts of the argument, respectively. If an inexact argument
has no reasonably close exact equivalent, (in the sense of
=
), then a violation of an implementation restriction may
be reported.
(exactintegersqrt k)
TODO
(exactinteger? z)
Returns #t if z is both exact and an integer; otherwise returns #f.
(exact? z)
Return #t
if Z
is exact. Otherwise
#f
.
(expt z1 z2)
Returns z1
raised to the power z2
.
features
TODO: no implemented
(fileerror? error)
TODO: not implemented?
(floor x)
The floor procedure returns the largest integer not larger than x.
floorquotient
TODO
floorremainder
TODO
floor/
TODO
(flushoutputport [port])
Flushes any buffered output from the buffer of outputport to the underlying file or device and returns an unspecified value.
(foreach proc list1 ...)
It is an error if proc does not accept as many arguments as there are lists.
The arguments to foreach are like the arguments to map, but foreach calls proc for its side effects rather than for its values. Unlike map, foreach is guaranteed to call proc on the elements of the lists in order from the first element(s) to the last, and the value returned by foreach is unspecified. If more than one list is given and not all lists have the same length, foreach terminates when the shortest list runs out. The lists can be circular, but it is an error if all of them are circular.
(gcd n1 ...)
Return the greatest common divisor.
(getoutputbytevector port)
It is an error if port was not created with
openoutputbytevector
.
Returns a bytevector consisting of the bytes that have been output to the port so far in the order they were output.
(getoutputstring port)
It is an error if port was not created with openoutputstring.
Returns a string consisting of the characters that have been output to the port so far in the order they were output.
(guard <clause> ...)
syntaxTODO
(if <expr> <then> [<else>])
TODO
include
TODO
includeci
TODO: not implemented
(inexact z)
The procedure inexact returns an inexact representation of z. The
value returned is the inexact number that is numerically closest to the
argument. For inexact arguments, the result is the same as the argument.
For exact complex numbers, the result is a complex number whose real and
imaginary parts are the result of applying inexact to the real and
imaginary parts of the argument, respectively. If an exact argument has
no reasonably close inexact equivalent (in the sense of =
),
then a violation of an implementation restriction may be reported.
(inexact? z)
Return #t
if Z
is inexact. Otherwise
#f
.
(inputportopen? port)
Returns #t if port is still open and capable of performing input, and
#f
otherwise.
(inputport? obj)
Return #t
if obj is an input port. Otherwise it return
#f
.
(integer>char integer)
Given an exact integer that is the value returned by a character when char>integer is applied to it, integer>char returns that character.
(integer? obj)
Return #t
if OBJ
is an integer. Otherwise
#f
.
(lambda <formals> <expr> ...)
TODO
(lcm n1 ...)
Return the least common multiple of its arguments.
(length list)
Returns the length of list.
let
TODO
let*
TODO
let*values
TODO
letsyntax
TODO
letvalues
TODO
letrec
TODO
letrec*
TODO
letrecsyntax
TODO
(list obj ...)
Returns a newly allocated list of its arguments.
(list>string list)
It is an error if any element of list is not a character.
list>string returns a newly allocated string formed from the elements in the list list.
(list>vector list)
The list>vector procedure returns a newly created vector initialized to the elements of the list list.
(listcopy obj)
Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of eqv?) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in the sense of eqv?. An obj which is not a list is returned unchanged. It is an error if obj is a circular list.
(listref list k)
The list argument can be circular, but it is an error if list has fewer than k elements.
Returns the kth element of list. (This is the same as the car of (listtail list k).)
(listset! list k obj)
It is an error if k is not a valid index of list.
The listset! procedure stores obj in element k of list.
(listtail list k)
It is an error if list has fewer than k elements.
Returns the sublist of list obtained by omitting the first k elements.
(list? obj)
Return #t
if OBJ
is a list. Otherwise
#f
.
(makebytevector k [byte])
The makebytevector procedure returns a newly allocated bytevector of length k. If byte is given, then all elements of the bytevector are initialized to byte, otherwise the contents of each element are unspecified.
(makelist k [fill])
Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.
(makeparameter init [converter])
Returns a newly allocated parameter object, which is a procedure that accepts zero arguments and returns the value associated with the parameter object. Initially, this value is the value of (converter init), or of init if the conversion procedure converter is not specified. The associated value can be temporarily changed using parameterize, which is described below.
(makestring k [char])
The makestring procedure returns a newly allocated string of length k. If char is given, then all the characters of the string are initialized to char, otherwise the contents of the string are unspecified.
(makevector k [fill])
Returns a newly allocated vector of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.
(map proc list1 ...)
It is an error if proc does not accept as many arguments as there are lists and return a single value.
The map procedure applies proc elementwise to the elements of the lists and returns a list of the results, in order. If more than one list is given and not all lists have the same length, map terminates when the shortest list runs out. The lists can be circular, but it is an error if all of them are circular. It is an error for proc to mutate any of the lists. The dynamic order in which proc is applied to the elements of the lists is unspecified. If multiple returns occur from map, the values returned by earlier returns are not mutated.
(max x1 ...)
Return the maximum of its arguments.
(member obj list [compare])
Return the first sublist of list whose car
is
obj
, where the sublists of list are the nonempty lists
returned by (listtail list k) for k less than the length of list. If
obj
does not occur in list
, then
#f
(not the empty list) is returned.
Uses compare
, if given, and equal?
otherwise.
(memq obj list)
Return the first sublist of list whose car
is
obj
, where the sublists of list are the nonempty lists
returned by (listtail list k) for k less than the length of list. If
obj
does not occur in list
, then
#f
(not the empty list) is returned.
Use eq?
for comparison.
(memv obj list)
Return the first sublist of list whose car
is
obj
, where the sublists of list are the nonempty lists
returned by (listtail list k) for k less than the length of list. If
obj
does not occur in list
, then
#f
(not the empty list) is returned.
Uses eqv?
for comparison.
(min x1 ...)
Return the minimum of its arguments.
(modulo n1 n2)
modulo
is equivalent to floorremainder
.
Provided for backward compatibility.
(negative? x)
Return #t
if X
is negative. Otherwise
#f
.
(newline [port])
Writes an end of line to output port.
(not obj)
The not procedure returns #t if obj is false, and returns #f otherwise.
(null? obj)
Returns #t if obj is the empty list, otherwise returns #f.
(number>string z [radix])
It is an error if radix is not one of 2, 8, 10, or 16.
(number? obj)
Return #t
if OBJ
is a number. Otherwise
#f
.
(numerator q)
TODO
(odd? number)
Return #t
if NUMBER
is odd. Otherwise
#f
.
(openinputbytevector bytevector)
Takes a bytevector and returns a binary input port that delivers bytes from the bytevector.
(openinputstring string)
Takes a string and returns a textual input port that delivers characters from the string. If the string is modified, the effect is unspecified.
(openoutputbytevector)
Returns a binary output port that will accumulate bytes for retrieval
by getoutputbytevector
.
(openoutputstring)
Returns a textual output port that will accumulate characters for
retrieval by getoutputstring
.
(or test1 ...)
syntaxThe test
expressions are evaluated from left to right,
and the value of the first expression that evaluates to a true value is
returned. Any remaining expressions are not evaluated. If all
expressions evaluate to #f or if there are no expressions, then #f is
returned.
(outputportopen? port)
Returns #t if port is still open and capable of performing output, and #f otherwise.
(outputport? obj)
Return #t if obj is an output port. Otherwise return #f.
(pair? obj)
The pair? predicate returns #t if obj is a pair, and otherwise returns #f.
(parameterize ((param1 value1) ...) expr ...)
A parameterize expression is used to change the values returned by specified parameter objects during the evaluation of the body.
The param and value expressions are evaluated in an unspecified order. The body is evaluated in a dynamic environment in which calls to the parameters return the results of passing the corresponding values to the conversion procedure specified when the parameters were created. Then the previous values of the parameters are restored without passing them to the conversion procedure. The results of the last expression in the body are returned as the results of the entire parameterize expression.
Note: If the conversion procedure is not idempotent, the results of (parameterize ((x (x))) …), which appears to bind the parameter x to its current value, might not be what the user expects.
If an implementation supports multiple threads of execution, then parameterize must not change the associated values of any parameters in any thread other than the current thread and threads created inside body.
Parameter objects can be used to specify configurable settings for a computation without the need to pass the value to every procedure in the call chain explicitly.
(peekchar [port])
Returns the next character available from the textual input port, but without updating the port to point to the following character. If no more characters are available, an endoffile object is returned.
Note: The value returned by a call to peekchar is the same as the value that would have been returned by a call to readchar with the same port. The only difference is that the very next call to readchar or peekchar on that port will return the value returned by the preceding call to peekchar. In particular, a call to peekchar on an interactive port will hang waiting for input whenever a call to readchar would have hung.
(peeku8 [port])
Returns the next byte available from the binary input port, but without updating the port to point to the following byte. If no more bytes are available, an endoffile object is returned.
(port? obj)
Return #t
if OBJ
is port. Otherwise
#f
.
(positive? x)
Return #t
if X
is positive. Otherwise
#f
.
(procedure? obj)
Return #t
if OBJ
is a procedure. Otherwise
#f
.
quasiquote
TODO
quote
TODO
quotient
TODO
(raise obj)
Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as that of the call to raise, except that the current exception handler is the one that was in place when the handler being called was installed. If the handler returns, a secondary exception is raised in the same dynamic environment as the handler. The relationship between obj and the object raised by the secondary exception is unspecified.
(raisecontinuable obj)
Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as the call to raisecontinuable, except that: (1) the current exception handler is the one that was in place when the handler being called was installed, and (2) if the handler being called returns, then it will again become the current exception handler. If the handler returns, the values it returns become the values returned by the call to raisecontinuable.
(rational? obj)
Return #t
if OBJ
is a rational number.
Otherwise #f
.
(rationalize x y)
The rationalize procedure returns the simplest rational number differing from x by no more than y.
(readbytevector k [port])
Reads the next k bytes, or as many as are available before the end of file, from the binary input port into a newly allocated bytevector in lefttoright order and returns the bytevector. If no bytes are available before the end of file, an endoffile object is returned.
(readbytevector! bytevector [port [start [end]]])
Reads the next end  start bytes, or as many as are available before the end of file, from the binary input port into bytevector in lefttoright order beginning at the start position. If end is not supplied, reads until the end of bytevector has been reached. If start is not supplied, reads beginning at position 0. Returns the number of bytes read. If no bytes are available, an endoffile object is returned.
(readchar [port])
Returns the next character available from the textual input port, updating the port to point to the following character. If no more characters are available, an endoffile object is returned.
(readerror? obj)
Error type predicates. Returns #t if obj is an object raised by the read procedure. Otherwise, it returns #f.
(readline [port])
Returns the next line of text available from the textual input port, updating the port to point to the following character. If an end of line is read, a string containing all of the text up to (but not including) the end of line is returned, and the port is updated to point just past the end of line. If an end of file is encountered before any end of line is read, but some characters have been read, a string containing those characters is returned. If an end of file is encountered before any characters are read, an endoffile object is returned. For the purpose of this procedure, an end of line consists of either a linefeed character, a carriage return character, or a sequence of a carriage return character followed by a linefeed character. Implementations may also recognize other end of line characters or sequences.
(readstring k [port])
Reads the next k characters, or as many as are available before the end of file, from the textual input port into a newly allocated string in lefttoright order and returns the string. If no characters are available before the end of file, an endoffile object is returned.
(readu8 [port])
Returns the next byte available from the binary input port, updating the port to point to the following byte. If no more bytes are available, an endoffile object is returned.
(real? obj)
Return #t if OBJ
is real number. Otherwise
#f
.
(remainder n1 n2)
TODO
(reverse list)
Returns a newly allocated list consisting of the elements of list in reverse order.
(round x)
TODO
(set! <variable> <expression>)
syntaxExpression is evaluated, and the resulting value is stored in the location to which variable is bound. It is an error if variable is not bound either in some region enclosing the set! expression or else globally. The result of the set! expression is unspecified.
(setcar! pair obj)
Stores obj
in the car field of pair
.
(setcdr! pair obj)
Stores obj in the cdr field of pair.
(square z)
Returns the square of z. This is equivalent to (* z z).
(string char ...)
Returns a newly allocated string composed of the arguments. It is analogous to list.
(string>list string [start [end]])
The string>list procedure returns a newly allocated list of the characters of string between start and end.
(string>number string [radix])
Returns a number of the maximally precise representation expressed by the given string. It is an error if radix is not 2, 8, 10, or 16.
If supplied, radix is a default radix that will be overridden if an explicit radix prefix is present in string (e.g. “#o177”). If radix is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number, or would result in a number that the implementation cannot represent, then string>number returns #f. An error is never signaled due to the content of string.
(string>symbol string)
Returns the symbol whose name is string. This procedure can create symbols with names containing special characters that would require escaping when written, but does not interpret escapes in its input.
(string>utf8 string [start [end]])
The string>utf8 procedure encodes the characters of a string between start and end and returns the corresponding bytevector.
(string>vector string [start [end]])
The string>vector procedure returns a newly created vector initialized to the elements of the string string between start and end.
(stringappend string ...)
Returns a newly allocated string whose characters are the concatenation of the characters in the given strings.
(stringcopy string [start [end]])
Returns a newly allocated copy of the part of the given string between start and end.
(stringcopy! to at from [start [end]])
It is an error if at is less than zero or greater than the length of to. It is also an error if ( (stringlength to) at) is less than ( end start).
Copies the characters of string from between start and end to string to, starting at at. The order in which characters are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary string and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
(stringfill! string fill [start [end]])
It is an error if fill is not a character.
The stringfill! procedure stores fill in the elements of string between start and end.
(stringforeach proc string1 ...)
It is an error if proc does not accept as many arguments as there are strings.
The arguments to stringforeach are like the arguments to stringmap, but stringforeach calls proc for its side effects rather than for its values. Unlike stringmap, stringforeach is guaranteed to call proc on the elements of the lists in order from the first element(s) to the last, and the value returned by stringforeach is unspecified. If more than one string is given and not all strings have the same length, stringforeach terminates when the shortest string runs out. It is an error for proc to mutate any of the strings.
(stringlength string)
Returns the number of characters in the given string.
(stringmap proc string1 ...)
It is an error if proc does not accept as many arguments as there are strings and return a single character.
The stringmap procedure applies proc elementwise to the elements of the strings and returns a string of the results, in order. If more than one string is given and not all strings have the same length, stringmap terminates when the shortest string runs out. The dynamic order in which proc is applied to the elements of the strings is unspecified. If multiple returns occur from stringmap, the values returned by earlier returns are not mutated.
(stringref string k)
It is an error if k is not a valid index of string.
The stringref procedure returns character k of string using zeroorigin indexing. There is no requirement for this procedure to execute in constant time.
(stringset! string k char)
It is an error if k is not a valid index of string.
The stringset! procedure stores char in element k of string. There is no requirement for this procedure to execute in constant time.
string<=?
TODO
string<?
TODO
(string=? string1 string2 ...)
Returns #t if all the strings are the same length and contain exactly the same characters in the same positions, otherwise returns #f.
string>=?
TODO
string>?
TODO
(string? obj)
Return #t
if OBJ
is string. Otherwise
#f
.
(substring string start end)
The substring procedure returns a newly allocated string formed from the characters of string beginning with index start and ending with index end. This is equivalent to calling stringcopy with the same arguments, but is provided for backward compatibility and stylistic flexibility.
(symbol>string symbol)
Returns the name of symbol as a string, but without adding escapes. It is an error to apply mutation procedures like stringset! to strings returned by this procedure.
(symbol=? symbol1 symbol2 ...)
Returns #t if all the arguments are symbols and all have the same names in the sense of string=?.
(symbol? obj)
Returns #t if obj is a symbol, otherwise returns #f.
syntaxerror
TODO
syntaxrules
TODO
textualport?
TODO
(truncate x)
TODO
truncatequotient
TODO
truncateremainder
TODO
truncate/
TODO
(u8ready? [port])
Returns #t if a byte is ready on the binary input port and returns #f otherwise. If u8ready? returns #t then the next readu8 operation on the given port is guaranteed not to hang. If the port is at end of file then u8ready? returns #t.
(unless <test> <expr> ...)
syntaxThe test is evaluated, and if it evaluates to #f, the expressions are evaluated in order. The result of the unless expression is unspecified.
unquote
TODO
unquotesplicing
TODO
(utf8>string bytevector [start [end]])
It is an error for bytevector to contain invalid UTF8 byte sequences.
The utf8>string procedure decodes the bytes of a bytevector between start and end and returns the corresponding string.
(values obj ...)
Delivers all of its arguments to its continuation.
(vector obj ...)
Returns a newly allocated vector whose elements contain the given arguments. It is analogous to list.
(vector>list vector [start [end]])
The vector>list procedure returns a newly allocated list of the objects contained in the elements of vector between start and end. The list>vector procedure returns a newly created vector initialized to the elements of the list list.
(vector>string vector [start [end]])
It is an error if any element of vector between start and end is not a character.
The vector>string procedure returns a newly allocated string of the objects contained in the elements of vector between start and end. The string>vector procedure returns a newly created vector initialized to the elements of the string string between start and end.
(vectorappend vector ...)
Returns a newly allocated vector whose elements are the concatenation of the elements of the given vectors.
(vectorcopy vector [start [end]])
Returns a newly allocated copy of the elements of the given vector between start and end. The elements of the new vector are the same (in the sense of eqv?) as the elements of the old.
(vectorcopy! to at from [start [end]])
It is an error if at is less than zero or greater than the length of to. It is also an error if ( (vectorlength to) at) is less than ( end start).
Copies the elements of vector from between start and end to vector to, starting at at. The order in which elements are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary vector and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
(vectorfill! vector fill [start [end]])
The vectorfill! procedure stores fill in the elements of vector between start and end.
(vectorforeach proc vector1 ...)
It is an error if proc does not accept as many arguments as there are vectors.
The arguments to vectorforeach are like the arguments to vectormap, but vectorforeach calls proc for its side effects rather than for its values. Unlike vectormap, vectorforeach is guaranteed to call proc on the elements of the vectors in order from the first element(s) to the last, and the value returned by vectorforeach is unspecified. If more than one vector is given and not all vectors have the same length, vectorforeach terminates when the shortest vector runs out. It is an error for proc to mutate any of the vectors.
(vectorlength vector)
Returns the number of elements in vector as an exact integer.
(vectormap proc vector1 ...)
It is an error if proc does not accept as many arguments as there are vectors and return a single value.
The vectormap procedure applies proc elementwise to the elements of the vectors and returns a vector of the results, in order. If more than one vector is given and not all vectors have the same length, vectormap terminates when the shortest vector runs out. The dynamic order in which proc is applied to the elements of the vectors is unspecified. If multiple returns occur from vectormap, the values returned by earlier returns are not mutated.
(vectorref vector k)
It is an error if k is not a valid index of vector.
The vectorref procedure returns the contents of element k of vector.
(vectorset! vector k obj)
It is an error if k is not a valid index of vector.
The vectorset! procedure stores obj in element k of vector.
vector?
Returns #t if obj is a bytevector. Otherwise, #f is returned.
(when <test> <expr> ...)
syntaxThe test is evaluated, and if it evaluates to a true value, the expressions are evaluated in order. The result of the when expression is unspecified.
withexceptionhandler
TODO
(writebytevector bytevector [port [start [end]]])
Writes the bytes of bytevector from start to end in lefttoright order to the binary output port.
(writechar char [port])
Writes the character char (not an external representation of the character) to the given textual output port and returns an unspecified value.
(writestring string [port [start [end]]])
Writes the characters of string from start to end in lefttoright order to the textual output port.
(writeu8 byte [port])
Writes the byte to the given binary output port and returns an unspecified value.
(zero? z)
Return #t
if z is zero. Otherwise #f
. #
(scheme bitwise)
This library is based on SRFI151.
This library offers a coherent and comprehensive set of procedures for performing bitwise logical operations on integers.
(bitwisenot i)
Returns the bitwise complement of i; that is, all 1 bits are changed to 0 bits and all 0 bits to 1 bits.
bitwisenot 10) ;; => 11
(bitwisenot 37) ;; => 36 (
The following ten procedures correspond to the useful set of nontrivial twoargument boolean functions. For each such function, the corresponding bitwise operator maps that function across a pair of bitstrings in a bitwise fashion. The core idea of this group of functions is this bitwise “lifting” of the set of dyadic boolean functions to bitstring parameters.
(bitwiseand i ...)
(bitwiseior i ...)
(bitwisexor i ...)
(bitwiseeqv i ...)
These operations are associative. When passed no arguments, the procedures return the identity values 1, 0, 0, and 1 respectively.
The bitwiseeqv procedure produces the complement of the bitwisexor procedure. When applied to three arguments, it does not produce a 1 bit everywhere that a, b and c all agree. That is, it does not produce
bitwiseior (bitwiseand a b c)
(bitwiseand (bitwisenot a)
(bitwisenot b)
(bitwisenot c))) (
Rather, it produces (bitwiseeqv a (bitwiseeqv b c)) or the equivalent (bitwiseeqv (bitwiseeqv a b) c).
bitwiseior 3 10) => 11
(bitwiseand 11 26) => 10
(bitwisexor 3 10) => 9
(37 12) => 42
(bitwiseeqv bitwiseand 37 12) => 4 (
(bitwisenand i j)
(bitwisenor i j)
(bitwiseandc1 i j)
(bitwiseandc2 i j)
(bitwiseorc1 i j)
(bitwiseorc2 i j)
These operations are not associative.
11 26) => 11
(bitwisenand 11 26) => 28
(bitwisenor 11 26) => 16
(bitwiseandc1 11 26) => 1
(bitwiseandc2 11 26) => 2
(bitwiseorc1 11 26) => 17 (bitwiseorc2
(arithmeticshift i count)
Returns the arithmetic left shift when count>0; right shift when count < 0.
8 2) => 32
(arithmeticshift 4 0) => 4
(arithmeticshift 8 1) => 4
(arithmeticshift 100000000000000000000000000000000 100) => 79 (arithmeticshift 
(bitcount i)
Returns the population count of 1’s (i >= 0) or 0’s (i < 0). The result is always nonnegative.
Compatibility note: The R6RS analogue bitwisebitcount applies bitwisenot to the population count before returning it if i is negative.
0) => 0
(bitcount 1) => 0
(bitcount 7) => 3
(bitcount 13) => 3 ;Two'scomplement binary: ...0001101
(bitcount 13) => 2 ;Two'scomplement binary: ...1110011
(bitcount 30) => 4 ;Two'scomplement binary: ...0011110
(bitcount 30) => 4 ;Two'scomplement binary: ...1100010
(bitcount expt 2 100)) => 1
(bitcount ( (expt 2 100))) => 100
(bitcount ( (1+ (expt 2 100)))) => 1 (bitcount (
(integerlength i)
The number of bits needed to represent i, i.e.
ceiling (/ (log (if (negative? integer)
( integer)
(+ 1 integer)))
(log 2))) (
The result is always nonnegative. For nonnegative i, this is the number of bits needed to represent i in an unsigned binary representation. For all i, (+ 1 (integerlength i)) is the number of bits needed to represent i in a signed twoscomplement representation.
0) => 0
(integerlength 1) => 1
(integerlength 1) => 0
(integerlength 7) => 3
(integerlength 7) => 3
(integerlength 8) => 4
(integerlength 8) => 3 (integerlength 
(bitwiseif mask i j)
Merge the bitstrings i and j, with bitstring mask determining from which string to take each bit. That is, if the kth bit of mask is 1, then the kth bit of the result is the kth bit of i, otherwise the kth bit of j.
bitwiseif 3 1 8) => 9
(bitwiseif 3 8 1) => 0
(bitwiseif 1 1 2) => 3
(bitwiseif #b00111100 #b11110000 #b00001111) => #b00110011 (
(bitset? index i)
Is bit index set in bitstring i (where index is a nonnegative exact integer)?
Compatibility note: The R6RS analogue bitwisebitset? accepts its arguments in the opposite order.
1 1) => false
(bitset? 0 1) => true
(bitset? 3 10) => true
(bitset? 1000000 1) => true
(bitset? 2 6) => true
(bitset? 0 6) => false (bitset?
(copybit index i boolean)
Returns an integer the same as i except in the indexth bit, which is 1 if boolean is #t and 0 if boolean is #f.
Compatibility note: The R6RS analogue bitwisecopybit as originally documented has a completely different interface. (bitwisecopybit dest index source) replaces the index’th bit of dest with the index’th bit of source. It is equivalent to (bitfieldreplacesame dest source index (+ index 1)). However, an erratum made a silent breaking change to interpret the third argument as 0 for a false bit and 1 for a true bit. Some R6RS implementations applied this erratum but others did not.
0 0 #t) => #b1
(copybit 2 0 #t) => #b100
(copybit 2 #b1111 #f) => #b1011 (copybit
(bitswap index1 index2 i)
Returns an integer the same as i except that the index1th bit and the index2th bit have been exchanged.
0 2 4) => #b1 (bitswap
(anybitset? testbits i)
(everybitset? testbits i)
Determines if any/all of the bits set in bitstring testbits are set in bitstring i. I.e., returns (not (zero? (bitwiseand testbits i))) and (= testbits (bitwiseand testbits i))) respectively.
3 6) => #t
(anybitset? 3 12) => #f
(anybitset? 4 6) => #t
(everybitset? 7 6) => #f (everybitset?
(firstsetbit i)
Return the index of the first (smallest index) 1 bit in bitstring i. Return 1 if i contains no 1 bits (i.e., if i is zero).
1) => 0
(firstsetbit 2) => 1
(firstsetbit 0) => 1
(firstsetbit 40) => 3
(firstsetbit 28) => 2
(firstsetbit expt 2 99)) => 99
(firstsetbit (expt 2 99)) => 99 (firstsetbit (
(bitfield i start end)
Returns the field from i, shifted down to the leastsignificant position in the result.
#b1101101010 0 4) => #b1010
(bitfield #b1101101010 3 9) => #b101101
(bitfield #b1101101010 4 9) => #b10110
(bitfield #b1101101010 4 10) => #b110110
(bitfield 6 0 1) => 0
(bitfield 6 1 3) => 3
(bitfield 6 2 999) => 1
(bitfield #x100000000000000000000000000000000 128 129) => 1 (bitfield
(bitfieldany? i start end)
Returns true if any of the field’s bits are set in bitstring i, and false otherwise.
#b1001001 1 6) => #t
(bitfieldany? #b1000001 1 6) => #f (bitfieldany?
(bitfieldevery? i start end)
Returns false if any of the field’s bits are not set in bitstring i, and true otherwise.
#b1011110 1 5) => #t
(bitfieldevery? #b1011010 1 5) => #f (bitfieldevery?
(bitfieldclear i start end)
(bitfieldset i start end)
Returns i with the field’s bits set to all 0s/1s.
#b101010 1 4) => #b100000
(bitfieldclear #b101010 1 4) => #b101110 (bitfieldset
(bitfieldreplace dest source start end)
Returns dest with the field replaced by the leastsignificant endstart bits in source.
#b101010 #b010 1 4) => #b100100
(bitfieldreplace #b110 1 0 1) => #b111
(bitfieldreplace #b110 1 1 2) => #b110 (bitfieldreplace
(bitfieldreplacesame dest source start end)
Returns dest with its field replaced by the corresponding field in source.
#b1111 #b0000 1 3) => #b1001 (bitfieldreplacesame
(bitfieldrotate i count start end)
Returns i with the field cyclically permuted by count bits towards highorder.
Compatibility note: The R6RS analogue bitwiserotatebitfield uses the argument ordering i start end count.
#b110 0 0 10) => #b110
(bitfieldrotate #b110 0 0 256) => #b110
(bitfieldrotate #x100000000000000000000000000000000 1 0 129) => 1
(bitfieldrotate #b110 1 1 2) => #b110
(bitfieldrotate #b110 1 2 4) => #b1010
(bitfieldrotate #b0111 1 1 4) => #b1011 (bitfieldrotate
(bitfieldreverse i start end)
Returns i with the order of the bits in the field reversed.
6 1 3) => 6
(bitfieldreverse 6 1 4) => 12
(bitfieldreverse 1 0 32) => #x80000000
(bitfieldreverse 1 0 31) => #x40000000
(bitfieldreverse 1 0 30) => #x20000000
(bitfieldreverse #x140000000000000000000000000000000 0 129) => 5 (bitfieldreverse
(bits>list i [ len ])
(bits>vector i [ len ])
Returns a list/vector of len booleans corresponding to each bit of the nonnegative integer i, returning bit #0 as the first element, bit #1 as the second, and so on. #t is returned for each 1; #f for 0.
#b1110101)) => (#t #f #t #f #t #t #t)
(bits>list 3 5)) => (#t #t #f #f #f)
(bits>list 6 4)) => (#f #t #t #f)
(bits>list
#b1110101)) => #(#t #f #t #f #t #t #t) (bits>vector
(list>bits list)
(vector>bits vector)
Returns an integer formed from the booleans in list/vector, using the first element as bit #0, the second element as bit #1, and so on. It is an error if list/vector contains nonbooleans. A 1 bit is coded for each #t; a 0 bit for #f. Note that the result is never a negative integer.
#t #f #t #f #t #t #t)) => #b1110101
(list>bits '(#f #f #t #f #t #f #t #t #t)) => #b111010100
(list>bits '(#f #t #t)) => 6
(list>bits '(#f #t #t #f)) => 6
(list>bits '(#f #f #t #t)) => 12
(list>bits '(
#t #f #t #f #t #t #t)) => #b1110101
(vector>bits '#(#f #f #t #f #t #f #t #t #t)) => #b111010100
(vector>bits '#(#f #t #t)) => 6
(vector>bits '#(#f #t #t #f)) => 6
(vector>bits '#(#f #f #t #t)) => 12 (vector>bits '#(
For positive integers, bits>list and list>bits are inverses in the sense of equal?, and so are bits>vector and vector>bits.
(bits bool ...)
Returns the integer coded by the bool arguments. The first argument is bit #0, the second argument is bit #1, and so on. Note that the result is never a negative integer.
#t #f #t #f #t #t #t) => #b1110101
(bits #f #f #t #f #t #f #t #t #t) => #b111010100 (bits
(bitwisefold proc seed i)
For each bit b of i from bit #0 (inclusive) to bit (integerlength i) (exclusive), proc is called as (proc b r), where r is the current accumulated result. The initial value of r is seed, and the value returned by proc becomes the next accumulated result. When the last bit has been processed, the final accumulated result becomes the result of bitwisefold.
cons '() #b1010111) => (#t #f #t #f #t #t #t) (bitwisefold
(bitwiseforeach proc i)
Repeatedly applies proc to the bits of i starting with bit #0 (inclusive) and ending with bit (integerlength i) (exclusive). The values returned by proc are discarded. Returns an unspecified value.
let ((count 0))
(lambda (b) (if b (set! count (+ count 1))))
(bitwiseforeach (#b1010111)
count)
(bitwiseunfold stop? mapper successor seed)
Generates a nonnegative integer bit by bit, starting with bit 0. If the result of applying stop? to the current state (whose initial value is seed) is true, return the currently accumulated bits as an integer. Otherwise, apply mapper to the current state to obtain the next bit of the result by interpreting a true value as a 1 bit and a false value as a 0 bit. Then get a new state by applying successor to the current state, and repeat this algorithm.
lambda (i) (= i 10))
(bitwiseunfold (even?
lambda (i) (+ i 1))
(0)) => #b101010101
(makebitwisegenerator i)
Returns a SRFI 121 generator that generates all the bits of i starting with bit #0. Note that the generator is infinite.
let ((g (makebitwisegenerator #b110)))
(#f (g))
(test #t (g))
(test #t (g))
(test #f (g))) (test
(scheme box)
This library is based on SRFI111.
Boxes are objects with a single mutable state. Several Schemes have them, sometimes called cells. A constructor, predicate, accessor, and mutator are provided.
(box value)
Constructor. Returns a newly allocated box initialized to value.
(box? object)
Predicate. Returns #t
if object is a box, and
#f
otherwise.
(unbox box)
Accessor. Returns the current value of box.
(setbox! box value)
Mutator. Changes box to hold value. #
(scheme bytevector)
This is based on R6RS bytevectors library
(endianness <endianess symbol>)
syntax(nativeendianness)
Returns the endianness symbol associated implementation’s preferred
endianness (usually that of the underlying machine architecture). This
may be any <endianness symbol>
, including a symbol
other than big and little.
(bytevector? obj)
Returns #t if obj is a bytevector, otherwise returns #f.
(makebytevector k [fill])
Returns a newly allocated bytevector of K
bytes.
If the FILL
argument is missing, the initial contents of
the returned bytevector are unspecified.
If the FILL
argument is present, it must be an exact
integer object in the interval {128, … 255} that specifies the initial
value for the bytes of the bytevector: If FILL
is positive,
it is interpreted as an octet; if it is negative, it is interpreted as a
byte.
(bytevectorlength bytevector)
Returns, as an exact integer object, the number of bytes in bytevector.
(bytevector=? bytevector1 bytevector2)
Returns #t if bytevector1 and bytevector2 are equalthat is, if they have the same length and equal bytes at all valid indices. It returns #f otherwise.
(bytevectorfill! bytevector fill)
The fill argument is as in the description of the makebytevector procedure. The bytevectorfill! procedure stores fill in every element of bytevector and returns unspecified values. Analogous to vectorfill!.
(bytevectorcopy! source sourcestart target targetstart k)
(bytevectorcopy bytevector)
Returns a newly allocated copy of bytevector.
(bytevectoru8ref bytevector k)
The bytevectoru8ref procedure returns the byte at index k of bytevector, as an octet.
(bytevectors8ref bytevector k)
The bytevectors8ref procedure returns the byte at index k of bytevector, as a (signed) byte.
(bytevectoru8set! bytevector k octet)
The bytevectoru8set! procedure stores octet in element k of bytevector.
(bytevectors8set! bytevector k byte)
The bytevectors8set! procedure stores the two’scomplement representation of byte in element k of bytevector.
(bytevector>u8list bytevector)
The bytevector>u8list procedure returns a newly allocated list of the octets of bytevector in the same order.
(u8list>bytevector list)
The u8list>bytevector procedure returns a newly allocated bytevector whose elements are the elements of list list, in the same order. It is analogous to list>vector.
(bytevectoruintref bytevector k endianness size)
(bytevectorsintref bytevector k endianness size)
(bytevectoruintset! bytevector k n endianness size)
(bytevectorsintset! bytevector k n endianness size)
(bytevector>uintlist bytevector endianness size)
(bytevector>sintlist bytevector endianness sizee
(uintlist>bytevector list endianness size)
(sintlist>bytevector list endianness size)
(bytevectoru16ref bytevector k endianness)
(bytevectors16ref bytevector k endianness)
(bytevectoru16nativeref bytevector k)
(bytevectors16nativeref bytevector k)
(bytevectoru16set! bytevector k n endianness)
(bytevectors16set! bytevector k n endianness)
(bytevectoru16nativeset! bytevector k n)
(bytevectors16nativeset! bytevector k n)
(bytevectoru32ref bytevector k endianness)
(bytevectors32ref bytevector k endianness)
(bytevectoru32nativeref bytevector k)
(bytevectors32nativeref bytevector k)
(bytevectoru32set! bytevector k n endianness)
(bytevectors32set! bytevector k n endianness)
(bytevectoru32nativeset! bytevector k n)
(bytevectors32nativeset! bytevector k n)
(bytevectoru64ref bytevector k endianness)
(bytevectors64ref bytevector k endianness)
(bytevectoru64nativeref bytevector k)
(bytevectors64nativeref bytevector k)
(bytevectoru64set! bytevector k n endianness)
(bytevectors64set! bytevector k n endianness)
(bytevectoru64nativeset! bytevector k n)
(bytevectors64nativeset! bytevector k n)
(bytevectorieeesinglenativeref bytevector k)
(bytevectorieeesingleref bytevector k endianness)
(bytevectorieeedoublenativeref bytevector k)
(bytevectorieeedoubleref bytevector k endianness)
(bytevectorieeesinglenativeset! bytevector k x)
(bytevectorieeesingleset! bytevector k x endianness)
(bytevectorieeedoublenativeset! bytevector k x)
(bytevectorieeedoubleset! bytevector k x endianness)
(string>utf8 string)
(string>utf16 string)
(string>utf16 string endianness)
(string>utf32 string)
(string>utf32 string endianness)
(utf8>string bytevector)
(utf16>string bytevector endianness)
(utf16>string bytevector endianness endiannessmandatory)
(utf32>string bytevector endianness)
(utf32>string bytevector endianness endiannessmandatory)
(scheme caselambda)
(caselambda <clause1> ...)
syntaxEach clause is of the form
(<formals> <body>)
, where
<formals>
and <body>
have the same
syntax as in a lambda expression.
A caselambda expression evaluates to a procedure that accepts a
variable number of arguments and is lexically scoped in the same manner
as a procedure resulting from a lambda expression. When the procedure is
called, the first clause for which the arguments agree with
<formals>
is selected, where agreement is specified
as for the <formals>
of a lambda expression. The
variables of <formals>
are bound to fresh locations,
the values of the arguments are stored in those locations, the
<body>
is evaluated in the extended environment, and
the results of <body>
are returned as the results of
the procedure call.
It is an error for the arguments not to agree with the
<formals>
of any clause`.
Example:
define add1
(caselambda
(0))
((a) (add1 a + 1 a b))))
((a b) (
1) ;; => 2
(add1 1 2) ;; => 4 (add1
(scheme char)
(charalphabetic? char)
TODO
(charalphabetic? char)
TODO
(charci<=? char)
TODO
(charci<? char)
TODO
(charci=? char)
TODO
(charci>=? char)
TODO
(charci>? char)
TODO
(chardowncase char)
TODO
(charfoldcase char)
TODO
(charlowercase? char)
TODO
(charnumeric? char)
TODO
(charupcase char)
TODO
(charuppercase? char)
TODO
(charwhitespace? char)
TODO
(stringci<=? string1 string2 ...)
TODO
(stringci<? string1 string2 ...)
TODO
(stringci=? string1 string2 ...)
TODO
(stringci>=? string1 string2 ...)
TODO
(stringci>? string1 string2 ...)
TODO
(stringdowncase string)
TODO
(stringfoldcase string)
TODO
(stringupcase string)
TODO # (scheme charset)
This library is based on SRFI14.
The ability to efficiently represent and manipulate sets of characters is an unglamorous but very useful capability for textprocessing code – one that tends to pop up in the definitions of other libraries.
(charset? obj)
Is the object obj a character set?
(charset= cs1 ...)
Are the character sets equal?
Boundary cases:
=> true
(charset=) => true (charset= cs)
Rationale: transitive binary relations are generally extended to nary relations in Scheme, which enables clearer, more concise code to be written. While the zeroargument and oneargument cases will almost certainly not arise in firstorder uses of such relations, they may well arise in higherorder cases or macrogenerated code. E.g., consider
(apply charset= csetlist)
This is welldefined if the list is empty or a singleton list. Hence we extend these relations to any number of arguments. Implementors have reported actual uses of nary relations in higherorder cases allowing for fewer than two arguments. The way of Scheme is to handle the general case; we provide the fully general extension.
A counterargument to this extension is that R5RS’s transitive binary arithmetic relations (=, <, etc.) require at least two arguments, hence this decision is a break with the prior convention – although it is at least one that is backwardscompatible.
(charset<= cs1 ...)
Returns true if every character set csi is a subset of character set csi+1.
Boundary cases:
=> true
(charset<=) => true (charset<= cs)
Rationale: See charset= for discussion of zero and oneargument applications. Consider testing a list of charsets for monotonicity with
(apply charset<= csetlist)
(charsethash cs [bound])
Compute a hash value for the character set cs. Bound is a nonnegative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).
If bound is either zero or not given, the implementation may use an implementationspecific default value, chosen to be as large as is efficiently practical. For instance, the default range might be chosen for a given implementation to map all strings into the range of integers that can be represented with a single machine word.
Invariant:
=> (= (charsethash cs1 b) (charsethash cs2 b)) (charset= cs1 cs2)
A legal but nonetheless discouraged implementation:
define (charsethash cs . maybebound) 1) (
Rationale: allowing the user to specify an explicit bound simplifies user code by removing the mod operation that typically accompanies every hash computation, and also may allow the implementation of the hash function to exploit a reduced range to efficiently compute the hash value. E.g., for small bounds, the hash function may be computed in a fashion such that intermediate values never overflow into bignum integers, allowing the implementor to provide a fixnumspecific “fast path” for computing the common cases very rapidly.
(charsetcursor cset)
(charsetref cset cursor)
(charsetcursornext cset cursor)
(endofcharset? cursor)
Cursors are a lowlevel facility for iterating over the characters in a set. A cursor is a value that indexes a character in a char set. charsetcursor produces a new cursor for a given char set. The set element indexed by the cursor is fetched with charsetref. A cursor index is incremented with charsetcursornext; in this way, code can step through every character in a char set. Stepping a cursor “past the end” of a char set produces a cursor that answers true to endofcharset?. It is an error to pass such a cursor to charsetref or to charsetcursornext.
A cursor value may not be used in conjunction with a different character set; if it is passed to charsetref or charsetcursornext with a character set other than the one used to create it, the results and effects are undefined.
Cursor values are not necessarily distinct from other types. They may be integers, linked lists, records, procedures or other values. This license is granted to allow cursors to be very “lightweight” values suitable for tight iteration, even in fairly simple implementations.
Note that these primitives are necessary to export an iteration facility for char sets to loop macros.
Example:
define cs (charset #\G #\a #\T #\e #\c #\h))
(
;; Collect elts of CS into a list.
let lp ((cur (charsetcursor cs)) (ans '()))
(if (endofcharset? cur) ans
(
(lp (charsetcursornext cs cur)cons (charsetref cs cur) ans))))
(=> (#\G #\T #\a #\c #\e #\h)
;; Equivalently, using a list unfold (from SRFI 1):
(unfoldright endofcharset?
(curry charsetref cs)
(curry charsetcursornext cs)
(charsetcursor cs))=> (#\G #\T #\a #\c #\e #\h)
Rationale: Note that the cursor API’s four functions “fit” the functional protocol used by the unfolders provided by the list, string and charset SRFIs (see the example above). By way of contrast, here is a simpler, twofunction API that was rejected for failing this criterion. Besides charsetcursor, it provided a single function that mapped a cursor and a character set to two values, the indexed character and the next cursor. If the cursor had exhausted the character set, then this function returned false instead of the character value, and another endofcharset cursor. In this way, the other three functions of the current API were combined together.
(charsetfold kons knil cs)
This is the fundamental iterator for character sets. Applies the function kons across the character set cs using initial state value knil. That is, if cs is the empty set, the procedure returns knil. Otherwise, some element c of cs is chosen; let cs’ be the remaining, unchosen characters. The procedure returns
(charsetfold kons (kons c knil) cs')
Examples:
;; CHARSETMEMBERS
lambda (cs) (charsetfold cons '() cs))
(
;; CHARSETSIZE
lambda (cs) (charsetfold (lambda (c i) (+ i 1)) 0 cs))
(
;; How many vowels in the char set?
lambda (cs)
(lambda (c i) (if (vowel? c) (+ i 1) i))
(charsetfold (0 cs))
(charsetunfold f p g seed [basecs])
(charsetunfold! f p g seed basecs)
This is a fundamental constructor for charsets.
G is used to generate a series of “seed” values from the initial seed: seed, (g seed), (g2 seed), (g3 seed), …
P tells us when to stop – when it returns true when applied to one of these seed values.
F maps each seed value to a character. These characters are added to the base character set basecs to form the result; basecs defaults to the empty set. charsetunfold! adds the characters to basecs in a linearupdate – it is allowed, but not required, to sideeffect and use basecs’s storage to construct the result.
More precisely, the following definitions hold, ignoring the optionalargument issues:
define (charsetunfold p f g seed basecs)
(
(charsetunfold! p f g seed (charsetcopy basecs)))
define (charsetunfold! p f g seed basecs)
(let lp ((seed seed) (cs basecs))
(if (p seed) cs ; P says we are done.
(; Loop on (G SEED).
(lp (g seed) ; Add (F SEED) to set.
(charsetadjoin! cs (f seed))))))
(Note that the actual implementation may be more efficient.)
Examples:
= (charsetunfold eofobject? values
(port>charset p) lambda (x) (readchar p))
(readchar p))
(
= (charsetunfold null? car cdr lis) (list>charset lis)
(charsetforeach proc cs)
Apply procedure proc to each character in the character set cs. Note that the order in which proc is applied to the characters in the set is not specified, and may even change from one procedure application to another.
Nothing at all is specified about the value returned by this procedure; it is not even required to be consistent from call to call. It is simply required to be a value (or values) that may be passed to a command continuation, e.g. as the value of an expression appearing as a nonterminal subform of a begin expression. Note that in R5RS, this restricts the procedure to returning a single value; nonR5RS systems may not even provide this restriction. charsetmap proc cs > charset proc is a char>char procedure. Apply it to all the characters in the charset cs, and collect the results into a new character set.
Essentially lifts proc from a char>char procedure to a charset > charset procedure.
Example:
chardowncase cset) (charsetmap
(charsetcopy cs)
Returns a copy of the character set cs. “Copy” means that if either the input parameter or the result value of this procedure is passed to one of the linearupdate procedures described below, the other character set is guaranteed not to be altered.
A system that provides purefunctional implementations of the linearoperator suite could implement this procedure as the identity function – so copies are not guaranteed to be distinct by eq?.
(charset char1 ...)
Return a character set containing the given characters.
(list>charset charlist [basecs])
(list>charset! charlist basecs)
Return a character set containing the characters in the list of characters charlist.
If character set basecs is provided, the characters from charlist are added to it. list>charset! is allowed, but not required, to sideeffect and reuse the storage in basecs; list>charset produces a fresh character set.
(string>charset s [basecs])
(string>charset! s basecs)
Return a character set containing the characters in the string s.
If character set basecs is provided, the characters from s are added to it. string>charset! is allowed, but not required, to sideeffect and reuse the storage in basecs; string>charset produces a fresh character set.
(charsetfilter pred cs [basecs])
(charsetfilter! pred cs basecs)
Returns a character set containing every character c in cs such that (pred c) returns true.
If character set basecs is provided, the characters specified by pred are added to it. charsetfilter! is allowed, but not required, to sideeffect and reuse the storage in basecs; charsetfilter produces a fresh character set.
An implementation may not save away a reference to pred and invoke it after charsetfilter or charsetfilter! returns – that is, “lazy,” ondemand implementations are not allowed, as pred may have external dependencies on mutable data or have other sideeffects.
Rationale: This procedure provides a means of converting a character predicate into its equivalent character set; the cs parameter allows the programmer to bound the predicate’s domain. Programmers should be aware that filtering a character set such as charset:full could be a very expensive operation in an implementation that provided an extremely large character type, such as 32bit Unicode. An earlier draft of this library provided a simple predicate>charset procedure, which was rejected in favor of charsetfilter for this reason.
(ucsrange>charset lower upper [error? basecs])
(ucsrange>charset! lower upper error? basecs)
Lower and upper are exact nonnegative integers; lower <= upper.
Returns a character set containing every character whose ISO/IEC 10646 UCS4 code lies in the halfopen range [lower,upper).
If the requested range includes unassigned UCS values, these are silently ignored (the current UCS specification has “holes” in the space of assigned codes).
If the requested range includes “private” or “user space” codes, these are handled in an implementationspecific manner; however, a UCS or Unicodebased Scheme implementation should pass them through transparently.
If any code from the requested range specifies a valid, assigned UCS character that has no corresponding representative in the implementation’s character type, then (1) an error is raised if error? is true, and (2) the code is ignored if error? is false (the default). This might happen, for example, if the implementation uses ASCII characters, and the requested range includes nonASCII characters.
If character set basecs is provided, the characters specified by the range are added to it. ucsrange>charset! is allowed, but not required, to sideeffect and reuse the storage in basecs; ucsrange>charset produces a fresh character set.
Note that ASCII codes are a subset of the Latin1 codes, which are in turn a subset of the 16bit Unicode codes, which are themselves a subset of the 32bit UCS4 codes. We commit to a specific encoding in this routine, regardless of the underlying representation of characters, so that client code using this library will be portable. I.e., a conformant Scheme implementation may use EBCDIC or SHIFTJIS to encode characters; it must simply map the UCS characters from the given range into the native representation when possible, and report errors when not possible.
(>charset x)
Coerces x into a charset. X may be a string, character or charset. A string is converted to the set of its constituent characters; a character is converted to a singleton set; a charset is returned asis. This procedure is intended for use by other procedures that want to provide “userfriendly,” widespectrum interfaces to their clients.
(charsetsize cs)
Returns the number of elements in character set cs.
(charsetcount pred cs)
Apply pred to the chars of character set cs, and return the number of chars that caused the predicate to return true.
(charset>list cs)
This procedure returns a list of the members of character set cs. The order in which cs’s characters appear in the list is not defined, and may be different from one call to another.
(charset>string cs)
This procedure returns a string containing the members of character set cs. The order in which cs’s characters appear in the string is not defined, and may be different from one call to another.
(charsetcontains? cs char)
This procedure tests char for membership in character set cs.
The MIT Scheme characterset package called this procedure charsetmember?, but the argument order isn’t consistent with the name.
(charsetevery pred cs)
(charsetany pred cs)
The charsetevery procedure returns true if predicate pred returns true of every character in the character set cs. Likewise, charsetany applies pred to every character in character set cs, and returns the first true value it finds. If no character produces a true value, it returns false. The order in which these procedures sequence through the elements of cs is not specified.
Note that if you need to determine the actual character on which a predicate returns true, use charsetany and arrange for the predicate to return the character parameter as its true value, e.g.
lambda (c) (and (charuppercase? c) c))
(charsetany ( cs)
(charsetadjoin cs char1 ...)
(charsetdelete cs char1 ...)
Add/delete the chari characters to/from character set cs.
(charsetadjoin! cs char1 ...)
(charsetdelete! cs char1 ...)
Linearupdate variants. These procedures are allowed, but not required, to sideeffect their first parameter.
(charsetcomplement cs)
(charsetunion cs1 ...)
(charsetintersection cs1 ...)
(charsetdifference cs1 cs2 ...)
(charsetxor cs1 ...)
(charsetdiff+intersection cs1 cs2 ...)
These procedures implement set complement, union, intersection, difference, and exclusiveor for character sets. The union, intersection and xor operations are nary. The difference function is also nary, associates to the left (that is, it computes the difference between its first argument and the union of all the other arguments), and requires at least one argument.
Boundary cases:
=> charset:empty
(charsetunion) => charset:full
(charsetintersection) => charset:empty
(charsetxor) => cs (charsetdifference cs)
charsetdiff+intersection returns both the difference and the intersection of the arguments – it partitions its first parameter. It is equivalent to
values (charsetdifference cs1 cs2 ...)
(...))) (charsetintersection cs1 (charsetunion cs2
but can be implemented more efficiently.
Programmers should be aware that charsetcomplement could potentially be a very expensive operation in Scheme implementations that provide a very large character type, such as 32bit Unicode. If this is a possibility, sets can be complimented with respect to a smaller universe using charsetdifference.
(charsetcomplement! cs)
(charsetunion! cs1 cs2 ...)
(charsetintersection! cs1 cs2 ...)
(charsetdifference! cs1 cs2 ...)
(charsetxor! cs1 cs2 ...)
(charsetdiff+intersection! cs1 cs2 cs3 ...)
These are linearupdate variants of the setalgebra functions. They are allowed, but not required, to sideeffect their first (required) parameter.
charsetdiff+intersection! is allowed to sideeffect both of its two required parameters, cs1 and cs2.
charset:lowercase
Lowercase letters
charset:uppercase
Uppercase letters
charset:titlecase
Titlecase letters
charset:letter
Letters
charset:digit
Digits
charset:letter+digit
Letters and digits
charset:graphic
Printing characters except spaces
charset:printing
Printing characters including spaces
charset:whitespace
Whitespace characters
charset:isocontrol
The ISO control characters
charset:punctuation
Punctuation characters
charset:symbol
Symbol characters
charset:hexdigit
A hexadecimal digit: 09, AF, af
charset:blank
Blank characters – horizontal whitespace
charset:ascii
All characters in the ASCII set.
charset:empty
Empty set
charset:full
All characters # (scheme comparator)
This library is based on SRFI128.
A comparator is an object of a disjoint type. It is a bundle of procedures that are useful for comparing two objects either for equality or for ordering. There are four procedures in the bundle:
The type test predicate returns #t if its argument has the correct type to be passed as an argument to the other three procedures, and #f otherwise.
The equality predicate returns #t if the two objects are the same in the sense of the comparator, and #f otherwise. It is the programmer’s responsibility to ensure that it is reflexive, symmetric, transitive, and can handle any arguments that satisfy the type test predicate.
The comparison procedure returns 1, 0, or 1 if the first object precedes the second, is equal to the second, or follows the second, respectively, in a total order defined by the comparator. It is the programmer’s responsibility to ensure that it is reflexive, weakly antisymmetric, transitive, can handle any arguments that satisfy the type test predicate, and returns 0 iff the equality predicate returns #t.
The hash function takes one argument, and returns an exact nonnegative integer. It is the programmer’s responsibility to ensure that it can handle any argument that satisfies the type test predicate, and that it returns the same value on two objects if the equality predicate says they are the same (but not necessarily the converse).
It is also the programmer’s responsibility to ensure that all four procedures provide the same result whenever they are applied to the same object(s) (in the sense of eqv?), unless the object(s) have been mutated since the last invocation. In particular, they must not depend in any way on memory addresses in implementations where the garbage collector can move objects in memory.
B> Limitations: The comparator objects defined in this library are not B> applicable to circular structure or to NaNs or objects containing B> them. Attempts to pass any such objects to any procedure defined B> here, or to any procedure that is part of a comparator defined B> here, is an error except as otherwise noted.
(comparator? obj)
Returns #t if obj is a comparator, and #f otherwise.
(comparatorcomparisonprocedure? comparator)
Returns #t if comparator has a supplied comparison procedure, and #f otherwise.
(comparatorhashfunction? comparator)
Returns #t if comparator has a supplied hash function, and #f otherwise.
booleancomparator
Compares booleans using the total order #f < #t.
charcomparator
Compares characters using the total order implied by char<?. On R6RS and R7RS systems, this is Unicode codepoint order.
charcicomparator
Compares characters using the total order implied by charci<? On R6RS and R7RS systems, this is Unicode codepoint order after the characters have been folded to lower case.
stringcomparator
Compares strings using the total order implied by string<?. Note that this order is implementationdependent.
stringcicomparator
Compares strings using the total order implied by stringci<?. Note that this order is implementationdependent.
symbolcomparator
Compares symbols using the total order implied by applying symbol>string to the symbols and comparing them using the total order implied by string<?. It is not a requirement that the hash function of symbolcomparator be consistent with the hash function of stringcomparator, however.
exactintegercomparator
integercomparator
rationalcomparator
realcomparator
complexcomparator
numbercomparator
These comparators compare exact integers, integers, rational numbers, real numbers, complex numbers, and any numbers using the total order implied by <. They must be compatible with the R5RS numerical tower in the following sense: If S is a subtype of the numerical type T and the two objects are members of S , then the equality predicate and comparison procedures (but not necessarily the hash function) of Scomparator and Tcomparator compute the same results on those objects.
Since nonreal numbers cannot be compared with <, the following leastsurprising ordering is defined: If the real parts are < or >, so are the numbers; otherwise, the numbers are ordered by their imaginary parts. This can still produce surprising results if one real part is exact and the other is inexact.
paircomparator
This comparator compares pairs using defaultcomparator (see below) on their cars. If the cars are not equal, that value is returned. If they are equal, defaultcomparator is used on their cdrs and that value is returned.
listcomparator
This comparator compares lists lexicographically, as follows:
The empty list compares equal to itself.
The empty list compares less than any nonempty list.
Two nonempty lists are compared by comparing their cars. If the cars are not equal when compared using defaultcomparator (see below), then the result is the result of that comparison. Otherwise, the cdrs are compared using listcomparator.
vectorcomparator
bytevectorcomparator
These comparators compare vectors and bytevectors by comparing their lengths. A shorter argument is always less than a longer one. If the lengths are equal, then each element is compared in turn using defaultcomparator (see below) until a pair of unequal elements is found, in which case the result is the result of that comparison. If all elements are equal, the arguments are equal.
If the implementation does not support bytevectors, bytevectorcomparator has a type testing procedure that always returns #f.
defaultcomparator
This is a comparator that accepts any two Scheme values (with the exceptions listed in the Limitations section) and orders them in some implementationdefined way, subject to the following conditions:
The following ordering between types must hold: the empty list precedes pairs, which precede booleans, which precede characters, which precede strings, which precede symbols, which precede numbers, which precede vectors, which precede bytevectors, which precede all other objects.
When applied to pairs, booleans, characters, strings, symbols, numbers, vectors, or bytevectors, its behavior must be the same as paircomparator, booleancomparator, charactercomparator, stringcomparator, symbolcomparator, numbercomparator, vectorcomparator, and bytevectorcomparator respectively. The same should be true when applied to an object or objects of a type for which a standard comparator is defined elsewhere.
Given disjoint types a and b, one of three conditions must hold:
All objects of type a compare less than all objects of type b.
All objects of type a compare greater than all objects of type b.
All objects of either type a or type b compare equal to each other. This is not permitted for any of the standard types mentioned above.
(makecomparator typetest equality compare hash)
Returns a comparator which bundles the typetest, equality, compare, and hash procedures provided. As a convenience, the following additional values are accepted:
If typetest is #t, a typetest procedure that accepts any arguments is provided.
If equality is #t, an equality predicate is provided that returns #t iff compare returns 0.
If compare or hash is #f, a procedure is provided that signals an error on application. The predicates comparatorcomparisonprocedure? and/or comparatorhashfunction?, respectively, will return #f in these cases.
(makeinexactrealcomparator epsilon rounding nanhandling)
Returns a comparator that compares inexact real numbers including NaNs as follows: if after rounding to the nearest epsilon they are the same, they compare equal; otherwise they compare as specified by <. The direction of rounding is specified by the rounding argument, which is either a procedure accepting two arguments (the number and epsilon, or else one of the symbols floor, ceiling, truncate, or round.
The argument nanhandling specifies how to compare NaN arguments to nonNaN arguments. If it is a procedure, the procedure is invoked on the other argument if either argument is a NaN. If it is the symbol min, NaN values precede all other values; if it is the symbol max, they follow all other values, and if it is the symbol error, an error is signaled if a NaN value is compared. If both arguments are NaNs, however, they always compare as equal.
(makelistcomparator elementcomparator)
(makevectorcomparator elementcomparator)
(makebytevectorcomparator elementcomparator)
These procedures return comparators which compare two lists, vectors, or bytevectors in the same way as listcomparator, vectorcomparator, and bytevectorcomparator respectively, but using elementcomparator rather than defaultcomparator.
If the implementation does not support bytevectors, the result of invoking makebytevectorcomparator is a comparator whose type testing procedure always returns #f.
(makelistwisecomparator typetest elementcomparator empty? head tail)
Returns a comparator which compares two objects that satisfy typetest as if they were lists, using the empty? procedure to determine if an object is empty, and the head and tail procedures to access particular elements.
(makevectorwisecomparator typetest elementcomparator length ref)
Returns a comparator which compares two objects that satisfy typetest as if they were vectors, using the length procedure to determine the length of the object, and the ref procedure to access a particular element.
(makecarcomparator comparator)
Returns a comparator that compares pairs on their cars alone using comparator.
(makecdrcomparator comparator)
Returns a comparator that compares pairs on their cdrs alone using comparator.
(makepaircomparator carcomparator cdrcomparator)
Returns a comparator that compares pairs first on their cars using carcomparator. If the cars are equal, it compares the cdrs using cdrcomparator.
(makeimproperlistcomparator elementcomparator)
Returns a comparator that compares arbitrary objects as follows: the empty list precedes all pairs, which precede all other objects. Pairs are compared as if with (makepaircomparator elementcomparator elementcomparator). All other objects are compared using elementcomparator.
(makeselectingcomparator comparator1 comparator2 ...)
Returns a comparator whose procedures make use of the comparators as follows:
The type test predicate passes its argument to the type test predicates of comparators in the sequence given. If any of them returns #t, so does the type test predicate; otherwise, it returns #f.
The arguments of the equality, compare, and hash functions are passed to the type test predicate of each comparator in sequence. The first comparator whose type test predicate is satisfied on all the arguments is used when comparing those arguments. All other comparators are ignored. If no type test predicate is satisfied, an error is signaled.
(makerefiningcomparator comparator1 comparator2 ...)
Returns a comparator that makes use of the comparators in the same way as makeselectingcomparator, except that its procedures can look past the first comparator whose type test predicate is satisfied. If the comparison procedure of that comparator returns zero, then the next comparator whose type test predicate is satisfied is tried in place of it until one returns a nonzero value. If there are no more such comparators, then the comparison procedure returns zero. The equality predicate is defined in the same way. If no type test predicate is satisfied, an error is signaled.
The hash function of the result returns a value which depends, in an implementationdefined way, on the results of invoking the hash functions of the comparators whose type test predicates are satisfied on its argument. In particular, it may depend solely on the first or last such hash function. If no type test predicate is satisfied, an error is signaled.
This procedure is analogous to the expression type refinecompare from SRFI 67.
(makereversecomparator comparator)
Returns a comparator that behaves like comparator, except that the compare procedure returns 1, 0, and 1 instead of 1, 0, and 1 respectively. This allows ordering in reverse.
(makedebugcomparator comparator)
Returns a comparator that behaves exactly like comparator, except that whenever any of its procedures are invoked, it verifies all the programmer responsibilities (except stability), and an error is signaled if any of them are violated. Because it requires three arguments, transitivity is not tested on the first call to a debug comparator; it is tested on all future calls using an arbitrarily chosen argument from the previous invocation. Note that this may cause unexpected storage leaks.
eqcomparator
eqvcomparator
equalcomparator
The equality predicates of these comparators are eq?, eqv?, and equal? respectively. When their comparison procedures are applied to nonequal objects, their behavior is implementationdefined. The type test predicates always return #t.
These comparators accept circular structure (in the case of equalcomparator, provided the implementation’s equal does so) and NaNs.
(comparatortypetestprocedure comparator)
Returns the type test predicate of comparator.
(comparatorequalitypredicate comparator)
Returns the equality predicate of comparator.
(comparatorcomparisonprocedure comparator)
Returns the comparison procedure of comparator.
(comparatorhashfunction comparator)
Returns the hash function of comparator.
(comparatortesttype comparator obj)
Invokes the type test predicate of comparator on obj and returns what it returns.
(comparatorchecktype comparator obj)
Invokes the type test predicate of comparator on obj and returns true if it returns true and signals an error otherwise.
(comparatorequal? comparator obj1 obj2)
Invokes the equality predicate of comparator on obj1 and obj2 and returns what it returns.
(comparatorcompare comparator obj1 obj2)
Invokes the comparison procedure of comparator on obj1 and obj2 and returns what it returns.
(comparatorhash comparator obj)
Invokes the hash function of comparator on obj and returns what it returns.
(makecomparison< ltpred)
(makecomparison> gtpred)
(makecomparison<= lepred)
(makecomparison>= gepred)
(makecomparison=/< eqpred ltpred)
(makecomparison=/> eqpred gtpred)
These procedures return a comparison procedure, given a lessthan predicate, a greaterthan predicate, a lessthanorequalto predicate, a greaterthanorequalto predicate, or the combination of an equality predicate and either a lessthan or a greaterthan predicate.
(if3 <expr> <less> <equal> <greater>)
The expression <expr>
is evaluated; it will
typically, but not necessarily, be a call on a comparison procedure. If
the result is 1, <less>
is evaluated and its
value(s) are returned; if the result is 0, <equal>
is
evaluated and its value(s) are returned; if the result is 1,
<greater>
is evaluated and its value(s) are returned.
Otherwise an error is signaled.
(if=? <expr> <consequent> [ <alternate> ])
(if<? <expr> <consequent> [ <alternate> ])
(if>? <expr> <consequent> [ <alternate> ])
(if<=? <expr> <consequent> [ <alternate> ])
(if>=? <expr> <consequent> [ <alternate> ])
(ifnot=? <expr> <consequent> [ <alternate> ])
The expression <expr>
is evaluated; it will
typically, but not necessarily, be a call on a comparison procedure. It
is an error if its value is not 1, 0, or 1. If the value is consistent
with the specified relation, <consequent>
is
evaluated and its value(s) are returned. Otherwise, if
<alternate>
is present, it is evaluated and its
value(s) are returned; if it is absent, an unspecified value is
returned.
(=? comparator object1 object2 object3 ...)
(<? comparator object1 object2 object3 ...)
(>? comparator object1 object2 object3 ...)
(<=? comparator object1 object2 object3 ...)
(>=? comparator object1 object2 object3 ...)
These procedures are analogous to the number, character, and string comparison predicates of Scheme. They allow the convenient use of comparators in situations where the expression types are not usable. They are also analogous to the similarly named procedures SRFI 67, but handle arbitrary numbers of arguments, which in SRFI 67 requires the use of the variants whose names begin with chain.
These procedures apply the comparison procedure of comparator to the objects as follows. If the specified relation returns #t for all objecti and objectj where n is the number of objects and 1 <= i < j <= n, then the procedures return #t, but otherwise #f.
The order in which the values are compared is unspecified. Because the relations are transitive, it suffices to compare each object with its successor.
(make=? comparator)
(make<? comparator)
(make>? comparator)
(make<=? comparator)
(make>=? comparator)
These procedures return predicates which, when applied to two or more arguments, return #t if comparing obj1 and obj2 using the equality or comparison procedures of comparator shows that the objects bear the specified relation to one another. Such predicates can be used in contexts that do not understand or expect comparators.
(inopeninterval? [comparator] obj1 obj2 obj3)
Return #t if obj1 is less than obj2, which is less thanobj3, and #f otherwise.
(inclosedinterval? [comparator] obj1 obj2 obj3)
Returns #t if obj1 is less than or equal to obj2, which is less than or equal to obj3, and #f otherwise.
(inopenclosedinterval? [comparator] obj1 obj2 obj3)
Returns #t if obj1 is less than obj2, which is less than or equal to obj3, and #f otherwise.
(inclosedopeninterval? [comparator] obj1 obj2 obj3)
Returns #t if obj1 is less than or equal to obj2, which is less than obj3, and #f otherwise.
(comparatormin comparator object1 object2 ...)
(comparatormax comparator object1 object2 ...)
These procedures are analogous to min and max respectively. They
apply the comparison procedure of comparator to the objects to find and
return a minimal (or maximal) object. The order in which the values are
compared is unspecified. # (scheme complex)
angle
TODO
imagpart
TODO
magnitude
TODO
makepolar
TODO
makerectangular
TODO
realpart
TODO # (scheme cxr)
Exports the following procedure which are the compositions of from
three to four car
and cdr
operations. For
example caddar
could be defined:
define caddar
(lambda (x) (car (cdr (cdr (car x)))))) (
Here is the full list:
caaaar
caaadr
caaar
caadar
caaddr
caadr
cadaar
cadadr
cadar
caddar
cadddr
caddr
cdaaar
cdaadr
cdaar
cdadar
cdaddr
cdadr
cddaar
cddadr
cddar
cdddar
cddddr
cdddr
# (scheme division)
This is based on SRFI141.
This SRFI provides a fairly complete set of integral division and remainder operators.
(floor/ numerator denominator)
(floorquotient numerator denominator)
(floorremainder numerator denominator)
q = floor(n/d)
Thus r is negative iff d is negative.
(ceiling/ numerator denominator)
(ceilingquotient numerator denominator)
(ceilingremainder numerator denominator)
q = ceiling(n/d)
Thus r is negative iff d is nonnegative.
If denominator is the number of units in a block, and
(truncate/ numerator denominator)
(truncatequotient numerator denominator)
(truncateremainder numerator denominator)
q = truncate(n/d)
Thus r is negative iff n is negative. However, by any nonunit denominator, the quotient of +1, 0, or 1 is 0; that is, three contiguous numerators by a common denominator share a common quotient. Of the other division operator pairs, only the round pair exhibits this property.
(round/ numerator denominator)
(roundquotient numerator denominator)
(roundremainder numerator denominator)
q = round(n/d)
The round function rounds to the nearest integer, breaking ties by choosing the nearest even integer. Nothing general can be said about the sign of r. Like the truncate operator pair, the quotient of +1, 0, or 1 by any nonunit denominator is 0, so that three contiguous numerators by a common denominator share a common quotient.
(euclidean/ numerator denominator)
(euclideanquotient numerator denominator)
(euclideanremainder numerator denominator)
If d > 0, q = floor(n/d); if d < 0, q = ceiling(n/d).
This division operator pair satisfies the stronger property
0 <= r < d,
used often in mathematics. Thus, for example, (euclideanremainder numerator denominator) is always a valid index into a vector whose length is at least the absolute value of denominator. This division operator pair is so named because it is the subject of the Euclidean division algorithm.
(balanced/ numerator denominator)
(balancedquotient numerator denominator)
(balancedremainder numerator denominator)
This division operator pair satisfies the property
d/2 <= r < d/2.
When d is a power of 2, say 2k for some k, this reduces to
2(k  1) <= r < 2(k  1).
Computer scientists will immediately recognize this as the interval
of integers representable in two’scomplement with k bits. #
(scheme ephemeron)
This library is based on SRFI124, that is itself based on the MIT Scheme Reference Manual.
An ephemeron is an object with two components called its key and its datum. It differs from an ordinary pair as follows: if the garbage collector (GC) can prove that there are no references to the key except from the ephemeron itself and possibly from the datum, then it is free to break the ephemeron, dropping its reference to both key and datum. In other words, an ephemeron can be broken when nobody else cares about its key. Ephemerons can be used to construct weak vectors or lists and (possibly in combination with finalizers) weak hash tables.
(ephemeron? obj)
Returns #t if object is an ephemeron; otherwise returns #f.
(makeephemeron key datum)
Returns a newly allocated ephemeron, with components key and datum. Note that if key and datum are the same in the sense of eq?, the ephemeron is effectively a weak reference to the object.
(ephemeronbroken? ephemeron)
Returns #t if ephemeron has been broken; otherwise returns #f.
This procedure must be used with care. If it returns #f, that guarantees only that prior evaluations of ephemeronkey or ephemerondatum yielded the key or datum that was stored in ephemeron. However, it makes no guarantees about subsequent calls to ephemeronkey or ephemerondatum, because the GC may run and break the ephemeron immediately after ephemeronbroken? returns. Thus, the correct idiom to fetch an ephemeron’s key and datum and use them if the ephemeron is not broken is:
let ((key (ephemeronkey ephemeron))
(
(datum (ephemerondatum ephemeron)))if (ephemeronbroken? ephemeron)
(... broken case ...
... code using key and datum ...))
(ephemeronkey ephemeron)
(ephemeronvalue ephemeron)
These return the key or datum component, respectively, of ephemeron. If ephemeron has been broken, these operations return #f, but they can also return #f if that is what was stored as the key or datum.
(referencebarrier key)
This procedure is optional.
This procedure ensures that the garbage collector does not break an
ephemeron containing an unreferenced key before a certain point in a
program. The program can invoke a reference barrier on the key by
calling this procedure, which guarantees that even if the program does
not use the key, it will be considered strongly reachable until after
referencebarrier returns. # (scheme eval)
(environment list1 ...)
This procedure returns a specifier for the environment that results by starting with an empty environment and then importing each list, considered as an import set, into it. The bindings of the environment represented by the specifier are immutable, as is the environment itself.
(eval exprordef environmentspecifier)
If exprordef
is an expression, it is evaluated in the
specified environment and its values are returned. If it is a
definition, the specified identifier(s) are defined in the specified
environment, provided the environment is not immutable. Implementations
may extend eval
to allow other objects. #
(scheme file)
(callwithinputfile)
TODO
(callwithoutputfile)
TODO
(deletefile)
TODO
(fileexists?)
TODO
(openinputfile)
TODO
(openoutputfile)
TODO
(withinputfromfile)
TODO
(withoutputtofile)
TODO
(openbinaryinputfile)
TODO
(openbinaryoutputfile)
TODO # (scheme fixnum)
This is based on SRFI143.
This library describes arithmetic procedures applicable to a limited range of exact integers only. These procedures are semantically similar to the corresponding genericarithmetic procedures, but allow more efficient implementations.
fxwidth
Bound to the value w that specifies the implementationdefined range. (R6RS fixnumwidth is a procedure that always returns this value.)
fxgreatest
Bound to the value 2w11, the largest representable fixnum. (R6RS greatestfixnum is a procedure that always returns this value.)
fxleast
Bound to the value 2w1, the smallest representable fixnum. (R6RS leastfixnum is a procedure that always returns this value.)
(fixnum? obj)
Returns #t if obj is an exact integer within the fixnum range, and #f otherwise.
(fx=? i ...)
Semantically equivalent to =.
(fx<? i ...)
Semantically equivalent to <.
(fx>? i ...)
Semantically equivalent to >.
(fx<=? i ...)
Semantically equivalent to <=.
(fx>=? i ...)
Semantically equivalent to >=.
(fxzero? i)
Semantically equivalent to zero?.
(fxpositive? i)
Semantically equivalent to positive?.
(fxnegative? i)
Semantically equivalent to negative?.
(fxodd? i)
Semantically equivalent to odd?.
(fxeven? i)
Semantically equivalent to even?.
(fxmax i j ...)
Semantically equivalent to max.
(fxmin i j ...)
Semantically equivalent to min.
(fx+ i j)
Semantically equivalent to +, but accepts exactly two arguments.
(fx i j)
Semantically equivalent to , but accepts exactly two arguments.
(fxneg i)
Semantically equivalent to , but accepts exactly one argument.
(fx* i j)
Semantically equivalent to *, but accepts exactly two arguments.
(fxquotient i j)
Semantically equivalent to quotient.
(fxremainder i j)
Semantically equivalent to remainder.
(fxabs i)
Semantically equivalent to abs. In accordance with the fixnum rule, has undefined results when applied to fxleast.
(fxsquare i)
Semantically equivalent to square.
(fxsqrt i)
Semantically equivalent to exactintegersqrt (not sqrt).
(fx+/carry i j k)
Returns the two fixnum results of the following computation:
let*values (((s) (+ i j k))
(expt 2 fxwidth))))
((q r) (balanced/ s (values r q))
(
fx/carry i j k) (
Returns the two fixnum results of the following computation:
let*values (((d) ( i j k))
(expt 2 fxwidth))))
((q r) (balanced/ d (values r q))
(
fx*/carry i j k) (
Returns the two fixnum results of the following computation:
let*values (((s) (+ (* i j) k))
(expt 2 fxwidth))))
((q r) (balanced/ s (values r q)) (
The balanced/ procedure is available in SRFI 141, and also in the R6RS base library under the name of div0andmod0. Bitwise operations
The following procedures are the fixnum counterparts of certain bitwise operations from SRFI 151 and the R6RS (rnrs arithmetic fixnums) library. In case of disagreement, SRFI 151 is preferred. The prefixes bitwise and integer are dropped for brevity and compatibility.
(fxnot i)
Semantically equivalent to bitwisenot.
(fxand i ...)
Semantically equivalent to bitwiseand.
(fxior i ...)
Semantically equivalent to bitwiseior.
(fxxor i ...)
Semantically equivalent to bitwisexor.
(fxarithmeticshift i count)
Semantically equivalent to arithmeticshift, except that it is an error for the absolute value of count to exceed w1.
(fxarithmeticshiftleft i count)
The same as fxarithmeticshift except that a negative value of count is an error. This is provided for additional efficiency.
(fxarithmeticshiftright i count)
The same as fxarithmeticshift except that a nonnegative value of count specifies the number of bits to shift right, and a negative value is an error. This is provided for additional efficiency.
(fxbitcount i)
Semantically equivalent to SRFI 151 bitcount.
(fxlength i)
Semantically equivalent to integerlength.
(fxif mask i j)
Semantically equivalent to bitwiseif. It can be implemented as (fxior (fxand mask i) (fxand (fxnot mask) j))).
(fxbitset? index i)
Semantically equivalent to SRFI 151 bitset?, except that it is an error for index to be larger than or equal to fxwidth.
(fxcopybit index i boolean)
Semantically equivalent to SRFI 151 copybit, except that it is an error for index to be larger than or equal to fxwidth.
(fxfirstsetbit i)
Semantically equivalent to firstsetbit.
(fxbitfield i start end)
Semantically equivalent to bitfield.
(fxbitfieldrotate i count start end)
Semantically equivalent to SRFI 151 bitfieldrotate.
(fxbitfieldreverse i start end)
Semantically equivalent to bitfieldreverse.
(scheme flonum)
This is based on SRFI144.
This library describes numeric procedures applicable to flonums, a subset of the inexact real numbers provided by a Scheme implementation. In most Schemes, the flonums and the inexact reals are the same. These procedures are semantically equivalent to the corresponding generic procedures, but allow more efficient implementations.
fle
Bound to the mathematical constant e. (C99 M_E)
fl1/e
Bound to 1/e. (C99 M_E)
fle2
Bound to e2.
flepi/4
Bound to eπ/4.
fllog2e
Bound to log2 e. (C99 M_LOG2E)
fllog10e
Bound to log10 e. (C99 M_LOG10E)
fllog2
Bound to loge 2. (C99 M_LN2)
fl1/log2
Bound to 1/loge 2. (C99 M_LN2)
fllog3
Bound to loge 3.
fllogpi
Bound to loge π.
fllog10
Bound to loge 10. (C99 M_LN10)
fl1/log10
Bound to 1/loge 10. (C99 M_LN10)
flpi
Bound to the mathematical constant π. (C99 M_PI)
fl1/pi
Bound to 1/π. (C99 M_1_PI)
fl2pi
Bound to 2π.
flpi/2
Bound to π/2. (C99 M_PI_2)
flpi/4
Bound to π/4. (C99 M_PI_4)
flpisquared
Bound to π2.
fldegree
Bound to π/180, the number of radians in a degree.
fl2/pi
Bound to 2/π. (C99 M_2_PI)
fl2/sqrtpi
Bound to 2/√π. (C99 M_2_SQRTPI)
flsqrt2
Bound to √2. (C99 M_SQRT2)
flsqrt3
Bound to √3.
flsqrt5
Bound to √5.
flsqrt10
Bound to √10.
fl1/sqrt2
Bound to 1/√2. (C99 M_SQRT1_2)
flcbrt2
Bound to ∛2.
flcbrt3
Bound to ∛3.
fl4thrt2
Bound to ∜2.
Bound to the mathematical constant φ.
fllogphi
Bound to log(φ).
fl1/logphi
Bound to 1/log(φ).
fleuler
Bound to the mathematical constant γ (Euler’s constant).
fleeuler
Bound to eγ.
flsin1
Bound to sin 1.
flcos1
Bound to cos 1.
flgamma1/2
Bound to Γ(1/2).
flgamma1/3
Bound to Γ(1/3).
flgamma2/3
Bound to Γ(2/3).
flgreatest
flleast
Bound to the largest/smallest positive finite flonum. (e.g. C99 DBL_MAX and C11 DBL_TRUE_MIN)
flepsilon
Bound to the appropriate machine epsilon for the hardware representation of flonums. (C99 DBL_EPSILON in <float.h>)
flfastfl+*
Bound to #t if (fl+* x y z) executes about as fast as, or faster than, (fl+ (fl* x y) z); bound to #f otherwise. (C99 FP_FAST_FMA)
So that the value of this variable can be determined at compile time, R7RS implementations and other implementations that provide a features function should provide the feature flfastfl+* if this variable is true, and not if it is false or the value is unknown at compile time.
flintegerexponentzero
Bound to whatever exact integer is returned by (flintegerexponent 0.0). (C99 FP_ILOGB0)
flintegerexponentnan
Bound to whatever exact integer is returned by (flintegerexponent +nan.0). (C99 FP_ILOGBNAN)
(flonum number)
If number is an inexact real number and there exists a flonum that is the same (in the sense of =) to number, returns that flonum. If number is a negative zero, an infinity, or a NaN, return its flonum equivalent. If such a flonum does not exist, returns the nearest flonum, where “nearest” is implementationdependent. If number is not a real number, it is an error. If number is exact, applies inexact or exact>inexact to number first.
(fladjacent x y)
Returns a flonum adjacent to x in the direction of y. Specifically: if x < y, returns the smallest flonum larger than x; if x > y, returns the largest flonum smaller than x; if x = y, returns x. (C99 nextafter)
(flcopysign x y)
Returns a flonum whose magnitude is the magnitude of x and whose sign is the sign of y. (C99 copysign)
(makeflonum x n)
Returns x × 2n, where n is an integer with an implementationdependent range. (C99 ldexp)
(flintegerfraction x)
Returns two values, the integral part of x as a flonum and the fractional part of x as a flonum. (C99 modf)
(flexponent x)
Returns the exponent of x. (C99 logb)
(flintegerexponent x)
Returns the same as flexponent truncated to an exact integer. If x is zero, returns flintegerexponentzero; if x is a NaN, returns flintegerexponentnan; if x is infinite, returns a large implementationdependent exact integer. (C99 ilogb)
(flnormalizedfractionexponent x)
Returns two values, a correctly signed fraction y whose absolute value is between 0.5 (inclusive) and 1.0 (exclusive), and an exact integer exponent n such that x = y(2n). (C99 frexp)
(flsignbit x)
Returns 0 for positive flonums and 1 for negative flonums and 0.0. The value of (flsignbit +nan.0) is implementationdependent, reflecting the sign bit of the underlying representation of NaNs. (C99 signbit)
(flonum? obj)
Returns #t if obj is a flonum and #f otherwise.
(fl=? x y z ...)
(fl<? x y z ...)
(fl>? x y z ...)
(fl<=? x y z ...)
(fl>=? x y z ...)
These procedures return #t if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing; they return #f otherwise. These predicates must be transitive. (C99 =, <, > <=, >= operators respectively)
(flunordered? x y)
Returns #t if x and y are unordered according to IEEE rules. This means that one of them is a NaN.
These numerical predicates test a flonum for a particular property, returning #t or #f.
(flinteger? x)
Tests whether x is an integral flonum.
(flzero? x)
Tests whether x is zero. Beware of roundoff errors.
(flpositive? x)
Tests whether x is positive.
(flnegative? x)
Tests whether x is negative. Note that (flnegative? 0.0) must return #f; otherwise it would lose the correspondence with (fl<? 0.0 0.0), which is #f according to IEEE 754.
(flodd? x)
Tests whether the flonum x is odd. It is an error if x is not an integer.
(fleven? x)
Tests whether the flonum x is even. It is an error if x is not an integer.
(flfinite? x)
Tests whether the flonum x is finite. (C99 isfinite)
(flinfinite? x)
Tests whether the flonum x is infinite. (C99 isinf)
(flnan? x)
Tests whether the flonum x is NaN. (C99 isnan)
(flnormalized? x)
Tests whether the flonum x is normalized. (C11 isnormal; in C99, use fpclassify(x) == FP_NORMAL)
(fldenormalized? x)
Tests whether the flonum x is denormalized. (C11 issubnormal; in C99, use fpclassify(x) == FP_SUBNORMAL)
(flmax x ...)
(flmin x ...)
Return the maximum/minimum argument. If there are no arguments, these procedures return inf.0 or +inf.0 if the implementation provides these numbers, and (fl flgreatest) or flgreatest otherwise. (C99 fmax fmin)
(fl+ x ...)
(fl* x ...)
Return the flonum sum or product of their flonum arguments. (C99 + * operators respectively)
(fl+* x y z)
Returns xy + z as if to infinite precision and rounded only once. The boolean constant flfastfl+* indicates whether this procedure executes about as fast as, or faster than, a multiply and an add of flonums. (C99 fma)
(fl x y ...)
(fl/ x y ...)
With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument. (C99  / operators respectively)
(flabs x)
Returns the absolute value of x. (C99 fabs)
(flabsdiff x y)
Returns x  y.
(flposdiff x y)
Returns the difference of x and y if it is nonnegative, or zero if the difference is negative. (C99 fdim)
(flsgn x)
Returns (flcopysign 1.0 x).
(flnumerator x)
(fldenominator x)
Returns the numerator/denominator of x as a flonum; the result is computed as if x was represented as a fraction in lowest terms. The denominator is always positive. The numerator of an infinite flonum is itself. The denominator of an infinite or zero flonum is 1.0. The numerator and denominator of a NaN is a NaN.
(flfloor x)
Returns the largest integral flonum not larger than x. (C99 floor)
(flceiling x)
Returns the smallest integral flonum not smaller than x. (C99 ceil)
(flround x)
Returns the closest integral flonum to x, rounding to even when x represents a number halfway between two integers. (Not the same as C99 round, which rounds away from zero)
(fltruncate x)
Returns the closest integral flonum to x whose absolute value is not larger than the absolute value of x (C99 trunc) Exponents and logarithms
(flexp x)
Returns ex. (C99 exp)
(flexp2 x)
Returns 2x. (C99 exp2)
(flexp1 x)
Returns ex  1, but is much more accurate than flexp for very small values of x. It is recommended for use in algorithms where accuracy is important. (C99 expm1)
(flsquare x)
Returns x2.
(flsqrt x)
Returns √x. For 0.0, flsqrt should return 0.0. (C99 sqrt)
(flcbrt x)
Returns ∛x. (C99 cbrt)
(flhypot x y)
Returns the length of the hypotenuse of a right triangle whose sides are of length x and y. (C99 hypot)
(flexpt x y)
Returns xy. If x is zero, then the result is zero. (C99 pow)
(fllog x)
Returns loge x. (C99 log)
(fllog1+ x)
Returns loge (x+ 1), but is much more accurate than fllog for values of x near 0. It is recommended for use in algorithms where accuracy is important. (C99 log1p)
(fllog2 x)
Returns log2 x. (C99 log2)
(fllog10 x)
Returns log10 x. (C99 log10)
(makefllogbase x)
Returns a procedure that calculates the basex logarithm of its argument. If x is 1.0 or less than 1.0, it is an error.
(flsin x)
Returns sin x. (C99 sin)
(flcos x)
Returns cos x. (C99 cos)
(fltan x)
Returns tan x. (C99 tan)
(flasin x)
Returns arcsin x. (C99 asin)
(flacos x)
Returns arccos x. (C99 acos)
(flatan [y] x)
Returns arctan x. (C99 atan)
With two arguments, returns arctan(y/x). in the range [π,π], using the signs of x and y to choose the correct quadrant for the result. (C99 atan2)
(flsinh x)
Returns sinh x. (C99 sinh)
(flcosh x)
Returns cosh x. (C99 cosh)
(fltanh x)
Returns tanh x. (C99 tanh)
(flasinh x)
Returns arcsinh x. (C99 asinh)
(flacosh x)
Returns arccosh x. (C99 acosh)
(flatanh x)
Returns arctanh x. (C99 atanh)
(flquotient x y)
Returns the quotient of x/y as an integral flonum, truncated towards zero.
(flremainder x y)
Returns the truncating remainder of x/y as an integral flonum.
(flremquo x y)
` Returns two values, the rounded remainder of x/y and the loworder n bits (as a correctly signed exact integer) of the rounded quotient. The value of n is implementationdependent but at least 3. This procedure can be used to reduce the argument of the inverse trigonometric functions, while preserving the correct quadrant or octant. (C99 remquo)
(flgamma x)
Returns Γ(x), the gamma function applied to x. This is equal to (x1)! for integers. (C99 tgamma)
(flloggamma x)
Returns two values, log Γ(x) without internal overflow, and the sign of Γ(x) as 1.0 if it is positive and 1.0 if it is negative. (C99 lgamma)
(flfirstbessel n x)
Returns the nth order Bessel function of the first kind applied to x, Jn(x). (jn, which is an XSI Extension of C99)
(flsecondbessel n x)
Returns the nth order Bessel function of the second kind applied to x, Yn(x). (yn, which is an XSI Extension of C99)
(flerf x)
Returns the error function erf(x). (C99 erf)
(flerfc x)
Returns the complementary error function, 1  erf(x). (C99 erfc)
(scheme generator)
This is based on SRFI158
This SRFI defines utility procedures that create, transform, and consume generators. A generator is simply a procedure with no arguments that works as a source of values. Every time it is called, it yields a value. Generators may be finite or infinite; a finite generator returns an endoffile object to indicate that it is exhausted. For example, readchar, readline, and read are generators that generate characters, lines, and objects from the current input port. Generators provide lightweight laziness.
This SRFI also defines procedures that return accumulators. An accumulator is the inverse of a generator: it is a procedure of one argument that works as a sink of values.
(generator arg ...)
The simplest finite generator. Generates each of its arguments in turn. When no arguments are provided, it returns an empty generator that generates no values.
(circulargenerator arg ...)
The simplest infinite generator. Generates each of its arguments in turn, then generates them again in turn, and so on forever.
(makeiotagenerator count [start [step]])
Creates a finite generator of a sequence of count numbers. The sequence begins with start (which defaults to 0) and increases by step (which defaults to 1). If both start and step are exact, it generates exact numbers; otherwise it generates inexact numbers. The exactness of count doesn’t affect the exactness of the results.
(makerangegenerator start [end [step]])
Creates a generator of a sequence of numbers. The sequence begins with start, increases by step (default 1), and continues while the number is less than end, or forever if end is omitted. If both start and step are exact, it generates exact numbers; otherwise it generates inexact numbers. The exactness of end doesn’t affect the exactness of the results.
(makecoroutinegenerator proc)
Creates a generator from a coroutine.
The proc argument is a procedure that takes one argument, yield. When called, makecoroutinegenerator immediately returns a generator g. When g is called, proc runs until it calls yield. Calling yield causes the execution of proc to be suspended, and g returns the value passed to yield.
Whether this generator is finite or infinite depends on the behavior of proc. If proc returns, it is the end of the sequence — g returns an endoffile object from then on. The return value of proc is ignored.
The following code creates a generator that produces a series 0, 1, and 2 (effectively the same as (makerangegenerator 0 3)) and binds it to g.
define g
(
(makecoroutinegeneratorlambda (yield) (let loop ((i 0))
(< i 3) (yield i) (loop (+ i 1)))))))
(when (
;; => (0 1 2) (generator>list g)
(list>generator list)
Convert LIST
into a generator.
(vector>generator vector [start [end]])
(reversevector>generator vector [start [end]])
(string>generator string [start [end]])
(bytevector>generator bytevector [start [end]])
These procedures return generators that yield each element of the given argument. Mutating the underlying object will affect the results of the generator.
1 2 3 4 5)))
(generator>list (list>generator '(;; => (1 2 3 4 5)
1 2 3 4 5)))
(generator>list (vector>generator '#(;; => (1 2 3 4 5)
1 2 3 4 5)))
(generator>list (reversevector>generator '#(;; => (5 4 3 2 1)
"abcde"))
(generator>list (string>generator ;; => (#\a #\b #\c #\d #\e)
The generators returned by the constructors are exhausted once all elements are retrieved; the optional startth and endth arguments can limit the range the generator walks across.
For reversevector>generator, the first value is the element right before the endth element, and the last value is the startth element. For all the other constructors, the first value the generator yields is the startth element, and it ends right before the endth element.
2))
(generator>list (vector>generator '#(a b c d e) ;; => (c d e)
2 4))
(generator>list (vector>generator '#(a b c d e) ;; => (c d)
2))
(generator>list (reversevector>generator '#(a b c d e) ;; => (e d c)
2 4))
(generator>list (reversevector>generator '#(a b c d e) ;; => (d c)
0 2))
(generator>list (reversevector>generator '#(a b c d e) ;; => (b a)
(makeforeachgenerator foreach obj)
A generator constructor that converts any collection obj to a generator that returns its elements using a foreach procedure appropriate for obj. This must be a procedure that when called as (foreach proc obj) calls proc on each element of obj. Examples of such procedures are foreach, stringforeach, and vectorforeach from R7RS. The value returned by foreach is ignored. The generator is finite if the collection is finite, which would typically be the case.
The collections need not be conventional ones (lists, strings, etc.) as long as foreach can invoke a procedure on everything that counts as a member. For example, the following procedure allows foreachgenerator to generate the digits of an integer from least to most significant:
define (foreachdigit proc n)
(> n 0)
(when (letvalues (((div rem) (truncate/ n 10)))
(
(proc rem)div)))) (foreachdigit proc
(makeunfoldgenerator stop? mapper successor seed)
A generator constructor similar to (scheme list)
unfold.
The stop? predicate takes a seed value and determines whether to stop. The mapper procedure calculates a value to be returned by the generator from a seed value. The successor procedure calculates the next seed value from the current seed value.
For each call of the resulting generator, stop? is called with the current seed value. If it returns true, then the generator returns an endoffile object. Otherwise, it applies mapper to the current seed value to get the value to return, and uses successor to update the seed value.
This generator is finite unless stop? never returns true.
(generator>list (makeunfoldgeneratorlambda (s) (> s 5))
(lambda (s) (* s 2))
(lambda (s) (+ s 1))
(0))
;; => (0 2 4 6 8 10)
(gcons* item ... generator)
Returns a generator that adds items in front of gen. Once the items have been consumed, the generator is guaranteed to tailcall gen.
0 2)))
(generator>list (gcons* 'a 'b (makerangegenerator ;; => (a b 0 1)
(gappend generator ...)
Returns a generator that yields the items from the first given generator, and once it is exhausted, from the second generator, and so on.
0 3) (makerangegenerator 0 2)))
(generator>list (gappend (makerangegenerator ;; => (0 1 2 0 1)
(generator>list (gappend));; => ()
(gflatten generator)
Returns a generator that yields the elements of the lists produced by the given generator.
(ggroup generator k [padding])
Returns a generator that yields lists of k items from the given generator. If fewer than k elements are available for the last list, and padding is absent, the short list is returned; otherwise, it is padded by padding to length k.
(gmerge lessthan generator1 ...)
Returns a generator that yields the items from the given generators in the order dictated by lessthan. If the items are equal, the leftmost item is used first. When all of given generators are exhausted, the returned generator is exhausted also.
As a special case, if only one generator is given, it is returned.
(gmap proc generator ...)
When only one generator is given, returns a generator that yields the items from the given generator after invoking proc on them.
When more than one generator is given, each item of the resulting generator is a result of applying proc to the items from each generator. If any of input generator is exhausted, the resulting generator is also exhausted.
Note: This differs from generatormap>list, which consumes all values at once and returns the results as a list, while gmap returns a generator immediately without consuming input.
 (makerangegenerator 0 3)))
(generator>list (gmap ;; => (0 1 2)
cons (generator 1 2 3) (generator 4 5)))
(generator>list (gmap ;; => ((1 . 4) (2 . 5))
(gcombine proc seed generator generator2)
A generator for mapping with state. It yields a sequence of subfolds over proc.
The proc argument is a procedure that takes as many arguments as the input generators plus one. It is called as (proc v1 v2 … seed), where v1, v2, … are the values yielded from the input generators, and seed is the current seed value. It must return two values, the yielding value and the next seed. The result generator is exhausted when any of the genn generators is exhausted, at which time all the others are in an undefined state.
(gfilter predicate generator)
(gremove predicate generator)
Returns generators that yield the items from the source generator, except those on which pred answers false or true respectively.
(gstatefilter proc seed generator)
Returns a generator that obtains items from the source generator and passes an item and a state (whose initial value is seed) as arguments to proc. Proc in turn returns two values, a boolean and a new value of the state. If the boolean is true, the item is returned; otherwise, this algorithm is repeated until gen is exhausted, at which point the returned generator is also exhausted. The final value of the state is discarded.
(gtake gen k [padding])
(gdrop gen k)
These are generator analogues of SRFI 1 take and drop. Gtake returns a generator that yields (at most) the first k items of the source generator, while gdrop returns a generator that skips the first k items of the source generator.
These won’t complain if the source generator is exhausted before generating k items. By default, the generator returned by gtake terminates when the source generator does, but if you provide the padding argument, then the returned generator will yield exactly k items, using the padding value as needed to provide sufficient additional values.
gtakewhile pred gen
gdropwhile pred gen
The generator analogues of SRFI1 takewhile and dropwhile. The generator returned from gtakewhile yields items from the source generator as long as pred returns true for each. The generator returned from gdropwhile first reads and discards values from the source generator while pred returns true for them, then starts yielding items returned by the source.
(gdelete item gen [=])
Creates a generator that returns whatever gen returns, except for any items that are the same as item in the sense of =, which defaults to equal?. The = predicate is passed exactly two arguments, of which the first was generated by gen before the second.
3 (generator 1 2 3 4 5 3 6 7)))
(generator>list (gdelete ;; => (1 2 4 5 6 7)
(gdeleteneighbordups gen [=])
Creates a generator that returns whatever gen returns, except for any items that are equal to the preceding item in the sense of =, which defaults to equal?. The = predicate is passed exactly two arguments, of which the first was generated by gen before the second.
(generator>list (gdeleteneighbordups (list>generator '(a a b c a a a d c))));; => (a b c a d c)
(gindex valuegen indexgen)
Creates a generator that returns elements of valuegen specified by the indices (nonnegative exact integers) generated by indexgen. It is an error if the indices are not strictly increasing, or if any index exceeds the number of elements generated by valuegen. The result generator is exhausted when either generator is exhausted, at which time the other is in an undefined state.
(generator>list (gindex (list>generator '(a b c d e f))0 2 4))))
(list>generator '(;; => (a c e)
(gselect valuegen truthgen)
Creates a generator that returns elements of valuegen that correspond to the values generated by truthgen. If the current value of truthgen is true, the current value of valuegen is generated, but otherwise not. The result generator is exhausted when either generator is exhausted, at which time the other is in an undefined state.
(generator>list (gselect (list>generator '(a b c d e f))#t #f #f #t #t #f))))
(list>generator '(;; => (a d e)
(generator>list generator [k])
Reads items from generator and returns a newly allocated list of them. By default, it reads until the generator is exhausted.
If an optional argument k is given, it must be a nonnegative integer, and the list ends when either k items are consumed, or generator is exhausted; therefore generator can be infinite in this case.
(generator>reverselist generator [k])
Reads items from generator and returns a newly allocated list of them in reverse order. By default, this reads until the generator is exhausted.
If an optional argument k is given, it must be a nonnegative integer, and the list ends when either k items are read, or generator is exhausted; therefore generator can be infinite in this case.
(generator>vector generator [k])
Reads items from generator and returns a newly allocated vector of them. By default, it reads until the generator is exhausted.
If an optional argument k is given, it must be a nonnegative integer, and the list ends when either k items are consumed, or generator is exhausted; therefore generator can be infinite in this case.
(generator>vector! vector at generator)
Reads items from generator and puts them into vector starting at index at, until vector is full or generator is exhausted. Generator can be infinite. The number of elements generated is returned.
(generator>string generator [k])
Reads items from generator and returns a newly allocated string of them. It is an error if the items are not characters. By default, it reads until the generator is exhausted.
If an optional argument k is given, it must be a nonnegative integer, and the string ends when either k items are consumed, or generator is exhausted; therefore generator can be infinite in this case.
(generatorfold proc seed generator ...)
Works like (scheme list)
fold on the values generated by
the generator arguments.
When one generator is given, for each value v generated by gen, proc is called as (proc v r), where r is the current accumulated result; the initial value of the accumulated result is seed, and the return value from proc becomes the next accumulated result. When gen is exhausted, the accumulated result at that time is returned from generatorfold.
When more than one generator is given, proc is invoked on the values returned by all the generator arguments followed by the current accumulated result. The procedure terminates when any of the genn generators is exhausted, at which time all the others are in an undefined state.
"a b c d e"
(withinputfromstring lambda () (generatorfold cons 'z read)))
(;; => (e d c b a . z)
(generatorforeach proc generator ...)
A generator analogue of foreach that consumes generated values using side effects. Repeatedly applies proc on the values yielded by gen, gen2 … until any one of the generators is exhausted, at which time all the others are in an undefined state. The values returned from proc are discarded. Returns an unspecified value.
(generatormap>list proc generator ...)
A generator analogue of map that consumes generated values, processes them through a mapping function, and returns a list of the mapped values. Repeatedly applies proc on the values yielded by gen, gen2 … until any one of the generators is exhausted, at which time all the others are in an undefined state. The values returned from proc are accumulated into a list, which is returned.
(generatorfind predicate generator)
Returns the first item from the generator gen that satisfies the predicate pred, or #f if no such item is found before gen is exhausted. If gen is infinite, generatorfind will not return if it cannot find an appropriate item.
(generatorcount predicate generator)
Returns the number of items available from the generator gen that satisfy the predicate pred.
(generatorany predicate generator)
Applies predicate to each item from gen. As soon as it yields a true value, the value is returned without consuming the rest of gen. If gen is exhausted, returns #f.
(generatorevery predicate generator)
Applies pred to each item from gen. As soon as it yields a false value, the value is returned without consuming the rest of gen. If gen is exhausted, returns the last value returned by pred, or #t if pred was never called.
(generatorunfold gen unfold arg ...)
Equivalent to
(unfold eofobject? (lambda (x) x) (lambda (x) (gen)) (gen) arg ...)
.
The values of gen are unfolded into the collection that unfold
creates.
The signature of the unfold procedure is (unfold stop? mapper successor seed args …). Note that the vectorunfold and vectorunfoldright of SRFI 43 and SRFI 133 do not have this signature and cannot be used with this procedure. To unfold into a vector, use SRFI 1’s unfold and then apply list>vector to the result.
;; Iterates over string and unfolds into a list using SRFI 1 unfold
"abc") unfold)
(generatorunfold (makeforeachgenerator stringforeach ;; => (#\a #\b #\c)
(makeaccumulator kons knil finalizer)
Returns an accumulator that, when invoked on an object other than an endoffile object, invokes kons on its argument and the accumulator’s current state, using the same order as a function passed to fold. It then sets the accumulator’s state to the value returned by kons and returns an unspecified value. The initial state of the accumulator is set to knil. However, if an endoffile object is passed to the accumulator, it returns the result of tailcalling the procedure finalizer on the state. Repeated calls with an endoffile object will reinvoke finalizer.
(countaccumulator)
qReturns an accumulator that, when invoked on an object, adds 1 to a count inside the accumulator and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the count.
(listaccumulator)
Returns an accumulator that, when invoked on an object, adds that object to a list inside the accumulator in order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the list.
(reverselistaccumulator)
Returns an accumulator that, when invoked on an object, adds that object to a list inside the accumulator in reverse order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the list.
(vectoraccumulator)
Returns an accumulator that, when invoked on an object, adds that object to a vector inside the accumulator in order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the vector.
(reversevectoraccumulator)
Returns an accumulator that, when invoked on an object, adds that object to a vector inside the accumulator in reverse order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the vector.
(vectoraccumulator! vector at)
Returns an accumulator that, when invoked on an object, adds that object to consecutive positions of vector starting at at in order of accumulation. It is an error to try to accumulate more objects than vector will hold. An unspecified value is returned. However, if an endoffile object is passed, the accumulator returns vector.
(stringaccumulator)
Returns an accumulator that, when invoked on a character, adds that character to a string inside the accumulator in order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the string.
(bytevectoraccumulator)
Returns an accumulator that, when invoked on a byte, adds that integer to a bytevector inside the accumulator in order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the bytevector.
(bytevectoraccumulator! bytevector at)
Returns an accumulator that, when invoked on a byte, adds that byte to consecutive positions of bytevector starting at at in order of accumulation. It is an error to try to accumulate more bytes than vector will hold. An unspecified value is returned. However, if an endoffile object is passed, the accumulator returns bytevector.
(sumaccumulator)
Returns an accumulator that, when invoked on a number, adds that number to a sum inside the accumulator in order of accumulation and returns an unspecified value. However, if an endoffile object is passed, the accumulator returns the sum.
(productaccumulator)
Returns an accumulator that, when invoked on a number, multiplies
that number to a product inside the accumulator in order of accumulation
and returns an unspecified value. However, if an endoffile object is
passed, the accumulator returns the product. #
(scheme hashtable)
This library is based on srfi125.
The library doesn’t implement deprecated features. Application must
rely on (scheme comparator)
to specify equal predicate and
hash function.
This SRFI defines an interface to hash tables, which are widely recognized as a fundamental data structure for a wide variety of applications. A hash table is a data structure that:
Is disjoint from all other types.
Provides a mapping from objects known as keys to corresponding objects known as values.
Keys may be any Scheme objects in some kinds of hash tables, but are restricted in other kinds.
Values may be any Scheme objects.
Has no intrinsic order for the keyvalue associations it contains.
Provides an equality predicate which defines when a proposed key is the same as an existing key. No table may contain more than one value for a given key.
Provides a hash function which maps a candidate key into a nonnegative exact integer.
Supports mutation as the primary means of setting the contents of a able.
Provides key lookup and destructive update in (expected) amortized constant time, provided a satisfactory hash function is available.
Does not guarantee that wholetable operations work in the presence of concurrent mutation of the whole hash table (values may be safely mutated).
(makehashtable comparator . args)
Returns a newly allocated hash table using
(scheme comparator)
object COMPARATOR
. For the
time being, ARGS
is ignored.
(hashtable comparator [key value] ...)
Returns a newly allocated hash table using
(scheme comparator)
object COMPARATOR
. For
each pair of arguments, an association is added to the new hash table
with key as its key and value as its value. If the same key (in the
sense of the equality predicate) is specified more than once, it is an
error.
(hashtableunfold stop? mapper successor seed comparator args ...)
Create a new hash table as if by makehashtable
using
comparator
and the args
. If the result of
applying the predicate stop?
to seed
is true,
return the hash table. Otherwise, apply the procedure
mapper
to seed
. mapper
returns
two values, which are inserted into the hash table as the key and the
value respectively. Then get a new seed
by applying the
procedure successor
to seed
, and repeat this
algorithm.
(alist>hashtable alist comparator arg ...)
Returns a newly allocated hashtable as if by
makehashtable
using comparator
and the
args
. It is then initialized from the associations of
alist
. Associations earlier in the list take precedence
over those that come later.
(hashtable? obj)
Returns #t if obj is a hash table, and #f otherwise
(hashtablecontains? hashtable key)
Returns #t if there is any association to key in hashtable, and #f otherwise.
(hashtableempty? hashtable)
Returns #t if hashtable contains no associations, and #f otherwise.
(hashtable=? valuecomparator hashtable1 hashtable2)
Returns #t if hashtable1 and hashtable2 have the same keys (in the sense of their common equality predicate) and each key has the same value (in the sense of valuecomparator), and #f otherwise.
(hashtablemutable? hashtable)
Returns #t if the hash table is mutable.
(hashtableref hashtable key [failure [success]])
Extracts the value associated to key in hashtable, invokes the procedure success on it, and returns its result; if success is not provided, then the value itself is returned. If key is not contained in hashtable and failure is supplied, then failure is invoked on no arguments and its result is returned.
(hashtableref/default hashtable key default)
TODO
(hashtableset! hashtable key value ...)
Repeatedly mutates hashtable, creating new associations in it by processing the arguments from left to right. The args alternate between keys and values. Whenever there is a previous association for a key, it is deleted. It is an error if the type check procedure of the comparator of hashtable, when invoked on a key, does not return #t. Likewise, it is an error if a key is not a valid argument to the equality predicate of hashtable. Returns an unspecified value.
(hashtabledelete! hashtable key ...)
Deletes any association to each key in hashtable and returns the number of keys that had associations.
(hashtableintern! hashtable key failure)
Effectively invokes hashtableref with the given arguments and returns what it returns. If key was not found in hashtable, its value is set to the result of calling failure.
(hashtableupdate! hashtable key updater [failure [success]])
TODO:
(hashtablepop! hashtable)
Chooses an arbitrary association from hashtable and removes it, returning the key and value as two values. It is an error if hashtable is empty.
(hashtableclear! hashtable)
Delete all the associations from hashtable.
(hashtablesize hashtable)
Returns the number of associations in hashtable as an exact integer.
(hashtablekeys hashtable)
Returns a newly allocated list of all the keys in hashtable.
(hashtablevalues hashtable)
Returns a newly allocated list of all the keys in hashtable.
(hashtableentries hashtable)
Returns two values, a newly allocated list of all the keys in hashtable and a newly allocated list of all the values in hashtable in the corresponding order.
(hashtablefind proc hashtable failure)
For each association of hashtable, invoke proc on its key and value. If proc returns true, then hashtablefind returns what proc returns. If all the calls to proc return #f, return the result of invoking the thunk failure.
(hashtablecount pred hashtable)
For each association of hashtable, invoke pred on its key and value. Return the number of calls to pred which returned true.
(hashtablemap proc comparator hashtable)
Returns a newly allocated hash table as if by
(makehashtable comparator)
. Calls PROC
for
every association in hashtable
with the value of the
association. The key of the association and the result of invoking
proc
are entered into the new hash table. Note that this is
not the result of lifting mapping over the domain of hash tables, but it
is considered more useful.
If comparator recognizes multiple keys in the hashtable as equivalent, any one of such associations is taken.
(hashtableforeach proc hashtable)
Calls proc for every association in hashtable with two arguments: the key of the association and the value of the association. The value returned by proc is discarded. Returns an unspecified value.
(hashtablemap! proc hashtable)
Calls proc for every association in hashtable with two arguments: the key of the association and the value of the association. The value returned by proc is used to update the value of the association. Returns an unspecified value.
(hashtablemap>list proc hashtable)
Calls proc for every association in hashtable with two arguments: the key of the association and the value of the association. The values returned by the invocations of proc are accumulated into a list, which is returned.
(hashtablefold proc seed hashtable)
Calls proc for every association in hashtable with three arguments: the key of the association, the value of the association, and an accumulated value val. Val is seed for the first invocation of procedure, and for subsequent invocations of proc, the returned value of the previous invocation. The value returned by hashtablefold is the return value of the last invocation of proc.
(hashtableprune! proc hashtable)
Calls proc for every association in hashtable with two arguments, the key and the value of the association, and removes all associations from hashtable for which proc returns true. Returns an unspecified value.
(hashtablecopy hashtable [mutable?])
Returns a newly allocated hash table with the same properties and associations as hashtable. If the second argument is present and is true, the new hash table is mutable. Otherwise it is immutable provided that the implementation supports immutable hash tables.
(hashtableemptycopy hashtable)
Returns a newly allocated mutable hash table with the same properties as hashtable, but with no associations.
(hashtable>alist hashtable)
Returns an alist with the same associations as hashtable in an unspecified order.
(hashtableunion! hashtable1 hashtable2)
Adds the associations of hashtable2 to hashtable1 and returns hashtable1. If a key appears in both hash tables, its value is set to the value appearing in hashtable1. Returns hashtable1.
(hashtableintersection! hashtable1 hashtable2)
Deletes the associations from hashtable1 whose keys don’t also appear in hashtable2 and returns hashtable1.
(hashtabledifference! hashtable1 hashtable2)
Deletes the associations of hashtable1 whose keys are also present in hashtable2 and returns hashtable1.
(hashtablexor! hashtable1 hashtable2)
Deletes the associations of hashtable1 whose keys are also present
in hashtable2, and then adds the associations of hashtable2 whose keys
are not present in hashtable1 to hashtable1. Returns hashtable1. #
(scheme idque)
This is based on SRFI134.
This SRFI defines immutable deques. A deque is a doubleended queue, a sequence which allows elements to be added or removed efficiently from either end. A structure is immutable when all its operations leave the structure unchanged. Note that none of the procedures specified here ends with an exclamation point.
This SRFI describes immutable deques, or ideques. Immutable structures are sometimes called persistent and are closely related to pure functional (a.k.a. pure) structures. The availability of immutable data structures facilitates writing efficient programs in the purefunctional style. Immutable deques can also be seen as a bidirectional generalization of immutable lists, and some of the procedures documented below are most useful in that context. Unlike the immutable lists of SRFI 116, it is efficient to produce modified versions of an ideque; unlike the list queues of SRFI 117, it is possible to efficiently return an updated version of an ideque without mutating any earlier versions of it.
The specification was designed jointly by Kevin Wortman and John Cowan. John Cowan is the editor and shepherd. The twolist implementation was written by John Cowan.
(ideque element ...)
Returns an ideque containing the elements. The first element (if any) will be at the front of the ideque and the last element (if any) will be at the back. Takes O(n) time, where n is the number of elements.
(idequetabulate n proc)
Invokes the predicate proc on every exact integer from 0 (inclusive) to n (exclusive). Returns an ideque containing the results in order of generation. Takes O(n) time.
(idequeunfold stop? mapper successor seed)
Invokes the predicate stop? on seed. If it returns false, generate the next result by applying mapper to seed, generate the next seed by applying successor to seed, and repeat this algorithm with the new seed. If stop? returns true, return an ideque containing the results in order of accumulation. Takes O(n) time.
(idequeunfoldright stop? mapper successor seed)
Invokes the predicate stop? on seed. If it returns false, generate the next result by applying mapper to seed, generate the next seed by applying successor to seed, and repeat the algorithm with the new seed. If stop? returns true, return an ideque containing the results in reverse order of accumulation. Takes O(n) time. Predicates
(ideque? x)
Returns #t if x is an ideque, and #f otherwise. Takes O(1) time.
(idequeempty? idaeque)
Returns #t if ideque contains zero elements, and #f otherwise. Takes O(1) time.
(ideque= elt= ideque ...)
Determines ideque equality, given an elementequality procedure. Ideque A equals ideque B if they are of the same length, and their corresponding elements are equal, as determined by elt=. If the elementcomparison procedure’s first argument is from idequei, then its second argument is from idequei+1, i.e. it is always called as (elt= a b) for a an element of ideque A, and b an element of ideque B.
In the nary case, every idequei is compared to idequei+1 (as opposed, for example, to comparing ideque1 to every idequei, for i > 1). If there are zero or one ideque arguments, ideque= simply returns true. The name does not end in a question mark for compatibility with the SRFI1 procedure list=.
Note that the dynamic order in which the elt= procedure is applied to pairs of elements is not specified. For example, if ideque= is applied to three ideques, A, B, and C, it may first completely compare A to B, then compare B to C, or it may compare the first elements of A and B, then the first elements of B and C, then the second elements of A and B, and so forth.
The equality procedure must be consistent with eq?. Note that this implies that two ideques which are eq? are always ideque=, as well; implementations may exploit this fact to “shortcut” the elementbyelement comparisons.
(idequeany pred ideque)
(idequeevery pred ideque)
Invokes pred on the elements of the ideque in order until one call returns a true/false value, which is then returned. If there are no elements, returns #f/#t. Takes O(n) time. Queue operations
(idequefront ideque)
(idequeback ideque)
Returns the front/back element of ideque. It is an error for ideque to be empty. Takes O(1) time.
(idequeremovefront ideque)
(idequeremoveback ideque)
Returns an ideque with the front/back element of ideque removed. It is an error for ideque to be empty. Takes O(1) time.
(idequeaddfront ideque obj)
(idequeaddback ideque obj)
Returns an ideque with obj pushed to the front/back of ideque. Takes O(1) time. Other accessors
(idequeref ideque n)
Returns the nth element of ideque. It is an error unless n is less than the length of ideque. Takes O(n) time.
(idequetake ideque n)
(idequetakeright ideque n)
Returns an ideque containing the first/last n elements of ideque. It is an error if n is greater than the length of ideque. Takes O(n) time.
(idequedrop ideque n)
(idequedropright ideque n)
Returns an ideque containing all but the first/last n elements of ideque. It is an error if n is greater than the length of ideque. Takes O(n) time.
(idequesplitat ideque n)
Returns two values, the results of (idequetake ideque n) and (idequedrop ideque n) respectively, but may be more efficient. Takes O(n) time. The whole ideque
(idequelength ideque)
Returns the length of ideque as an exact integer. May take O(n) time, though O(1) is optimal.
(idequeappend ideque ...)
Returns an ideque with the contents of the ideque followed by the others, or an empty ideque if there are none. Takes O(kn) time, where k is the number of ideques and n is the number of elements involved, though O(k log n) is possible.
(idequereverse ideque)
Returns an ideque containing the elements of ideque in reverse order. Takes O(1) time.
(idequecount pred ideque)
Pred is a procedure taking a single value and returning a single value. It is applied elementwise to the elements of ideque, and a count is tallied of the number of elements that produce a true value. This count is returned. Takes O(n) time. The dynamic order of calls to pred is unspecified.
(idequezip ideque1 ideque2 ...)
Returns an ideque of lists (not ideques) each of which contains the corresponding elements of ideques in the order specified. Terminates when all the elements of any of the ideques have been processed. Takes O(kn) time, where k is the number of ideques and n is the number of elements in the shortest ideque.
(idequemap proc ideque)
Applies proc to the elements of ideque and returns an ideque containing the results in order. The dynamic order of calls to proc is unspecified. Takes O(n) time.
(idequefiltermap proc ideque)
Applies proc to the elements of ideque and returns an ideque containing the true (i.e. non#f) results in order. The dynamic order of calls to proc is unspecified. Takes O(n) time.
(idequeforeach proc ideque)
(idequeforeachright proc ideque)
Applies proc to the elements of ideque in forward/reverse order and returns an unspecified result. Takes O(n) time.
(idequefold proc nil ideque)
(idequefoldright proc nil ideque)
Invokes proc on the elements of ideque in forward/reverse order, passing the result of the previous invocation as a second argument. For the first invocation, nil is used as the second argument. Returns the result of the last invocation, or nil if there was no invocation. Takes O(n) time.
(idequeappendmap proc ideque)
Applies proc to the elements of ideque. It is an error if the result is not a list. Returns an ideque containing the elements of the lists in order. Takes O(n) time, where n is the number of elements in all the lists returned.
(idequefilter pred ideque)
(idequeremove pred ideque)
Returns an ideque containing the elements of ideque that do/do not satisfy pred. Takes O(n) time.
(idequepartition proc ideque)
Returns two values, the results of (idequefilter pred ideque) and (idequeremove pred ideque) respectively, but may be more efficient. Takes O(n) time.
(idequefind pred ideque [ failure ])
(idequefindright pred ideque [ failure ])
Returns the first/last element of ideque that satisfies pred. If there is no such element, returns the result of invoking the thunk failure; the default thunk is (lambda () #f). Takes O(n) time.
(idequetakewhile pred ideque)
(idequetakewhileright pred ideque)
Returns an ideque containing the longest initial/final prefix of elements in ideque all of which satisfy pred. Takes O(n) time.
(idequedropwhile pred ideque)
(idequedropwhileright pred ideque)
Returns an ideque which omits the longest initial/final prefix of elements in ideque all of which satisfy pred, but includes all other elements of ideque. Takes O(n) time.
(idequespan pred ideque)
(idequebreak pred ideque)
Returns two values, the initial prefix of the elements of ideque which do/do not satisfy pred, and the remaining elements. Takes O(n) time.
(list>ideque list)
(ideque>list ideque)
Conversion between ideque and list structures. FIFO order is preserved, so the front of a list corresponds to the front of an ideque. Each operation takes O(n) time.
(generator>ideque generator)
(ideque>generator ideque)
Conversion between SRFI 121 generators and ideques. Each operation
takes O(n) time. A generator is a procedure that is called repeatedly
with no arguments to generate consecutive values, and returns an
endoffile object when it has no more values to return. #
(scheme ilist)
This library is based on SRFI116.
Scheme currently does not provide immutable pairs corresponding to its existing mutable pairs, although most uses of pairs do not exploit their mutability. The Racket system takes the radical approach of making Scheme’s pairs immutable, and providing a minimal library of mutable pairs with procedures named mpair?, mcons, mcar, mcdr, setmcar!, setmcdr!. This SRFI takes the opposite approach of leaving Scheme’s pairs unchanged and providing a full set of routines for creating and dealing with immutable pairs. The sample implementation is portable (to systems with SRFI 9) and efficient.
(ipair a d)
The primitive constructor. Returns a newly allocated ipair whose icar is a and whose icdr is d. The ipair is guaranteed to be different (in the sense of eqv?) from every existing object.
=> (a)
(ipair 'a '()) => ((a) b c d)
(ipair (iq a) (iq b c d)) "a" (iq b c)) => ("a" b c)
(ipair 3) => (a . 3)
(ipair 'a => ((a b ) . c) (ipair (iq a b) 'c)
(ilist object ...)
Returns a newly allocated ilist of its arguments.
+ 3 4) 'c) => (a 7 c)
(ilist 'a (=> () (ilist)
(xipair d a)
lambda (d a) (ipair a d)) (
Of utility only as a value to be conveniently passed to higherorder procedures.
=> (a b c) (xipair (iq b c) 'a)
The name stands for “eXchanged Immutable PAIR.”
Like ilist, but the last argument provides the tail of the constructed ilist, returning
... eltn)))
(ipair elt1 (ipair elt2 (ipair
1 2 3 4) => (1 2 3 . 4)
(ipair* 1) => 1 (ipair*
(makeilist n [fill])
Returns an nelement ilist, whose elements are all the value fill. If the fill argument is not given, the elements of the ilist may be arbitrary values.
4 'c) => (c c c c) (makeilist
(ilisttabulate n initproc)
Returns an nelement ilist. Element i of the ilist, where 0 <= i < n, is produced by (initproc i). No guarantee is made about the dynamic order in which initproc is applied to these indices.
4 values) => (0 1 2 3) (ilisttabulate
(ilistcopy dilist)
Copies the spine of the argument, including the ilist tail.
(iiota count [start step])
Returns an ilist containing the elements
... start+(count1)*step) (start start+step
The start and step parameters default to 0 and 1, respectively. This procedure takes its name from the APL primitive.
5) => (0 1 2 3 4)
(iiota 5 0 0.1) => (0 0.1 0.2 0.3 0.4) (iiota
(properilist? x)
(ilist? x)
These identifiers are bound either to the same procedure, or to procedures of equivalent behavior. In either case, true is returned iff x is a proper ilist — a ()terminated ilist.
More carefully: The empty list is a proper ilist. An ipair whose icdr is a proper ilist is also a proper ilist. Everything else is a dotted ilist. This includes nonipair, non() values (e.g. symbols, numbers, mutable pairs), which are considered to be dotted ilists of length 0.
(dottedilist? x)
True if x is a finite, nonnilterminated ilist. That is, there exists an n >= 0 such that icdrn(x) is neither an ipair nor (). This includes nonipair, non() values (e.g. symbols, numbers), which are considered to be dotted ilists of length 0.
= (not (properilist? x)) (dottedilist? x)
(ipair? object)
Returns #t if object is an ipair; otherwise, #f.
=> #t
(ipair? (ipair 'a 'b)) => #t
(ipair? (iq a b c)) cons 1 2)) => #f
(ipair? (=> #f
(ipair? '()) => #f
(ipair? '#(a b)) 7) => #f
(ipair? => #f (ipair? 'a)
Ilist is a proper ilist. This procedure returns true if the argument is the empty list (), and false otherwise. It is an error to pass this procedure a value which is not a proper ilist. This procedure is recommended as the termination condition for ilistprocessing procedures that are not defined on dotted ilists.
(notipair? x)
lambda (x) (not (ipair? x))) (
Provided as a procedure as it can be useful as the termination condition for ilistprocessing procedures that wish to handle all ilists, both proper and dotted.
(ilist= elt= ilist1 ...)
Determines ilist equality, given an elementequality procedure. Proper ilist A equals proper ilist B if they are of the same length, and their corresponding elements are equal, as determined by elt=. If the elementcomparison procedure’s first argument is from ilisti, then its second argument is from ilisti+1, i.e. it is always called as (elt= a b) for a an element of ilist A, and b an element of ilist B.
In the nary case, every ilisti is compared to ilisti+1 (as opposed, for example, to comparing ilist1 to ilisti, for i>1). If there are no ilist arguments at all, ilist= simply returns true.
It is an error to apply ilist= to anything except proper ilists. It cannot reasonably be extended to dotted ilists, as it provides no way to specify an equality procedure for comparing the ilist terminators.
Note that the dynamic order in which the elt= procedure is applied to pairs of elements is not specified. For example, if ilist= is applied to three ilists, A, B, and C, it may first completely compare A to B, then compare B to C, or it may compare the first elements of A and B, then the first elements of B and C, then the second elements of A and B, and so forth.
The equality procedure must be consistent with eq?. That is, it must be the case that:
eq? x y) => (elt= x y). (
Note that this implies that two ilists which are eq? are always ilist=, as well; implementations may exploit this fact to “shortcut” the elementbyelement comparisons.
eq?) => #t ; Trivial cases
(ilist= eq? (iq a)) => #t (ilist=
(icar ipair)
(icdr ipair)
These procedures return the contents of the icar and icdr field of their argument, respectively. Note that it is an error to apply them to the empty ilist.
=> a (icdr (iq a b c)) => (b c)
(icar (iq a b c)) => (a) (icdr (iq (a) b c d)) => (b c d)
(icar (iq (a) b c d)) 1 2)) => 1 (icdr (ipair 1 2)) => 2
(icar (ipair => *error* (icdr '()) => *error* (icar '())
(icaar ipair)
(icadr ipair)
…
(icdddar ipair)
These procedures are compositions of icar and icdr, where for example icaddr could be defined by
define icaddr (lambda (x) (icar (icdr (icdr x))))) (
Arbitrary compositions, up to four deep, are provided. There are twentyeight of these procedures in all.
(ilistref ilist i)
Returns the ith element of ilist. (This is the same as the icar of (idrop ilist i).) It is an error if i >= n, where n is the length of ilist.
2) => c (ilistref (iq a b c d)
(ifirst ipair)
(isecond ipair)
(ithird ipair)
(ifourth ipair)
(ififth ipair)
(isixth ipair)
(iseventh ipair)
(ieighth ipair)
(ininth ipair)
(itenth ipair)
Synonyms for car, cadr, caddr, …
=> c (ithird '(a b c d e))
(icar+icdr ipair)
The fundamental ipair deconstructor:
lambda (p) (values (icar p) (icdr p))) (
This can, of course, be implemented more efficiently by a compiler.
(itake x i)
(idrop x i)
(ilisttail x i)
itake
returns the first i elements of ilist x.
idrop
returns all but the first i elements of ilist
x.
ilisttail
is either the same procedure as idrop or else
a procedure with the same behavior.
``scheme (itake (iq a b c d e) 2) => (a b) (idrop (iq a b c d e) 2) => (c d e)
x may be any value — a proper or dotted ilist:
```scheme
(itake (ipair 1 (ipair 2 (ipair 3 'd))) => (1 2)
(idrop (ipair 1 (ipair 2 (ipair 3 'd))) 2) => (3 . d)
(itake (ipair 1 (ipair 2 (ipair 3 'd))) 3) => (1 2 3)
(idrop (ipair 1 (ipair 2 (ipair 3 'd))) 3) => d
For a legal i, itake and idrop partition the ilist in a manner which can be inverted with iappend:
= x (iappend (itake x i) (idrop x i))
idrop is exactly equivalent to performing i icdr operations on x; the returned value shares a common tail with x.
(itakeright dilist i)
(idropright dilist i)
itakeright returns the last i elements of dilist. idropright returns all but the last i elements of dilist.
2) => (d e)
(itakeright (iq a b c d e) 2) => (a b c) (idropright (iq a b c d e)
The returned ilist may share a common tail with the argument ilist.
dilist may be any ilist, either proper or dotted:
1 (ipair 2 (ipair 3 'd))) 2) => (2 3 . d)
(itakeright (iq ipair 1 (ipair 2 (ipair 3 'd))) 2) => (1)
(idropright (ipair 1 (ipair 2 (ipair 3 'd))) 0) => d
(itakeright (ipair 1 (ipair 2 (ipair 3 'd))) 0) => (1 2 3) (idropright (ipair
For a legal i, itakeright and idropright partition the ilist in a manner which can be inverted with iappend:
= dilist (iappend (itake dilist i) (idrop dilist i))
itakeright’s return value is guaranteed to share a common tail with dilist.
(isplitat x i)
isplitat splits the ilist x at index i, returning an ilist of the first i elements, and the remaining tail. It is equivalent to
values (itake x i) (idrop x i)) (
(ilast ipair)
(lastipair ipair)
Returns the last element of the nonempty, possibly dotted, ilist ipair. lastipair returns the last ipair in the nonempty ilist pair.
=> c
(ilast (iq a b c)) => (c) (lastipair (iq a b c))
(ilength ilist)
Returns the length of its argument. It is an error to pass a value to ilength which is not a proper ilist (()terminated).
The length of a proper ilist is a nonnegative integer n such that icdr applied n times to the ilist produces the empty list.
(iappend ilist1 ...)
Returns an ilist consisting of the elements of ilist1 followed by the elements of the other ilist parameters.
=> (x y)
(iappend (iq x) (iq y)) => (a b c d)
(iappend (iq a) (iq b c d)) => (a (b) (c)) (iappend (iq a (b)) (iq (c)))
The resulting ilist is always newly allocated, except that it shares structure with the final ilisti argument. This last argument may be any value at all; an improper ilist results if it is not a proper ilist. All other arguments must be proper ilists.
=> (a b c . d)
(iappend (iq a b) (ipair 'c 'd)) => a
(iappend '() 'a) => (x y)
(iappend (iq x y)) => () (iappend)
(iconcatenate ilistofilists)
Appends the elements of its argument together. That is, iconcatenate returns
(iapply iappend ilistofilists)
or, equivalently,
(ireduceright iappend '() ilistofilists)
Note that some Scheme implementations do not support passing more than a certain number (e.g., 64) of arguments to an nary procedure. In these implementations, the (iapply iappend …) idiom would fail when applied to long lists, but iconcatenate would continue to function properly.
As with iappend, the last element of the input list may be any value at all.
(ireverse ilist)
Returns a newly allocated ilist consisting of the elements of ilist in reverse order.
=> (c b a)
(ireverse (iq a b c))
(ireverse (iq a (b c) d (e (f))))=> ((e (f)) d (b c) a)
(iappendreverse revhead tail)
iappendreverse returns (iappend (ireverse revhead) tail). It is provided because it is a common operation — a common listprocessing style calls for this exact operation to transfer values accumulated in reverse order onto the front of another ilist, and because the implementation is significantly more efficient than the simple composition it replaces. (But note that this pattern of iterative computation followed by a reverse can frequently be rewritten as a recursion, dispensing with the reverse and iappendreverse steps, and shifting temporary, intermediate storage from the heap to the stack, which is typically a win for reasons of cache locality and eager storage reclamation.)
(izip ilist1 ilist2 ...)
lambda ilists (iapply imap ilist ilists)) (
If izip is passed n ilists, it returns an ilist as long as the shortest of these ilists, each element of which is an nelement ilist comprised of the corresponding elements from the parameter ilists.
(izip (iq one two three)1 2 3)
(iq
(iq odd even odd even odd even odd even));; => ((one 1 odd) (two 2 even) (three 3 odd))
1 2 3)) => ((1) (2) (3)) (izip (iq
(iunzip1 ilist)
(iunzip2 ilist)
(iunzip3 ilist)
(iunzip4 ilist)
(iunzip5 ilist)
iunzip1 takes an ilist of ilists, where every ilist must contain at least one element, and returns an ilist containing the initial element of each such ilist. That is, it returns (imap icar ilists). iunzip2 takes an ilist of ilists, where every ilist must contain at least two elements, and returns two values: an ilist of the first elements, and an ilist of the second elements. iunzip3 does the same for the first three elements of the ilists, and so forth.
1 one) (2 two) (3 three))) =>
(iunzip2 (iq (1 2 3)
( (one two three)
(icount pred ilist1 ilist2 ...)
pred is a procedure taking as many arguments as there are ilists and returning a single value. It is applied elementwise to the elements of the ilists, and a count is tallied of the number of elements that produce a true value. This count is returned. count is “iterative” in that it is guaranteed to apply pred to the ilist elements in a lefttoright order. The counting stops when the shortest ilist expires.
even? (iq 3 1 4 1 5 9 2 5 6)) => 3
(count < (iq 1 2 4 8) (iq 2 4 6 8 10 12 14 16)) => 3 (count
(ifold kons knil ilist1 ilist2 ...)
The fundamental ilist iterator.
First, consider the single ilistparameter case. If ilist1 = (e1 e2 … en), then this procedure returns
... (kons e2 (kons e1 knil)) ... ) (kons en
That is, it obeys the (tail) recursion
= (ifold kons (kons (icar lis) knil) (icdr lis))
(ifold kons knil lis) = knil (ifold kons knil '())
Examples:
+ 0 lis) ; Add up the elements of LIS.
(ifold
; Reverse LIS.
(ifold ipair '() lis)
; See APPENDREVERSE.
(ifold ipair tail revhead)
;; How many symbols in LIS?
lambda (x count) (if (symbol? x) (+ count 1) count))
(ifold (0
lis)
;; Length of the longest string in LIS:
lambda (s maxlen) (max maxlen (stringlength s)))
(ifold (0
lis)
If n ilist arguments are provided, then the kons function must take n+1 parameters: one element from each ilist, and the “seed” or fold state, which is initially knil. The fold operation terminates when the shortest ilist runs out of values:
1 2 3 4 5)) => (c 3 b 2 a 1) (ifold ipair* '() (iq a b c) (iq
(ifoldright kons knil ilist1 ilist2 ...)
The fundamental ilist recursion operator.
First, consider the single ilistparameter case. If ilist1 = (e1 e2 … en), then this procedure returns
... (kons en knil))) (kons e1 (kons e2
That is, it obeys the recursion
= (kons (icar lis) (ifoldright kons knil (icdr lis)))
(ifoldright kons knil lis) = knil (ifoldright kons knil '())
Examples:
; Copy LIS.
(ifoldright ipair '() lis)
;; Filter the even numbers out of LIS.
lambda (x l) (if (even? x) (ipair x l) l)) '() lis)) (ifoldright (
If n ilist arguments are provided, then the kons procedure must take n+1 parameters: one element from each ilist, and the “seed” or fold state, which is initially knil. The fold operation terminates when the shortest ilist runs out of values:
1 2 3 4 5)) => (a 1 b 2 c 3) (ifoldright ipair* '() (iq a b c) (iq
(ipairfold kons knil ilist1 ilist2 ...)
Analogous to fold, but kons is applied to successive subilists of the ilists, rather than successive elements — that is, kons is applied to the ipairs making up the lists, giving this (tail) recursion:
= (let ((tail (icdr lis)))
(ipairfold kons knil lis)
(ipairfold kons (kons lis knil) tail))= knil (ipairfold kons knil '())
Example:
=> ((c) (b c) (a b c)) (ipairfold ipair '() (iq a b c))
(ipairfoldright kons knil ilist1 ilist2 ...)
Holds the same relationship with ifoldright that ipairfold holds with ifold. Obeys the recursion
=
(ipairfoldright kons knil lis)
(kons lis (ipairfoldright kons knil (icdr lis)))= knil (ipairfoldright kons knil '())
Example:
=> ((a b c) (b c) (c)) (ipairfoldright ipair '() (iq a b c))
(ireduce f ridentity ilist)
ireduce is a variant of ifold.
ridentity should be a “right identity” of the procedure f — that is, for any value x acceptable to f,
= x (f x ridentity)
ireduce has the following definition:
If ilist = (), return ridentity;
Otherwise, return (ifold f (icar ilist) (icdr ilist)).
…in other words, we compute (ifold f ridentity ilist).
Note that ridentity is used only in the emptylist case. You typically use ireduce when applying f is expensive and you’d like to avoid the extra application incurred when ifold applies f to the head of ilist and the identity value, redundantly producing the same value passed in to f. For example, if f involves searching a file directory or performing a database query, this can be significant. In general, however, ifold is useful in many contexts where ireduce is not (consider the examples given in the ifold definition — only one of the five folds uses a function with a right identity. The other four may not be performed with ireduce).
;; take the max of an ilist of nonnegative integers.
max 0 nums) ; i.e., (iapply max 0 nums) (ireduce
(ireduceright f ridentity ilist)
ireduceright is the foldright variant of ireduce. It obeys the following definition:
= ridentity
(ireduceright f ridentity '()) = (f e1 ridentity) = e1
(ireduceright f ridentity (iq e1)) ...)) =
(ireduceright f ridentity (iq e1 e2 ...))) (f e1 (ireduce f ridentity (e2
…in other words, we compute (ifoldright f ridentity ilist).
;; Append a bunch of ilists together.
;; I.e., (iapply iappend ilistofilists)
(ireduceright iappend '() ilistofilists)
(iunfold p f g seed [tailgen])
iunfold is best described by its basic recursion:
=
(iunfold p f g seed) if (p seed) (tailgen seed)
(
(ipair (f seed) (iunfold p f g (g seed))))
In other words, we use g to generate a sequence of seed values
... seed, g(seed), g2(seed), g3(seed),
These seed values are mapped to ilist elements by f, producing the elements of the result ilist in a lefttoright order. P says when to stop.
iunfold is the fundamental recursive ilist constructor, just as ifoldright is the fundamental recursive ilist consumer. While iunfold may seem a bit abstract to novice functional programmers, it can be used in a number of ways:
;; Ilist of squares: 1^2 ... 10^2
lambda (x) (> x 10))
(iunfold (lambda (x) (* x x))
(lambda (x) (+ x 1))
(1)
; Copy a proper ilist.
(iunfold nullilist? icar icdr lis)
;; Read current input port into an ilist of values.
eofobject? values (lambda (x) (read)) (read))
(iunfold
;; Copy a possibly nonproper ilist:
(iunfold notipair? icar icdr lisvalues)
;; Append HEAD onto TAIL:
(iunfold nullilist? icar icdr headlambda (x) tail)) (
Interested functional programmers may enjoy noting that ifoldright and iunfold are in some sense inverses. That is, given operations knull?, kar, kdr, kons, and knil satisfying
= x and (knull? knil) = #t (kons (kar x) (kdr x))
then
= x (ifoldright kons knil (iunfold knull? kar kdr x))
and
= x (iunfold knull? kar kdr (ifoldright kons knil x))
This combinator sometimes is called an “anamorphism;” when an explicit tailgen procedure is supplied, it is called an “apomorphism.”
(iunfoldright p f g seed [tail])
iunfoldright constructs an ilist with the following loop:
let lp ((seed seed) (lis tail))
(if (p seed) lis
(
(lp (g seed)
(ipair (f seed) lis))))
p
Determines when to stop unfolding.
f
Maps each seed value to the corresponding ilist element.
g
Maps each seed value to next seed value.
seed"state" value for the unfold.
The
tail; defaults to '(). ilist terminator
In other words, we use g to generate a sequence of seed values
... seed, g(seed), g2(seed), g3(seed),
These seed values are mapped to ilist elements by f, producing the elements of the result ilist in a righttoleft order. P says when to stop.
iunfoldright is the fundamental iterative ilist constructor, just as ifold is the fundamental iterative ilist consumer. While iunfoldright may seem a bit abstract to novice functional programmers, it can be used in a number of ways:
;; Ilist of squares: 1^2 ... 10^2
zero?
(iunfoldright lambda (x) (* x x))
(lambda (x) ( x 1))
(10)
;; Reverse a proper ilist.
(iunfoldright nullilist? icar icdr lis)
;; Read current input port into an ilist of values.
eofobject? values (lambda (x) (read)) (read))
(iunfoldright
;; (iappendreverse revhead tail)
(iunfoldright nullilist? icar icdr revhead tail)
Interested functional programmers may enjoy noting that ifold and iunfoldright are in some sense inverses. That is, given operations knull?, kar, kdr, kons, and knil satisfying
= x and (knull? knil) = #t (kons (kar x) (kdr x))
then
= x (ifold kons knil (iunfoldright knull? kar kdr x))
and
= x. (iunfoldright knull? kar kdr (ifold kons knil x))
This combinator presumably has some pretentious mathematical name; interested readers are invited to communicate it to the author.
(imap proc ilist1 ilist2 ...)
proc is a procedure taking as many arguments as there are ilist arguments and returning a single value. imap applies proc elementwise to the elements of the ilists and returns an ilist of the results, in order. The dynamic order in which proc is applied to the elements of the ilists is unspecified.
=> (b e h)
(imap icadr (iq (a b) (d e) (g h)))
lambda (n) (expt n n))
(imap (1 2 3 4 5))
(iq => (1 4 27 256 3125)
+ (iq 1 2 3) (iq 4 5 6)) => (5 7 9)
(imap
let ((count 0))
(lambda (ignored)
(imap (set! count (+ count 1))
(
count)=> (1 2) or (2 1) (iq a b)))
(iforeach proc ilist1 ilist2 ...)
The arguments to iforeach are like the arguments to imap, but iforeach calls proc for its side effects rather than for its values. Unlike imap, iforeach is guaranteed to call proc on the elements of the ilists in order from the first element(s) to the last, and the value returned by iforeach is unspecified.
let ((v (makevector 5)))
(lambda (i)
(iforeach (vectorset! v i (* i i)))
(0 1 2 3 4))
(iq => #(0 1 4 9 16) v)
(iappendmap f ilist1 ilist2 ...)
Equivalent to
...)) (iapply iappend (imap f ilist1 ilist2
and
...)) (iapply iappend (imap f ilist1 ilist2
Map f over the elements of the ilists, just as in the imap function. However, the results of the applications are appended together (using iappend) to make the final result.
The dynamic order in which the various applications of f are made is not specified.
Example:
lambda (x) (ilist x ( x))) (iq 1 3 8))
(iappendmap (;; => (1 1 3 3 8 8)
(imapinorder f ilist1 ilist2 ...)
A variant of the imap procedure that guarantees to apply f across the elements of the ilisti arguments in a lefttoright order. This is useful for mapping procedures that both have side effects and return useful values.
(ipairforeach f ilist1 ilist2 ...)
Like iforeach, but f is applied to successive subilists of the argument ilists. That is, f is applied to the cells of the ilists, rather than the ilists’ elements. These applications occur in lefttoright order.
lambda (ipair) (display ipair) (newline)) (iq a b c)) ==>
(ipairforeach (
(a b c)
(b c) (c)
(ifiltermap f ilist1 ilist2 ...)
Like imap, but only true values are saved.
lambda (x) (and (number? x) (* x x))) (iq a 1 b 3 c 7))
(ifiltermap (=> (1 9 49)
The dynamic order in which the various applications of f are made is not specified.
(ifilter pred ilist)
Return all the elements of ilist that satisfy predicate pred. The ilist is not disordered — elements that appear in the result ilist occur in the same order as they occur in the argument ilist. The returned ilist may share a common tail with the argument ilist. The dynamic order in which the various applications of pred are made is not specified.
even? (iq 0 7 8 8 43 4)) => (0 8 8 4) (ifilter
(ipartition pred ilist)
Partitions the elements of ilist with predicate pred, and returns two values: the ilist of inelements and the ilist of outelements. The ilist is not disordered — elements occur in the result ilists in the same order as they occur in the argument ilist. The dynamic order in which the various applications of pred are made is not specified. One of the returned ilists may share a common tail with the argument ilist.
symbol? (iq one 2 3 four five 6)) =>
(ipartition
(one four five)2 3 6) (
(iremove pred ilist)
Returns ilist without the elements that satisfy predicate pred:
lambda (pred ilist) (ifilter (lambda (x) (not (pred x))) ilist)) (
The ilist is not disordered — elements that appear in the result ilist occur in the same order as they occur in the argument ilist. The returned ilist may share a common tail with the argument ilist. The dynamic order in which the various applications of pred are made is not specified.
even? (iq 0 7 8 8 43 4)) => (7 43) (iremove
(ifind pred ilist)
Return the first element of ilist that satisfies predicate pred; false if no element does.
even? (iq 3 1 4 1 5 9)) => 4 (ifind
Note that ifind has an ambiguity in its lookup semantics — if ifind returns #f, you cannot tell (in general) if it found a #f element that satisfied pred, or if it did not find any element at all. In many situations, this ambiguity cannot arise — either the ilist being searched is known not to contain any #f elements, or the ilist is guaranteed to have an element satisfying pred. However, in cases where this ambiguity can arise, you should use ifindtail instead of ifind — ifindtail has no such ambiguity:
cond ((ifindtail pred lis) => (lambda (ipair) ...)) ; Handle (icar ipair)
(else ...)) ; Search failed. (
(ifindtail pred ilist)
Return the first ipair of ilist whose icar satisfies pred. If no ipair does, return false.
ifindtail can be viewed as a generalpredicate variant of the imember function.
Examples:
even? (iq 3 1 37 8 5 0 0)) => (8 5 0 0)
(ifindtail even? (iq 3 1 37 5)) => #f
(ifindtail
;; IMEMBER X LIS:
lambda (elt) (equal? x elt)) lis) (ifindtail (
iqfindtail is essentially idropwhile, where the sense of the predicate is inverted: Ifindtail searches until it finds an element satisfying the predicate; idropwhile searches until it finds an element that doesn’t satisfy the predicate.
(itakewhile pred ilist)
Returns the longest initial prefix of ilist whose elements all satisfy the predicate pred.
even? (iq 2 18 3 10 22 9)) => (2 18) (itakewhile
(idropwhile pred ilist)
idrops the longest initial prefix of ilist whose elements all satisfy the predicate pred, and returns the rest of the ilist.
even? (iq 2 18 3 10 22 9)) => (3 10 22 9) (idropwhile
(ispan pred ilist)
(ibreak pred ilist)
ispan splits the ilist into the longest initial prefix whose elements all satisfy pred, and the remaining tail. ibreak inverts the sense of the predicate: the tail commences with the first element of the input ilist that satisfies the predicate.
In other words: ispan finds the initial span of elements satisfying pred, and ibreak breaks the ilist at the first element satisfying pred.
ispan is equivalent to
values (itakewhile pred ilist)
(
(idropwhile pred ilist))
even? (iq 2 18 3 10 22 9)) =>
(ispan 2 18)
(3 10 22 9)
(
even? (iq 3 1 4 1 5 9)) =>
(ibreak 3 1)
(4 1 5 9) (
(iany pred ilist1 ilist2 ...)
Applies the predicate across the ilists, returning true if the predicate returns true on any application.
If there are n ilist arguments ilist1 … ilistn, then pred must be a procedure taking n arguments and returning a boolean result.
iany applies pred to the first elements of the ilisti parameters. If this application returns a true value, iany immediately returns that value. Otherwise, it iterates, applying pred to the second elements of the ilisti parameters, then the third, and so forth. The iteration stops when a true value is produced or one of the ilists runs out of values; in the latter case, iany returns #f. The application of pred to the last element of the ilists is a tail call.
Note the difference between ifind and iany — ifind returns the element that satisfied the predicate; iany returns the true value that the predicate produced.
Like ievery, iany’s name does not end with a question mark — this is to indicate that it does not return a simple boolean (#t or #f), but a general value.
integer? (iq a 3 b 2.7)) => #t
(iany integer? (iq a 3.1 b 2.7)) => #f
(iany < (iq 3 1 4 1 5)
(iany 2 7 1 8 2)) => #t (iq
(ievery pred ilist1 ilist2 ...)
Applies the predicate across the ilists, returning true if the predicate returns true on every application.
If there are n ilist arguments ilist1 … ilistn, then pred must be a procedure taking n arguments and returning a boolean result.
ievery applies pred to the first elements of the ilisti parameters. If this application returns false, ievery immediately returns false. Otherwise, it iterates, applying pred to the second elements of the ilisti parameters, then the third, and so forth. The iteration stops when a false value is produced or one of the ilists runs out of values. In the latter case, ievery returns the true value produced by its final application of pred. The application of pred to the last element of the ilists is a tail call.
If one of the ilisti has no elements, ievery simply returns #t.
Like iany, ievery’s name does not end with a question mark — this is to indicate that it does not return a simple boolean (#t or #f), but a general value.
(ilistindex pred ilist1 ilist2 ...)
Return the index of the leftmost element that satisfies pred.
If there are n ilist arguments ilist1 … ilistn, then pred must be a function taking n arguments and returning a boolean result.
ilistindex applies pred to the first elements of the ilisti parameters. If this application returns true, ilistindex immediately returns zero. Otherwise, it iterates, applying pred to the second elements of the ilisti parameters, then the third, and so forth. When it finds a tuple of ilist elements that cause pred to return true, it stops and returns the zerobased index of that position in the ilists.
The iteration stops when one of the ilists runs out of values; in this case, ilistindex returns #f.
even? (iq 3 1 4 1 5 9)) => 2
(ilistindex < (iq 3 1 4 1 5 9 2 5 6) (iq 2 7 1 8 2)) => 1
(ilistindex = (iq 3 1 4 1 5 9 2 5 6) (iq 2 7 1 8 2)) => #f (ilistindex
(imember x ilist [=])
(imemq x ilist)
These procedures return the first subilist of ilist whose icar is x, where the subilists of ilist are the nonempty ilists returned by (idrop ilist i) for i less than the length of ilist. If x does not occur in ilist, then #f is returned. imemq uses eq? to compare x with the elements of ilist, while imemv uses eqv?, and imember uses equal?.
(imemq 'a (iq a b c)) => (a b c)
(imemq 'b (iq a b c)) => (b c)
(imemq 'a (iq b c d)) => #f
(imemq (list 'a)
(ilist 'b '(a) 'c)) => #f
(imember (list 'a)
(ilist 'b '(a) 'c))) => ((a) c)
(imemq 101 (iq 100 101 102)) => *unspecified*
(imemv 101 (iq 100 101 102)) => (101 102)
The comparison procedure is used to compare the elements ei of ilist to the key x in this way:
= x ei) ; ilist is (E1 ... En) (
That is, the first argument is always x, and the second argument is one of the ilist elements. Thus one can reliably find the first element of ilist that is greater than five with (imember 5 ilist <)
Note that fully general ilist searching may be performed with the ifindtail and ifind procedures, e.g.
even? ilist) ; Find the first elt with an even key. (ifindtail
(idelete x ilist [=])
idelete uses the comparison procedure =, which defaults to equal?, to find all elements of ilist that are equal to x, and deletes them from ilist. The dynamic order in which the various applications of = are made is not specified.
The ilist is not disordered — elements that appear in the result ilist occur in the same order as they occur in the argument ilist. The result may share a common tail with the argument ilist.
Note that fully general element deletion can be performed with the iremove procedures, e.g.:
;; idelete all the even elements from LIS: