# embeddings_queue

created_at: 2024-04-29 18:33:01
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed handwritten notes from an image7
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Cas is all too often done\n'well, it works on o ... it works on 6 => therefore it works'.\n\nWhat we can gain from program proving is greatly increased confidence that our programs work.\n\nFor the fact program - there are a number of distinct factors which might make for errors\n1 -> the algorithm might be wrong\n2 -> the Bignum library implementing schemes in infinite precisions of integer arithmetic might be flawed"}


created_at: 2024-04-29 18:33:10
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing potential flaws and assumptions in a system8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "scheme itself might be flawed\n\nThe Operating System might be flawed\n\nThe chips might be flawed\n\nWe will assume 2...5 do not occur - everything but the algorithm will be assumed to work correctly\n\nWhat we'll get\n\ntesting glasses\n\nsoftware\n\nproving glasses\n\nboth are necessary\n\nneither is sufficient"}


created_at: 2024-04-29 18:33:26
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten notes discussing the mathematical concept of recursion, specifically applied to the factorial function.9

metadata:
{"source": "pdf", "chroma:document": "Let's take another look at the recursive version of factorial.\n\nStart from the(math) definition of the factorial:\n\nn! = { 1 if n = 0\n      { n x (n-1)! otherwise\n\nAssumptions: n >= 0 and n is an integer\n\nWhy isn't this a circular definition? After all it defines 'n!' in terms of ' (n-1)!' . The reason is that this is an inductive definition.\n\nCircularity avoided by making good use of the natural metric on non-neg. integers\n\nHere n! is defined in terms of something smaller than n -- i.e. (n-1)! \n\nWe have no ground - or basis - case\n\n(Always those cases for which the induction is not necessary).\n\nThe working assumption is that (n-1)! is defined."}


created_at: 2024-04-29 18:33:38
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Description of the diagram and code related to mathematical or programming concepts10
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "\"first layer of unknown space\" \"known space\" n n-1 ... : n=0 Basis (ground) or wish or induction hypothesis . IS (induction step) IH (induction hypothesis) The scheme version is just a recasting of the function definition The goal of this case is to show that Define (fact n) pre: n >= 0 \u2227 n is an integer our program fact correctly computes factorial all n! ie (fact n) post: (fact n = n!) A correctness proof in this course is (cond ((zero? n) 1) (else (* n (fact (- n 1)))))"}


created_at: 2024-04-29 18:33:50
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Transcribed text from an image containing handwritten notes on program correctness and termination arguments.11

metadata:
{"source": "pdf", "chroma:document": "given in two parts:\n-> partial correctness\n   \"if the program terminates, it gives the correct answer\"\n-> termination argument\n   \"the program really does return an answer\"\nThis is where we deploy induction -> will usually be satisfied with a hand-waving argument\nAssuming that scheme works as advertized\nIn this case: The program starts with input n > 0. Because n is an integer, 1 can be subtracted infinitely many times before reaching 0 at which point the execution halts.\nThe induction argument\n-> First: what are we inducting on?\n   We'll induct on n"}


created_at: 2024-04-29 18:34:03
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing mathematical induction and descending chains12
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Induction on n depends on n>=0 being an integer.\n\nIf we're doing induction, we need a well-founded set; there can be no infinite descending chains so we can't induct on\n-one cannot induct on real numbers\n-one cannot induct on the set of all integers\n\n... -10 -9 -8 ... -1 0 1 2 ...\n\nThere are infinite descending chains\n\nWhat is an example of an infinite descending chain of real numbers between 0 and 1?\n\nSecond, how are we decomposing the problem? Essentially: what is the IH?\n\nFor most programs, the IH -- to a first approximation -- is \"we assume that the recursive call works.\""}


created_at: 2024-04-29 18:34:13
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Sample handwritten notes discussing a recursive function for factorial calculation13
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "This isn't quite enough - a better approximation is\n'We assume that if the precondition is satisfied, then the recursive call works'\n\npre: n >= 0 AND n is an integer\n(define (fact n)\n  (cond [(zero? n) 1]\n        [else (* n (fact (- n 1)))]\n  )\n)\npost: fact n = n!\n\nLet's see: we know n >= 0\nstat(zero? n) is false\nHence: n > 0 hence n-1 >= 0"}


created_at: 2024-04-29 18:34:27
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a transcription of handwritten notes discussing mathematical or programming concepts, especially focusing on the correctness or steps in a process involving factorials.14

metadata:
{"source": "pdf", "chroma:document": "c we'd also need to say that n-1 is an integer, but this is immediate from the fact that n is an integer.\n\nThird, we need to give the inductive step\u2014i.e., we need to show that the program does the right thing with the value (n-1) returned by the call. Here (n-1)! is multiplied by n \u2014 which, according to the def of a factorial function \u2014 gives n!."}


created_at: 2024-04-29 18:34:39
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten note discussing observations in an argument and explaining a concept alongside examples.15

metadata:
{"source": "pdf", "chroma:document": "It is important to observe what isn't done in this argument as well as to observe what is done.\nNote that there is NOTHING like the pattern of calls expansion \u2014 nothing like\n(fact n) calls\n(fact (n-1))\ncalls\n(fact (n-2))\n...\nand so on until 0\nHere\u2019s the giveaway: The ellipsis\nRule of thumb\nIf your argument proceeds by induction"}


created_at: 2024-04-29 18:34:48
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes on a lined notebook page16
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "\"unwinding\" the recursion to an indefinite extent as shown by the ellipsis $\textellipsis$ then it is \textbf{NOT} an induction. Induction - properly used - is the most powerful software engineering tool that exists. One simple argument replaces an unbounded number of unwindings... The induction argument \textbf{MUST} make use of the induction hypothesis - the unwinding args have no induction hypothesis"}


created_at: 2024-04-29 18:34:56
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten note about a concept in software engineering17
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "In the context of software engineering\nthe it amounts to a black box\nwhich is assumed to magically\nsolve the smaller problem."}


created_at: 2024-04-29 18:35:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten notes explaining the iterative factorial function along with example code and a table illustrating function calls and outcomes.0

metadata:
{"source": "pdf", "chroma:document": "Intro to Invariants - Proving Iterative Factorial\n\nRecall\n(define (fact-iter n count result)\n  (cond ((= count n) result)\n    (else (fact-iter n (+ count 1) (* (+ count 1) result))))\n)\n(define (fact n)\n  (fact-iter n 0 1))\n\nPattern of calls \u2014 useful clue to the proof \u2014 laid out in a table with formal parameters as column headings:\n\nn      count     result\n6      0         1\n6      1         1\n6      2         2\n6      3         6\n6      4         24\n6      5         120\n6      6         720\n\nShowing values each time fact-iter is called\n\nOn this call, the stopping test passes. So 720 is returned."}


created_at: 2024-04-29 18:35:35
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed text from the provided handwritten image1
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "The clue we seek is the pattern; at each call, \nresult = count! For the first call\n1 = 0! For the second\n1 = 1! for the third\n2 = 2!\n6 = 3! etc\n\nSo we can see that this equation is true each time fact_iter is called.\n\nWe say that the equation - a relation among (some of) the program\u2019s variables - is INVARIANT.\n\nHow does this help us prove that the program is correct?\n- If the invariant holds each time fact_iter is called, then it holds the last time fact_iter is called.\n- According to the code, count = n the last time fact_iter is called, and when this is true, the value of result is returned."}


created_at: 2024-04-29 18:35:51
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a transcription of handwritten notes possibly discussing a mathematical or programming topic.2

metadata:
{"source": "pdf", "chroma:document": "-> BUT if result = count! and count = n, This means that result = n! : the correct value is returned.\n Hey - aren't you getting ahead of yourself? I mean; we did this for n = 6, not for general n.\n Of course - The expansion for n = 6 provides only a clue as to the invariant. We need to do some more work to conclude that result = count! really is invariant, no matter the input. (given that pre is satisfied!)\n So let's consider the more general situation - still for factorial, but now for an arbitrary integer n >= 0."}


created_at: 2024-04-29 18:36:03
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed text from a handwritten image discussing programming invariants3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "An invariant is a relation among a program's variables.\nHere are some 'invariant-like' creatures which are NOT what we need:\n\n7\n?\nn = 6\n\nNone of these help to prove that the program worked. Specifically, we need\n\nIs it the case that\n\nif  A (count = n)\n              =>\n   result = n\n\n?? What about\n\nif (n = 6) \u2227 (count = n) => (result = n)\n\n?? Neither of these is a valid implication.\n\nWe will say that none of these Guess-Invariants (CGI) is STRONG ENOUGH."}


created_at: 2024-04-29 18:36:12
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing programming concepts4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "In the same vein\n\nI != 1\n\n(while invariant in the dictionary sense) != not an invariant we can use;\n\nC!=1) \u2227 (stopping-cond) \u21d2 post-cond;\n\nIntuitively - the problem with all of these is that they do not mention (enough of) the program's variables.\n\nFirst test for a GJ: is it strong enough Heuristic guidance i.e. it needs to talk about the program's variables\n\n(to imply the post-condition when logically ANDed with the stopping condition?)"}


created_at: 2024-04-29 18:36:24
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on the topic of invariants in programming or logic.5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Important property of invariants:\nInvariants are RELATIONS - They are NOT action statements. They are static assertions - in standard logic - about variables' values. They DO NOT REFER TO TIME. (No reference to \"old\" or \"new\" variable values)\n\nWe've seen that a guess/invariant can be too weak. Can it be too strong? For example, why not just take\n\nresult = n!\nas the GI? Well, This relation among variables, is NOT achieved by our initialization.\n\nWe have (define (fact n)\n  (fact-iter n 0 1))\nand clearly it's not the case that 1 \u2260 n!\nin most cases"}


created_at: 2024-04-29 18:36:44
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten note discussing the considerations for an invariant in a programming context.6

metadata:
{"source": "pdf", "chroma:document": "So: second test for a GI is that it must be weak enough to be achieved (made true) by the code the first time the looping function (here fact_test) is called.\n\nWhat we're working up to here is an induction proof that the invariant is true on each call of the looping function. We are setting up an induction on the number of calls to the looping function.\n\nNOTE: that this is different from what we did for recursive factorial. In that case, the invariant was on the data (n), not on the number of calls.\n\namounts to the basis step."}


created_at: 2024-04-29 18:36:57
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains handwritten notes possibly extracted from a mathematics or computer science study regarding recursive functions and mathematical induction.7

metadata:
{"source": "pdf", "chroma:document": "OUR IH: assume the GI was true for the current call. GI becomes I after it passes our tests. Our IS: show that the GI is true for the next call. We have (define (fact-iter n count result) (cond ((= count n) result) (else (fact-iter n (+ count 1) (* (+ count 1) result))))) We don\u2019t know the area of no parameter updates - and the GI might be broken mid-stream, e.g. after this update but before the last update. The beauty is that we do NOT care about midstream: all that matters is"}


created_at: 2024-04-29 18:37:05
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed handwritten mathematical and logical explanation8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Showing this is just a standard logic implication. Specifically we need that the invariant has been re-established by next call to fact. Iter. count! = result => (count+1)! = (count+1) * result and this is true by basic algebra and the def of factorial. This is the third test for a GI : is it preserved true? (i.e., that the parameter updates preserve invGT)"}


created_at: 2024-04-29 18:37:15
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing tests, ideas, and goals related to logic in coding9
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Assuming that all three tests\n-> strong enough?\n-> weak enough?\n-> preserved?\nare passed, the GI is promoted to T.\n\nwe still need to give a termination\nargument to complete the proof,\n\nMuch more to come! Our ultimate goal is to\nuse the logic during the coding process,\nnot merely to retrofit logic to existing\ncode."}


created_at: 2024-04-29 18:37:29
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains handwritten notes and schematics related to computer science concepts, specifically about lambda calculus and procedures as returned values in programming.0

metadata:
{"source": "pdf", "chroma:document": "CSC 335 Class 13 Part 2 - March 14 2024\n\n(ref. to Abelson & Sussman)\n; Section 1.3.4 Procedures as Returned Values\n\n(define (make-addConstant x)\n  (lambda (y) (+ x y)))\n\n((make-addConstant 4) 5)\n\n(define add4 (make-addConstant 4))\n(add4 3)\n\nThis is a closure\nenvironment model simulation\nevaluation of (make-addConstant 4)\nneeds now to be evaluated in the new-frame\nThis is the value resulting from evaluation of\n((lambda (y) (+ x y))"}


created_at: 2024-04-29 18:37:41
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten text discussing memory management concepts in programming.1
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Might expect the frame x would be garbage once the evaluation is complete \u2014 but this does not happen because x is (indirectly) pointed at by an object \u2014 and A \u2014 at the top level. We say that x is live. Recall that an environment is defined to be a sequence of frames \u2014 so the addA object (or just addA) has a 2-frame environment. Let's figure out what happens when we evaluate (addA 3)."}


created_at: 2024-04-29 18:37:50
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Description of a programming function simulation written on a lined notebook2
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "A look at (The simulation of) (add4 3):\nmake-add(Constant)\nadd4 .\n(add4 3)\n\nAs above\n\ncontaining frame\nis The frame\npointed at by\nThe closure\nobject, not\nthe frame\nin which\nthe call\nis made.\n\nx: 4\n(+ x y)\ny: 3\n(+ x y) giving 7\n\nThe garbage collector will\nnext remove the frame\nin which y is bound to\n3."}


created_at: 2024-04-29 18:38:05
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed text from a handwritten note explaining programming concepts3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "; curried form of sigma (currying a function)\n\n(define (curried-sigma-term)\n  (define (sum-term a b)\n    (cond ((> a b) 0)\n          (else (+ (term a) (sum-term (+ a 1) b))))\n  sum-term)\n\n((curried-sigma (lambda (x) x)) 1 10)\n\n(define sum-of-squares\n  (curried-sigma (lambda (x) (* x x))))\n\n(sum-of-squares 1 10) .\n\n; contrast to\n\n(sigma (lambda (x) (* x x)) 1 10)\n\n;An uncurried sigma in which the term parameter must be passed explicitly.\n\nInteresting for a couple of reasons - 1) it allows another level of code reuse. 2) It can facilitate efficiency by setting up partial compilation; 3) It suggests that in principle - we only need single-argument functions - function specializing."}


created_at: 2024-04-29 18:38:14
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains computer code written in Scheme language along with flowchart elements demonstrating functions and their recursive operations.4

metadata:
{"source": "pdf", "chroma:document": "(define (curried-sigma term)\n  (define (sum-term a b)\n    (cond ((> a b) 0)\n          (else (+ (term a) (sum-term (+ a 1) b))))\n    sum-term)\n\n(define-sigma (curried-sigma (lambda (x) x)))\n\n(sigma 1 3)"}


created_at: 2024-04-29 18:38:22
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: List of suggested exercises5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "suggested exercises\n\n- cook with curry on your own -> i.e -> Try your hand at currying a function or two\n\n- See if you can work out the environment diagram simulation for curried-signature"}


created_at: 2024-04-29 18:38:37
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: The image contains handwritten mathematical notes about derivatives and code.6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "close with an example from A&S hinting at the usefulness of having functions as values.\n\n(define (deriv f)\n(let ((dx 0.00000001))\n(lambda (x) ((f (+ x dx)) - (f x)) / dx)))\n\n(define (cube x) (* x x x))\n\n((deriv cube) 5)\n\nThe value returned is lambda(x)\n\n(f (x + dx) - f(x) ) / dx\n\nwhere dx is .0000001\n\nso (deriv cube) gives the function of x\n\n(cube (x + dx) - cube(x)) / dx\n\nwhich you recognize as the difference quotient for cube.\n\nRecall: deriv of cube at the point x\n\nlim cube (x + \u0394x) - cube(x)\n\u0394x->0           \u0394x\n\nIn calculus derivatives are functions -\nand suppose a language in which\nthis can be expressed directly."}


created_at: 2024-04-29 18:38:52
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Lecture notes from CSC 335 class on March 14, 2024, including definitions and guidelines for handling S-expressions as taught in the context of the course.0

metadata:
{"source": "pdf", "chroma:document": "CSC 335 Class 14 March 14 2024\n\nAbbreviation for The Little Schemer - see the syllabus.\nTLS - go ahead and start working through Chapters 1-6\nAtS - see Chapter 2\n\nS-expressions\n\nAn inductive definition in BNF (Backus-Naur form) for the class of S-exps is\nsexp ::= atom | '(' sexp ... sexp ')'\n\nIn traditional math form, this definition might be given as follows:\nThe class of Sexps over {a, b} is the least class containing the atoms a and b, as well as the empty list, which is closed when the operation of forming finite lists."}


created_at: 2024-04-29 18:39:03
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains handwritten notes and diagrams related to class definitions and data structures.1

metadata:
{"source": "pdf", "chroma:document": "We can understand these definitions by looking at them as recipes for generating the class of s-exps over {a,b}. Remember our onions: finite lists of elements drawn from layers inside of this one. The class s-exp contains the class listT. Since these BNF definitions are a big deal going forward, possibly ((a b), ((a))) c))"}


created_at: 2024-04-29 18:39:16
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes2
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Let's look at an exercise for practice. The question is: Is list ::= atom | ( atom ... atom ), where atom ::= a | b, a \"good\" definition of the class of lists over {a, b}? What do we mean by \"good\"? There are two criteria, -> soundness (i.e. is every object produced by the recipe actually a list over {a, b}?), -> completeness (i.e. is every list over {a, b} produced by this recipe?). I think you can see intuitively that * is not complete: There appears to be no way of generating - e.g., any list which contains non-empty sublists."}


created_at: 2024-04-29 18:39:29
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes on a green-lined paper3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Strongly suggested: prove - by structural induction - that (*) does not generate lists with non-empty sublists.\n\nHint: How can the IH be applied? The key is to recognize that some list (e1, e2, ... ek) is generated by * only if e1, and e2, and ... ek are generated by *.\n\nWhat about soundness? It certainly appears that every object generated by * is a list over {a, b}. But how could we prove this? It's very helpful to use a pictorial representation of lists - at this point, we will focus entirely on Scheme lists.\n\nThese pictorial reps are called box and pointer diagrams - you can find these discussed in chz of t4s."}


created_at: 2024-04-29 18:39:38
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Descriptive text and diagram details related to cons cells in computer programming.4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "The basic building block of a box and pointer diagram is the cons cell. A cons cell is an assembly of two addresses (pointers).\ncons cell\n car pointer\n cdr pointer\nTraditional terms from the original Lisp - late 1950s 'contents address register' 'address decrement register'\nA scheme list can be assembled using cons, which is a primitive. For example, the list (a b), boxed and pointed as\na -> b -> ()"}


created_at: 2024-04-29 18:39:50
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on programming concepts involving symbolic data and quoting5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "can be defined\n\n(define l1 (cons 'a (cons 'b '())))\n\nAside on quotation\n\n'a is shorthand for (quote a)\n\n\u2192 Quote and ' are primitives\n\n\u2192 Their role is to block evaluation; if you enter a (without a quote, and without having previously defined it), you\u2019ll get an unbound variable error. But 'a just returns the symbol - a\n\nIn other words, quote gives Scheme a means for dealing with symbolic data -\n\nWhen working broadly in LCS, you will need to add quote marks ahead of their symbols.\n\nBack to cons..."}


created_at: 2024-04-29 18:40:00
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: This is a handwritten note involving code and diagrams explaining list constructions in Lisp.6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "(define l1 (cons 'a (cons 'b '()))) \nIf we take this apart - say \n\n(define l2 (cons 'b '())) \n\nl2 ---> [] ---> () \n            b\n\nand then\n\n(define l3 (cons 'a l2)) \n\nl3 ---> [] ---> l2 \n            a              ---> [] ---> () \n                               b\n\nwhich is"}


created_at: 2024-04-29 18:40:16
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten note discussing memory allocation in programming, specifically using cons cells in Scheme.7

metadata:
{"source": "pdf", "chroma:document": "Q3 -> [  ] -> [  ] -> [  ]  a     b     c  You can only have: are Q1 and Q3 \"the same\"?  The answer may be a bit surprising, because cons allocates new memory it is called. In fact, following the sequence of definitions just shown, we would have Q1 -> [  ] -> [  ] -> [  ] a     b     c Q2 -> [  ] -> [  ] -> [  ]            a b Q3 -> [  ] -> [  ]              a      b atoms and the empty list are unique in Scheme. There is only one '() and only one '()'"}


created_at: 2024-04-29 18:40:28
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Notes on programming concepts related to equality tests in Scheme8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "scheme has two equally parts of particular interest to us - equal? and eq?\n\nIf you experiment with this stuff, you will find\n\n(equal? l l3) == #t\n\n[Same logical structure]\n\n(eq? l l3) == #f\n\n[Physically different addresses]\n\nGoing a bit further, you'll see that\n\n(eq? (car l) (car l3)) == #t\n\nhow to eval? Assuming that the value of l is a cons cell\n\n(car l) returns the value pointed at by the car pointer of that cell"}


created_at: 2024-04-29 18:40:39
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten note discussing concepts related to data structures or programming, possibly in the context of a computer science class.9

metadata:
{"source": "pdf", "chroma:document": "For datatypes, we will have constructors and selectors (and maybe classifiers as well). For the pair structures in Scheme, the constructor is cons and the selectors are car and cdr. Not all pair structures are lists! (will come back) We've seen that we can extract a as (car l) l-> [a]-> [t]->() a b How about extracting b? We'd get b via function composition: (cdr l) = (b) l.e -> [a]->[b]->() b"}


created_at: 2024-04-29 18:40:49
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Notes and handwriting involving coding concepts10
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "(car (cdr l)) = 6\nA scheme list - in terms of B&P diagrams - is any cons-cell structure with a \"list backbone\" whose rightmost cdr is ().\n\nscheme object1 -> scheme object2 -> ... -> scheme objectk\n\nwhich displays as\n\n(so1 so2 ... soK)\n\nOn the other hand, (cons 'a 'b) is the structure"}


created_at: 2024-04-29 18:41:10
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten lecture notes from a computer science class.0
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "CSC 335 Class 15 March 19 2024\n\nSome more on cons-cell structures, let's start with an example.\n\nSuppose we have the list (I (had (bread and (peanuts (and yoghurt)))) (for (lunch))).\n\nHow could this list be defined? How can components of the list be accessed? What is the Scheme representation of this list?\n\nIt would be error-prone to try to enter the list directly, all at once, from the keyboard. Better to do it one component at a time.\n\n(define l4 (list 'peanuts\n                 (list 'and 'yoghurt)))\n\nSets up in memory\n\nl4 -> [  ] -> [  ] -> ()\n      peanuts      [  ] -> ()\n                      yoghurt"}


created_at: 2024-04-29 18:41:20
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten text related to programming constructs and examples1
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Although list (the primitive constructor) is convenient, there are other ways of building QA. \n(define QA (cons 'peanuts (list (list 'and 'yoghurt)))) \nand \n(define QA (cons 'peanuts (cons (list 'and 'yoghurt) ()))) \nand \n(define QA (cons 'peanuts (cons 'and (cons 'yoghurt ()))))) \nThis last form exposes the underlying structure of QA as shown above. We can use the"}


created_at: 2024-04-29 18:41:32
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on programming concepts2
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "B&P diagram to understand how to access components of QA. Suppose, for example, that we wish to extract the component and using the datatype selectors car and cdr. Following pointer arrows in the B&P diagram, we see (car (car (cdr QA))) = 'c' and Shorthand: (caadr QA) Recall: cons allocates a fresh cons-cell. If we had (define num1 (list 2 3)) then (define num2 (cons 1 (list 2 3))) returns num2 -> num1 -> 1 written out, this would be"}


created_at: 2024-04-29 18:41:41
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes about programming concepts3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "num2 \u2192 num1\n1 \u2192 2 \u2192 3 \u2192 ())\n\nC Reminder - no need to quote numbers, as they are self-evaluating.\n\nThis is the idea for showing soundness of list;; atom (atom ... atom)\n\nAssuming lists are built using cons and recalling that lists are built from flat cars-cell backbones with rightmost cdr\n\nThe empty list - you can see that consing an atom to a list of atoms again returns a list.\n\nBack to Q4 - to type it in directly, one could use quote \n(Define Q4 '(Peanuts (and Yoghourt)))"}


created_at: 2024-04-29 18:41:52
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten programming notes4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Note, however, that\n\n(define RL '( (peanuts (list and yoghurt)) ) )\nreturns\n\n(peanuts (list and yoghurt))\n\nunevaluated due to the quote.\n\nExercise: Figure out additional components of\nRL and then how to define RL (Z)\nDraw RL and access various components\nof RL."}


created_at: 2024-04-29 18:42:00
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten text about list operations in programming5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Another example: if R1 and R2 are lists, what is the value of (cons R1 R2)?\nE.g.: R1 = '(1 2)\n       R2 = '(3 4)\n       (cons R1 R2) = ((1 2) 3 4)\n\nThere is another primitive list op called append:\n       (append R1 R2) = (1 2 3 4)"}


created_at: 2024-04-29 18:42:12
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains handwritten notes about programming with lists, including definitions and conditional statements.6

metadata:
{"source": "pdf", "chroma:document": "Let's look at some program developments using lists.\nConsider a program which is to input a list and output #t if the input is a list of atoms, and #f otherwise.\n\nHere we will assume\n\nlst::= () (cons atom list) (cons list list)\n\nand\n\nlat ::= () (cons atom lat)\ndown::= a|b\n\nThe first definition describes the input data, and effectively tells us how to structure the program\n\n(define (lat q)\n  (cond ((null? q) #t)\n        ((atom? (car q)) ________?? )\n        (else #f))))\n\n          (recursive call on a shorter list - i.e (lat (cdr q)))"}


created_at: 2024-04-29 18:42:22
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes related to programming concepts7
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "check out the above to avoid having to type def. of atom? each time you want it. atom? is NOT a primitive - so we define it (define (atom? x) (and (not (null? x)) (not (pair? x)))) Here null? and pair? are primitives (null?. ?) = #t if l is the empty list #f otherwise (What does scheme do if l is not a list?) (pair? . ) = #t if c is a cons-cell #f otherwise (What does scheme do if c is say a number?)"}


created_at: 2024-04-29 18:42:34
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten code and notes8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "(define (lat? s)\n(cond ((null? s) #t)\n      ((atom? (car s))     ?)\n      (else #f)))\nRecursive call on a shorter list -\n(lat (cdr s))\nWhy that else-clause? How about\n(define (lat? s)\n(cond ((null? s) #t)\n      (else (and (atom? (car s)) (lat? (cdr s)))))\nCleaner. Simpler. More in line with the BNF.\nPf by induction on the length of the input #elts in the list\nStrategy used: 'cdring down the list' -"}


created_at: 2024-04-29 18:42:42
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Discussion on a design idea for processing lists recursively in programming, using divide and conquer strategy and recursion9

metadata:
{"source": "pdf", "chroma:document": "With this design idea, plus the idea of processing the tail of the list recursively we have our divide and conquer set up. i.e., solved by 'recursive magic' processed by checking whether it is an atom. We know that the list is a list precisely if BOTH the car is an atom and the cdr is a list. So we use 'and', which is the deferred operator."}


created_at: 2024-04-29 18:42:56
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes about Simpson's Rule for numerical integration.0
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Some Problems from HW5 \u2014 concerning higher order functions.\n\nA&S 1.29 (Implementing Simpson's Rule)\n\nThe text states, \"Using Simpson's Rule the integral of a function f between a and b is approximated as\n\n\\(\\frac{h}{3} [y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + ... + 2y_{n-2} + 4y_{n-1} + y_n]\\)\n\nwhere h = \\(\\frac{(b-a)}{n}\\) for some even integer n, and y_k = f(a+k*h)\""}


created_at: 2024-04-29 18:43:19
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes including annotated code discussing Simpson's Rule for numerical integration.1
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "we are asked to code this.\n;assumes that n is even\n(define (simpson f a b n)\n  (simp-aux f a b n (/ (- b a) (* n 1.0))))\n\n(define (simp-aux f a b h)\n  (define (term k)\n    (cond ((= k 0) (* h f a))\n          ((= n k) (* h (* a (* k h))))\n          ((odd? k) (* h (* 4 (f (+ a (* k h))))))\n          ((even? k) (* h (* 2 (f (+ a (* k h))))))\n    ))\n  (define (next k)\n    (+ k 1))\n  (* (/ h 3.0)\n     (sum-term 0 next n)))\n\nSimpson's Rule uses parabolas instead of rectangles to integrate the integral approximation. R is an integer (want to avoid floating point issues).\n\nNote that I am not using the yk values to control the h op.\n\nWhat is to be proved?\n\nClearly we would NOT want to give a pt of Simpson's Rule itself - Rather - the proof burden would be to show that this code actually does IMPLEMENT Simpson's Rule.\n\nA useful verification would be showing diagrammatically that the code does what Simpson's Rule requires.\n\nAs for real-number pitfalls - I'd like you to write a loop with stopping condition k = 1, 'n' x initially 0 which adds 0.01 to x with each iteration x:= 0.0\nWhile < x 1.0 do x:= x + 0.01 It does not stop!"}


created_at: 2024-04-29 18:43:36
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Mathematical notes and code related to the computation of Wallis' product2
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "There is an easy way to avoid the repeated multiplication (x * k * k) - think about introducing a new variable to keep track of the right endpoints.\n\nNote that Problem 1.30 - negative sigma - has been discussed in class\n\nProblem 1.31 - Another example of the use of a specialized sigma term parameter in the computation of Wallis' product:\n\n\u03c0 = 2 * (2/1) * (2/3) * (4/3) * (4/5) * (6/5) * (6/7) * 8 * ... \n\u0394 = 3 * (3/1) * (3/3) * (5/3) * (5/5) * 7 * 7 * ...\n\n(define (wallis n)\n  (define (term k)\n    (cond ((odd? k) (* 1.0 (/ (+ k 1) (+ k 2))))\n          (else (* 1.0 (/ (+ k 2) (+ k 1))))))\n  (define (next_k) (+ k 1))\n  (iter-prod term 1 next n))\n\nWhere you can fill in the details for the function iter-prod."}


created_at: 2024-04-29 18:43:48
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed text from the provided image, which discusses an algorithmic approach.3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Let's take a break from the homework problems with an Iterative Count Change program. A recursive divide and conquer approach is developed in the text (pp 40-41): The number of ways to change amount a using n kinds of coins equals the number of ways to change amount a using all but the first kind of coin, plus the number of ways to change amount a - d using n kinds of coins, where d is the denomination of the first kind of coin. What might an iterative approach look like? One approach essentially solves the problem via an iterative solver."}


created_at: 2024-04-29 18:44:09
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
The image contains handwritten code and comments in Scheme programming language, along with handwritten notes.4

metadata:
{"source": "pdf", "chroma:document": ";; the only looping here is in sigma\n\n;; GI: result = sum of term(i) from A to a-1 AND a <= b + 1\n\n(define (sigma a term b)\n    (define (iter a result)\n        (cond ((> a b) result)\n              (else (iter (+ a 1) (+ (term a) result)))))\n    (iter a 0))\n\n;; the max number of nickels is {quotient amt 5}, and for each 0 <= i <={quotient amt 5}, there is\n;; way of making change using i nickels (with pennies as the balance)\n\n(define (pn amt)\n    (cond ((< amt 5) 1)\n          (else (+ 1 {quotient amt 5}))))\n\n;; the max number of dimes is {quotient amt 10}, and for each 0 <= i <= {quotient amt 10}, there\n;; (pn (- amt (* 10 i))) ways of making change\n\n(define (pnd amt)\n    (sigma 0\n           (lambda (numberOfDimes) (pn (- amt (* 10 numberOfDimes))))\n           (quotient amt 10)))\n\n(define (pndq amt)\n    (sigma 0\n           (lambda (numberOfQuarters) (pnd (- amt (* 25 numberOfQuarters))))\n           (quotient amt 25)))\n\n(define (pndqh amt)\n    (sigma 0\n           (lambda (numberOfHalves) (pndq (- amt (* 50 numberOfHalves))))\n           (quotient amt 50)))\n\nNo new invariant needed since\nwe've already proved that sigma\nworks."}


created_at: 2024-04-29 18:44:16
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten text on a notepad.5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Suggested for you\n\nThese last functions are so small that our inner functional programmer wants to ask: can they be abstracted as we did earlier for sigma?\n\nWell, back to work ..."}


created_at: 2024-04-29 18:44:24
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes about a programming problem involving function definition in Scheme6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Problem 1.34\n\n(define (f g)\n  (g 2))\n\nWhat happens when we call\n\n(f f)?\n\nThis results in (f 2),\nwhich gives (2 2), which\nthrows an error because (2 2)\nmakes no sense as a function\ncall."}


created_at: 2024-04-29 18:44:47
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes and code from a math-related exercise7
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "(Continued Fractions)\nExercise 1.37\n\n; iterative_version\n(define (cont-frac n d k)\n\n(define (cont-iter result count)\n(if (= count 0)\nresult\n(cont-iter\n(/ (+ (n count) (d count) result))\n(- count 1)))))\n\n(cont-iter (/ (n k) (d k))\n(- k 1)))\n\n; test with golden ratio\n(cont-frac\n(lambda (i) 1.0)\n(lambda (i) 1.0)\n1000000)\n\n; guess-invariant: result =\n\n;\n;\n;\n;\n;\n;\n;\n;\n;\n\n; so now when count = 0, the first numerator included in result is\n; N(1), or is it N(0) ?\n\nNumbers a and b with a > b are said to be in the golden ratio if their\nratio is the same as the ratio of their sum to a. That is, if a/b = (a + b)/b\nApprox 1.6180339 ..."}


created_at: 2024-04-29 18:44:59
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: This is a handwritten note discussing a mathematical pattern involving the terms N_k and D_k.8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "What is the next value of result?\nN_k-1          (R)         t\n________ = _______  + _____\nD_k-1 + result   t+1\n\nAnd the next value?\nN_k-2          (R)         t\n________ = _______  + _____\nD_k-2 + result   t+2\n\nAnd so on \u2013 we can see the emerging pattern, even if we might not see how to describe this pattern with anything other than a t-fort\n\nSuggested for you: If the terms above are the 0th, 1st and 2nd terms, what does the nth term look like?"}


created_at: 2024-04-29 18:45:12
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten mathematical notes and questions9
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Does Nk-p\nDk-p + (N\nk-(p-1))\nDk-(p-1) +\nPerhaps this could be abbreviated as cont-frac(N,D,p-1)?\nSo that as gi we mayyt have\nresult = Nk-p\nDk-p + cont-frac(N,D,p-1)\n? But we've lost the variable count. Can you complete this by letting expressing p in terms of count?\nI'll leave the recursive solution to you. (It's easier.)"}


created_at: 2024-04-29 18:45:32
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
The image contains handwritten mathematical notes and code snippets related to composing functions.10

metadata:
{"source": "pdf", "chroma:document": "Moving right along:\n\n;; exercise 1.42\n(define (compose f g)\n  (lambda (x) (f (g x))))\n\n(define (addone x)\n  (+ x 1))\n\n(define (square x)\n  (* x x))\n\n((compose square addone) 3)\n\n; what is assumed about f and g?\n\n(square (addone 3)) = 36\n\nCould we have (lambda(x) ...) as the value of a call to compose? Yes!\n\n; could take multiple args, with a singleton output. E.g.: g could be 2-arg and the function rewritten\n\n; as far as we have gone, our functions all produce a 1-dimensional output\n\nE.g.: we have no way now of directly writing a function f: Z^2 -> Z^2\n\n; of course, we could be clever and find a way to encode pairs of integers as single integers. (E.g. Cantor's diagonal proof that set of pairs of integers is countable (Z^2...))"}


created_at: 2024-04-29 18:45:45
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten notes about function composition in programming, including a scheme code snippet and a diagram explaining compose along with additional notes and a practice task11

metadata:
{"source": "pdf", "chroma:document": "define new-compose f g\n(lambda (x y) (f (g x y))))\n\nWhat is the diagram for compose.\n\ncompose:\n\n                ____________\n              Params (f g)\n\n\nx, y need to satisfy precond for g and (g x y) needs to satisfy precond for f\n\nbody (lambda (x y) (f (g x y)))\n\nPractice: work out diagram for\n(compose sg myadd) 2 3\n\nThe proof for compose itself has nothing to do with the proofs of f and g"}


created_at: 2024-04-29 18:46:00
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing a mathematical function concept12
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Is there truly no way of writing a function (with just what we know now) capable of returning multiple values? It is true that we can get only a single value now, but we could use that value to encode (e.g., pairs, triples, etc.) One way if we want outputs of 3 values (p, q, and r), have the function compute 2^p * 3^q * 5^r - extracting p, q, r is then just a matter of (what amounts to) taking base 2, base 3, base 5 logs. 'Fancy way of saying: we can do repeated division by 2, to extract p (and so on)'"}


created_at: 2024-04-29 18:46:08
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten educational notes and a diagram13
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "There are other ways to see the argument that the set of pairs (p, q) of integers has the same size as the set of integers itself. Here's the idea: The analytic form of the function tracing this traversal curve (and that for its inverse) are known."}


created_at: 2024-04-29 18:46:23
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten code and notes related to functional programming14
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "exercise 1.43\n\n(define (repeated f k)\n  (if (= k 1)\n      f\n      (compose f (repeated f (- k 1)))))\n\n(define (compose f g)\n  (lambda (x) (f (g x))))\n\n(define (square x)\n  (* x x))\n\n((repeated square 2) 5)\n\n; iterative solution:\n\n; design idea - keep a variable result-so-far and another variable count - and maintain result-so-far = f composed with itself count times\n\nNote: looks like count would most usefully increase from 0 up to count - stop when count = k, then result-so-far would be f^k.\n\n((repeated sq 2) 3) = (sq (sq 3)) = (sq 9) = 81\n\n((repeated sq 3) 2) - (sq (sq (sq 2))) = (sq 4) = 16"}


created_at: 2024-04-29 18:46:42
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes containing programming code and comments15
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "i > 0 is an integer \ndefine (crepeated f k) \n  (iter 0 k f (lambda (x) x)) \n\n(define (iter count k f result-so-far) \n  ...) \n\ni > 1 is an integer \ndefine (npeated f k) \n  (iter 1 k f f) \n\n(define (iter count k f result-so-far) \n  (cond ((= count k) result-so-far) \n    (else \n      (iter (+ count 1) k f (compose f result-so-far))))) \n\nAside: \n  (lambda (x) (f x)) \n  is the same as \n  f. \n\nWe want to check the invariant, but this thing \nwas built with a specific girl in mind! \n\nSuggested practice: work out the down-converting version, in which ef no \nlonger need to be passed as parameter."}


created_at: 2024-04-29 18:46:58
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten notes on a lecture about early examples of program development discussing mathematical concepts and problem-solving strategies0

metadata:
{"source": "pdf", "chroma:document": "Class 07 CSC 335 Sections M and R 02/15/24\nEarly Examples of Program Development\n\nComputing b^n where, for simplicity, we shall assume that n >= 0 is an integer, and b is just a number.\n\nSpecifically - just b * b x ... x b\n\nn times\n\nThe first question: should we use recursion, or iteration? Generally it is much easier to use recursion - so we start with that. Having decided that, the next question is: how will we 'divide and conquer'? Specifically what related (but smaller) problem will we solve, and how will we use that solution to solve the larger (main) problem?\n\nb x ... x b\nn-1 times\n\nNote that the first step in a is NOT 'what is the basis step?' The reason is clear - we can't know what the basis step is until we know what we are trying to prove.\n\nBut at this point - with the divide and conquer strategy..."}


created_at: 2024-04-29 18:47:12
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten note discussing a computational problem-solving approach involving recursion and divide-and-conquer strategy.1

metadata:
{"source": "pdf", "chroma:document": "In place we can ask: what problem of this kind cannot be subdivided? And that is the basis step for the strategy we propose, the n=0 case cannot be subdivided\u2014so we must compute it directly (without recursion). \n\nPlease notice that the strategy does not further decompose\u2014specifically, it does NOT spell out '... and then we decompose the b^(n-1) problem, and then the b^(n-2) problem (...) and so on until the b^0 problem is reached', \n\nThe divide and conquer strategy has some serious magic; the divide step includes a black-box component. We do NOT ask how b^(n-1) is computed\u2014we simply ASSUME that it is. This relies on the Principle of Induction. \n\nLet's take a moment to understand the difference between the EVIL and LAZY ellipses. \n\nHere it is: the lazy ellipsis can always be replaced. For example, "}


created_at: 2024-04-29 18:47:30
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of a mathematical discussion written on lined notebook paper2
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "\u2200x...\u00d7b \n n-1 times \n n-1 \n can be replaced by \u220f (from i=1 to n-1) b. \n Notated aside: Hey, wait: i doesn't occur in the term \n So what does this mean? The idea is to regard \u220f (from i=1 to n-1) as \u220f (from i=1 to n-1) f(i), where f(i) is the constant b for all values of i. \n In other words, we wrote b\u00d7...\u00d7b, but we did not need to. \n For the EVIL ellipsis, there is no way of replacing it. One way or another, a description at that level involves the concept ''eventually''. You need to carry out an induction."}


created_at: 2024-04-29 18:47:40
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on workflow design and abstract computer language designs3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Another point, having to do with workflow: design in English, not in code.\n\nSupporting argument: you will find that the human-language descriptions are more abstract than the computer-language designs.\n\nBy this I mean that usually there are many possible computer encodings of a given algorithm.\n\nAlgorithmic Idea\n\n<multiple arrows pointing to different objects including circled 'Algorithmic Idea'>\n\n<sketch of three heads and a circle>\n\nmany possible programs\n\nEach program makes many specific"}


created_at: 2024-04-29 18:47:50
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing programming concepts and presenting a code snippet.4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "e.g. choices regarding data representation, precisely what to do next and so on. As far as solving the org. problem is concerned, they are over-constrained.\n\nRelated: programming languages and errors for designing solutions. So you don't want to use them for this.\n\nLet's get back to b. At this point we might generate some guess-code\n\npre: b is a number and n >= 0 is an integer\n\ndefine (myexp b n)\n    (if (zero? n) 1\n        (else (* b (myexp b (- n 1))))\n\npos: returns b"}


created_at: 2024-04-29 18:48:04
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes related to a recursive call and its conditions5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "IH: The recursive call works, provided the pre-cond holds at the point of the call.\n\nWe have to show - in this particular case - that PRE \u2227 n \u2260 0 => b is a number and n-1 > 0 \n\nThis is clear: n \u2265 0 \u2227 n \u2260 0 => n-1 \u2265 0 if b was a number, then - because the program never changes b - it is still a number.\n\nSo (myexp) b (- n-1) actually does return b, the program multiplies this by b, hence giving the correct result.\n\nSo - are we done? Nope - still have to check the basis step.\n\nWe have to show that"}


created_at: 2024-04-29 18:48:15
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing mathematical implications and error checking in programming.6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "PRE A (n=0) -> \n1 is the right answer\nBut this is not a valid implication, because our current PRE allows b=0; In case \nn=0, the result 0^0 is undefined - \nThe program should certainly not return 1.\nSo; what to do?\nNo input checking in 335\nNo error message outputs in this course.\nWe can change the precondition - one \npossibility is\nb \u2260 0 is a number and n\u22650 is an integer\nAnother - less restrictive, and so superior if \nit works - is\nb is a number and n\u22650 is an integer\nand (b and n are not both 0)"}


created_at: 2024-04-29 18:48:24
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten mathematical notes7
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "P1 solves our problem - for now\nb^0 ^ n = 0 => b = 1\n(This is the basis step)\n\nYou can check that the induction step\nis not bothered by this new precondition\nbecause... the new precondition\nimplies the old precondition.\n\nbut it would be nice if we could use\nP2. One way might be\n\n; P2\n(define (another-expt b n)\n  (cond ((zero? b) 0)\n    (if b \u2260 0 (myexpt b n) computes b^n)\n    (else (myexpt b n))))\n;b^n is returned."}


created_at: 2024-04-29 18:48:34
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes discussing a programming issue.8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Homework: you might try using P2 with the original program (i.e., no checking whether b = 0) \u2013 and giving a 'no-unwinding' analysis of what goes wrong.\n\nThe unwinding analysis might go as follows: if b = 0, then since eventually n = 0, we will be confronted with 0 \u2013 so the whole plan fails.\n\nHint: The fault rests in an invalid implication.\n\nThe termination argument \u2013 which is essentially the same as for recursive factorial \u2013 needs yet to be given."}


created_at: 2024-04-29 18:48:51
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on recursion and problem solving9
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Grading Rubric for a problem of this kind:\n\n1. Specification - i.e. pre and post\n\n2. Decide whether to use recursion or iteration - usually start with recursion because it's easier\n\n2.1 Having decided on recursion\n   -> functional\n   -> decomposition if more than one function seems to be necessary\n   -> divide & conquer strategy (D & C)\n   -> IH: what will we induct on?\n   -> either has base or the basis\n     -> base step is given in terms of IH & D & C\n     -> for these types of problems,\n       number problem,\n       it is usually some basic\n       algebra\n   -> check that the pre-condition holds\n      when the recursive call is made\n   -> check that pre & basis ->\n      post condition\n   -> Termination arg\n\nif any of these steps break,\nreverse possibly\nstarting over"}


created_at: 2024-04-29 18:49:08
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes about a design idea for an iterative exponentiation program.10
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "2. Invariant first / code later development of an iterative exponentiation program.\n\nWe start with a design idea: we wish to compute b^n (b + 0, n = 0 - b is a number and n is an integer) in the following way: using an accumulator variable result, we will increase a counter - count - from 0 up to n, with b^count kept in result.\n\nWhen we stop, count = n, and result should be b^n. We have a guess-invariant:\n\nresult = b^count\n\n-> Is this strong enough? [Yes; when count = n we can return result]\n\n-> Is it weak enough? [Yes - if we set result initially to 1, we have result = b when count = 0]\n\n-> Is it preservable? [Yes: if result = b^count for the current call, is this still true on the next call? Our design idea was to increase count - presumably by 1 - so"}


created_at: 2024-04-29 18:49:19
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten notes and code related to a design problem involving equation optimization and code termination analysis.11

metadata:
{"source": "pdf", "chroma:document": "all we need do to maintain the equation is to multiply result by b.\n\nDoes the proposed design terminate? Yes - incrementing count from 0 to integer n >= 0 will terminate.\n\nGeneric Design Idea\n\"Make progress towards termination while keeping the invariant true\"\n\nGuess-code\n(define (my-expt b n)\n   (some call to expt-iter )\n(define (expt-iter b n count result)\n   (cond ((= count n) result)\n         (else (expt-iter b n (+ count 1) (* b result)))))"}


created_at: 2024-04-29 18:49:31
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes possibly related to programming or software design12
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "let's test... need first to set up the initial call to expt-iter\nThe initial call is supposed to make the invariant true\nthe first time expt-iter is called\n(defun (myexpt b n)\n(expt-iter b n 0 1))\n\nIs there an alternate design? As engineers, we need to do better than settle for the first idea that occurs to us,\n\nTry to look at your designs critically\n\nFor the program we just wrote, one criticism might be that we need at each step to compare count to n"}


created_at: 2024-04-29 18:49:41
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: A handwritten note discussing some form of sequential logic or count operation.13
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "If we were to start count at n, and decrease it to 0, would our current invariant still work?\n\nIf we were to start count at n, and decrease it to 0, would we still need all the variables?\n\nLet's take the first question: currently our GI is \nresult = count\n\nDoes anything go wrong when we change the design?\n\nOne problem: on start, count = n, \nin so result would need to be bn. And this means that"}


created_at: 2024-04-29 18:49:48
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes discussing issues related to a program's logic and its functionality.14
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "The problem has already been solved - there is no reason to run the program!\nAnother problem: It's also not strong enough - in that it does not imply the postcondition when n = 0 (i.e., when the proposed loop stops).\nYet it seems that we ought to be able to compute n by counting down to 0 - so perhaps the thing to do"}


created_at: 2024-04-29 18:49:56
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes with mathematical expressions and comments15
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "is to adjust our GI!\n\nresult = b ^ count ?\n\nlooks better.\n\nso the exponent\nis 0 when\ncount = 0 and\n\nHW\nSuggested for you:\nWork this out - ie - modify the\npreviously given\ncode so that\nthis GI works"}


created_at: 2024-04-29 18:50:06
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes related to a class discussion on a design idea.0
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Class 08 Sections M and R February 20 and 27 2024\n\nWe wrapped up last time by sketching the design of a downcounting exponentiation program, thinking that such a design might allow us to eliminate a parameter from expt-iter: if we start count at n and finish when count = 0, we no longer need the parameter n in expt-iter.\n\nRecalling that a 'design idea', as we use the term in 335, consists in large part of a GI, we start today by giving a second development of a GI for this program."}


created_at: 2024-04-29 18:50:14
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes regarding program design and functionality.1
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Part of the design idea - what about a GUI? We need a certain kind of platform which makes a connection between the program variables and the desired end result. Here - between count, result and b.\n\nWhen the program stops, we want result = b^n\n\nWhen the program starts, we have count=0 and we need to have a value for result which is 'easily' computed."}


created_at: 2024-04-29 18:50:24
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This is a handwritten text discussing mathematical or logical operations, revolving around variables and conditions.2

metadata:
{"source": "pdf", "chroma:document": "Suppose result = 1 to start. Then b = ?? * result\nSo if b = count * result is weak enough\nIf we make this b then on start we would have b = count^n * result\nMoreover, when count = 0 this equation would give us b^n = b^0 * result ie, result = b^n.\nThe only thing left to check is whether it is presentable? The plan is to decrement count - and so we need to adjust result to keep the equation true. Clearly, if"}


created_at: 2024-04-29 18:51:00
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten mathematical and programming related notes3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "b^n = b^(count) x result\nthen also\nb^n = b^(count-1) x (b x result)\nSo: we just need to multiply result by b\n\nSo we have guess-code for an alternate design:\n\n(define (expt-iter b count result)\n  (cond ((zero? count) result)\n    (else (expt-iter b (- count 1)\n      (* b result)))))\n\nNote: the n parameter has been removed.\n\nWith this design\nthere is no need to compare b and n."}


created_at: 2024-04-29 18:51:10
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten note on lined paper4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Then test it.. and you're done unless the test turns up problems."}


created_at: 2024-04-29 18:51:20
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten mathematical concepts and programming design ideas on iterative addition5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "2.\nLet's look now at an iterative program for adding two numbers a and b.\n\nWe'll assume a>=0 is an integer but you will certainly want to see about removing a>=0 restriction.\n\nDesign idea: addition by repeated incrementation. We will start with a and b and simultaneously decrement a and increment b until a=0.\n\nSince we decrement a at the same time as we increment b, a likely GI is:\n\na + b is constant\n\nHow does this help? - If we had a convenient way of referring to the initial values of a and b..."}


created_at: 2024-04-29 18:51:31
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes about mathematical or logical operations6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "then say as A and B, respectively, then we could write ghost variables never change A+B = a+b why -> strong enough? On termination, our plan is that a = 0. So the eqn then implies A+B = 0 + b = b and we could simply return b to get the desired sum. -> weak enough? On start, a = A and b = B. So certainly A+B = a+b"}


created_at: 2024-04-29 18:51:40
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes possibly related to programming and mathematical operations7
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "-> preservable?\nA+B = a+b\n\nA+B = (a-1) + (b+1)\n\nSo - bang! - we have code\ndefine (myplus a b)\n  (cond ((zero? a) b)\n    (else (myplus (- a 1)\n                   (+ b 1))))"}


created_at: 2024-04-29 18:51:52
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of a handwritten mathematical exploration of a recursive function8
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "What about the recursive procedure for the same task, given my myplus-version-1 in A & S?\n\nHow could we use a divide and conquer strategy to solve the problem?\n\nHow will we break the problem up?\na + b = 1 + ((a-1) + b) -> 'smaller problem of the same kind'\n\nadjustment necessary to leverage the result from the smaller problem to solve the entire problem\n\nTermination when a = 0\n\nTentative Basis: (0 + b) = b"}


created_at: 2024-04-29 18:52:02
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten mathematics and programming related notes9
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "It appears we can organize the construction and proof as an induction on a\n\nReality check: is <something> which can be instructed on.\n\nWell yea - a >= 0 is an integer.\n\nSo we're ready for guess code - \n(define (myadd a b)\n  (cond ((zero? a) b)\n    (else (+ 1 (myadd (- a 1) b))))\n\nThe TS: we add 1 to (a - 1) + b provided: the proposition holds\nat the time of the call"}


created_at: 2024-04-29 18:52:20
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten class notes on Pascal's Triangle including a diagram and some explanatory text0
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Classes 10 and 11 CSc 335 February 29 and March 5 2024\n\nExercise 1.12 from A & S \u2013 The Pascal's Triangle Problem\n\nusing 0-based indexing, this is the set of Pascal\u2019s triangle which, This gives input to want the value (3,2) writing this actual index, refers to this position.\n\nWe are to write a program which inputs the \"index\" of an entry in this table and which returns the corresponding value.\n\nWhat is the definition of index in this case? After some thought, we decide to use row-column indexing where columns are diagonal. Given this, there is still the question of whether to use 0-based or 1-based indices.\n\nFor example - should the leftmost column be the 0th column or the 1st column?\n\nSince we can in all likelihood develop a program for either choice, we ask whether there is another criterion we can use to make the decision.\n\nAs you probably know, the numbers in the Triangle are precisely the binomial coefficients - ie - the numbers (n k) which occur as the coefficients."}


created_at: 2024-04-29 18:52:33
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Handwritten mathematics lecture notes discussing binomial coefficients and suggesting indexing methods for programming.1

metadata:
{"source": "pdf", "chroma:document": "In the expansion of (x+y)^n. So it makes sense that the convention we use lines up with this.\n\nLet's compute some values for (n k).\n\n(0 0) = 1\n\n(1 0) = 1\n(1 1) = 1\n\n(2 0) = 1\n(2 1) = 2\n(2 2) = 1\n\nRecall (n k) =\nn! / [k! (n-k)!]\n\n(0 0) (1 0) (1 1)\n\n(2 0) (2 1) (2 2)\n\n(3 0) (3 1) (3 2) (3 3)\n\nSuggest checking out 1-based indexing and work out the program.\n\nLooks like we are best served by using 0-based indexing for both the rows and the columns.\n\nWith this in mind, we can tighten the program's specificity."}


created_at: 2024-04-29 18:52:44
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
This image contains handwritten notes relating to a programming concept, specifically discussing recursive computation of binomial coefficients.2

metadata:
{"source": "pdf", "chroma:document": "pre: row and col are integers such that\n(row col) makes sense as a binomial coefficient\n\npre - bcd are non-negative integers and\ncol <= row\n\nprogram\npost: returns (col)\n\nStart by understanding the recursion\n-> if col = 0 return 1\n-> if col = row, return 1\n-> Otherwise\n(pascal row col) is computed from\n(pascal (row-1) (col-1))\nand\n(pascal (row-1) col)\ncol) is not reduced, so can't induct on col"}


created_at: 2024-04-29 18:53:01
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcribed text from an image containing handwritten notes related to an algorithm3
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Tentative HH: The recursive calls work so long as the precondition is satisfied AND the col index is no more than row-1. \nWe know col <= row and we know neither row nor col is 0 and we know col < row so clearly col-1 <= row-1 and also col <= row-1 because everything is an int[eger]. \nTermination is clean because for each recursive call, the row index is reduced by 1 -- and the program halts when row = 0. \n\nIs our design ready to be tested as code? \n-> Design roles for variables \n-> Divide and conquer strategy - i.e. the shape of the HH and its - is in place \n-> Termination argument is in place"}


created_at: 2024-04-29 18:53:11
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: This is a handwritten note containing code and development plans.4
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "Looks like we're ready to code!\n\n(define (pos row col)\n  (cond ((= row 0) 1)\n        ((or (= col 0) (= col row)) 1)\n        (else (+ (pos (- row 1) (- col 1))\n               (pos (- row 1) col)))))\n\nNext, check for consistency with the development\n\neg - does this work and well?\n\n(define (pul row col)\n  (cmd ((= col 0) 1)\n       ((= col row) 1)\n       (else ... as above ...)))\n\nNext: run a few tests\n\nNext: (if time) write out a concise proof, which effectively summarizes your development."}


created_at: 2024-04-29 18:53:21
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Transcription of handwritten notes discussing different ideas and concepts5
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "That's a wrap!\n\nIn the typed note, you'll find a version which makes a different choice for the indexing.\n\nWhat about an iterative solution?\n\n- could use iterative factorial in the formula given above, but considerable care needs to be taken to avoid unnecessary duplication of effort.\n\n- another way would be to make use of lists or vectors with the idea of computing the nth row (represented as a list, say) from the (n-1)st row. Will come back.\n\nThis brings into question what is meant by the phrase"}


created_at: 2024-04-29 18:53:28
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: Handwritten notes on programming concepts6
encoding: FLOAT32
metadata:
{"source": "pdf", "chroma:document": "\"Iterative programs work in constant space\" because - clearly - these rows grow longer and longer as the computation proceeds. Similarly, the space needed for (fact (- n 1)) increases as n increases. What we mean is, \"the stack of calls does not grow\""}


created_at: 2024-04-29 18:53:46
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
encoding: FLOAT32
id:
Text transcribed from a computer science or mathematics handwritten note containing code, annotations, and equations.7

metadata:
{"source": "pdf", "chroma:document": "Exercise 1.11 - as given in the text\n; a function f is defined by the rule that f(n) = n if n < 3 and \n; f(n) = f(n-1) + 2*f(n-2) + 3*f(n-3) if n >= 3. Write a procedure that \n; computes f by means of a recursive process. Write a procedure that \n; computes f by means of an iterative process.\n\nHere is a procedure that computes f by means of a recursive process\n\n(define (f n)\n  (cond ((< n 3) n)\n        (else (+ (f (+ n -1)) (+ 2 (f (+ n -2))) (+ 3 (f (+ n -3)))))))\n\n; where the updates, just as parameter updates in scheme, do not interfere with one another\n\n(define (f-iterative n)\n  (define (f-iter m w x y z)\n    (cond ((= m n) w)\n          (else (f-iter (+ m 1) (+ w (+ x (* 2 y) (+* 3 z))) w x y))))\n  (f-iter 3 2 (+ 2 1) (+ 3 0) 1 0))"}


# embedding_metadata

key: chroma:document
string_value:
WEAK AND STRONG INDUCTION – REVIEW SET 1 CSC 335 PROFESSOR TROEGER I strongly recommend the text I used in CSc 104: David Liben-Nowell’s excellent Discrete Mathematics for Computer Science, published by Wiley. These problems are from his Chapter 5. (1) Prove by (weak) induction on n: Σi=n i=0i2=n(n+1)(2 n+1) 6 (2) Prove by (weak) induction on n: Σi=n i=0i3=n4+2n3+n2 4 (3) Prove by (strong) induction on nthat, for every integer n≥4, it is possible to make ndollars using only two- and ﬁve-dollar bills. (4) Prove by (strong) induction on nthat, for every integer n≥1, there exist k≥0 prime numbers p1, p2, . . . , p ksuch that n= Πi=k i=1pi (5) What is the sum of the ﬁrst nodd positive integers? Prove your claim by induction. Date : February 3 2020. 1............................................................................................................................................................................................................................................................................


key: chroma:document
string_value:
INDUCTION – REVIEW SET 2 CSC 335 PROFESSOR TROEGER Again, I strongly recommend David Liben-Nowell’s excellent text, Discrete Mathematics for Computer Science, published by Wiley. These problems are from his Chapter 5. (1) In chess, a knight at position ⟨r, c⟩can move in an L-shaped pattern to any of eight positions: moving over one row and up/down two columns, or two rows over and one column up/down. A knight’s walk is a sequence of legal moves, starting from a square of your choice, that visits every square of the board. Prove by induction that there exists a knight’s walk for any n-by-nchessboard, for any n≥4. Note that the knight (horse) may visit squares more than once. (2) A string of balanced parentheses [ , ] is one of the following: (a) the empty string; (b) a string [ S] where S is a string of balanced parentheses; or (c) a string S1S2where S1andS2are both balanced strings of parentheses. Prove by structural induction (a) Every string of balanced parentheses has exactly the same number of open parent


key: chroma:document
string_value:
heses as close parentheses; (b) Every preﬁx of a string of balanced parentheses has at least as many open parentheses as it does close parentheses Date : February 3 2020. 1....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................


key: chroma:document
string_value:
PROPOSITIONAL LOGIC – REVIEW SET 1 CSC 335 PROFESSOR TROEGER Again, I strongly recommend David Liben-Nowell’s excellent text, Discrete Mathematics for Computer Science. These problems are from his Chapters 3 and 5. Both can be solved using structural induction. (1) Prove that each proposition deﬁned using the connectives ∧,∨,¬and = ⇒is logically equivalent to a proposition deﬁned using only ∧and¬. (2) Let us say that a literal is a Boolean variable or the negation of a Boolean variable. (Sopand¬pare both literals.) A proposition is in conjunctive normal form if it is the conjunction of one or more clauses , where each clause is the disjunction of one or more literals. For example, ( ¬p∨q∨r)∧(¬q∨¬r)∧(r) is in conjunctive normal form. Prove that each proposition deﬁned using the connectives ∧,∨,¬and = ⇒ is logically equivalent to a proposition in conjunctive normal form. Date : September 15 2020. 1...................................................................................................................


key: chroma:document
string_value:
Revised5Report on the Algorithmic Language Scheme RICHARD KELSEY , WILLIAM CLINGER, AND JONATHAN REES(Editors ) H. A BELSON R. K. D YBVIG C. T. H AYNES G. J. R OZAS N. I. A DAMS IV D. P. F RIEDMAN E. K OHLBECKER G. L. S TEELE JR. D. H. B ARTLEY R. H ALSTEAD D. O XLEY G. J. S USSMAN G. B ROOKS C. H ANSON K. M. P ITMAN M. W AND Dedicated to the Memory of Robert Hieb 20 February 1998 SUMMARY The report gives a deﬁning description of the program- ming 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 an exceptionally clear and simple semantics and few diﬀerent ways to form expressions. A wide variety of programming paradigms, in- cluding imperative, functional, and message passing styles, ﬁnd convenient expression in Scheme. The introduction oﬀers a brief history of the language and of the report. The ﬁrst three chapters present the fundamental ideas of the language an


key: chroma:document
string_value:
d describe the notational conventions used for describing the language and for writing programs in the language. Chapters 4and5describe the syntax and semantics of expressions, programs, and deﬁnitions. Chapter 6describes Scheme’s built-in procedures, which include all of the language’s data manipulation and in- put/output primitives. Chapter 7provides 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. The report concludes with a list of references and an al- phabetic index.CONTENTS Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1 Overview of Scheme . . . . . . . . . . . . . . . . . . . . . . . 3 1.1 Semantics . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 Notation and terminology . . . . . . . . . . . . . . . . 3 2 Lexical conventions . . . . . . . . . . . . . . . . . . . . . . . 5 2.1 Id


key: chroma:document
string_value:
entiﬁers . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.2 Whitespace and comments . . . . . . . . . . . . . . . . 5 2.3 Other notations . . . . . . . . . . . . . . . . . . . . . . 5 3 Basic concepts . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3.1 Variables, syntactic keywords, and regions . . . . . . . 6 3.2 Disjointness of types . . . . . . . . . . . . . . . . . . . 6 3.3 External representations . . . . . . . . . . . . . . . . . 6 3.4 Storage model . . . . . . . . . . . . . . . . . . . . . . . 7 3.5 Proper tail recursion . . . . . . . . . . . . . . . . . . . 7 4 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.1 Primitive expression types . . . . . . . . . . . . . . . . 8 4.2 Derived expression types . . . . . . . . . . . . . . . . . 10 4.3 Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 5 Program structure . . . . . . . . . . . . . . . . . . . . . . . . 16 5.1 Programs . . . . . . . . . . . . . . . . . . . . . . . . . 16 5.2 Deﬁnitions . . . . . . . . .


key: chroma:document
string_value:
 . . . . . . . . . . . . . . . . 16 5.3 Syntax deﬁnitions . . . . . . . . . . . . . . . . . . . . 17 6 Standard procedures . . . . . . . . . . . . . . . . . . . . . . 17 6.1 Equivalence predicates . . . . . . . . . . . . . . . . . . 17 6.2 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 19 6.3 Other data types . . . . . . . . . . . . . . . . . . . . . 25 6.4 Control features . . . . . . . . . . . . . . . . . . . . . . 31 6.5Eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 6.6 Input and output . . . . . . . . . . . . . . . . . . . . . 35 7 Formal syntax and semantics . . . . . . . . . . . . . . . . . . 38 7.1 Formal syntax . . . . . . . . . . . . . . . . . . . . . . . 38 7.2 Formal semantics . . . . . . . . . . . . . . . . . . . . . 40 7.3 Derived expression types . . . . . . . . . . . . . . . . . 43 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Additional material . . . . . . . . . . . . . . . . . . . . . . . . 45 Example . . . . . . . . . . . . . . . . . 


key: chroma:document
string_value:
. . . . . . . . . . . . . . 45 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Alphabetic index of deﬁnitions of concepts, keywords, and procedures . . . . . . . . . . . . . . . . 482 Revised5Scheme INTRODUCTION 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 nec- essary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suﬃce to form a practical and eﬃcient programming language that is ﬂexible enough to support most of the major programming paradigms in use today. Scheme was one of the ﬁrst programming languages to in- corporate ﬁrst class 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 ﬁrst major dialect of Lisp to distinguish procedures from lambda expressions and symbols, to use 


key: chroma:document
string_value:
a single lex- ical environment for all variables, and to evaluate the op- erator 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 tail- recursive procedure calls are essentially goto’s that pass arguments. Scheme was the ﬁrst widely used program- ming language to embrace ﬁrst class escape procedures, from which all previously known sequential control struc- tures 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 re- cently, Scheme became the ﬁrst programming language to support hygienic macros, which permit the syntax of a block-structured language to be extended in a consistent and reliable manner. Background The ﬁrst description of Scheme was written in 1975 [ 28]. A revised report [ 25] appeared in 1978, which described the evolution of the language as its MIT implementation was upgraded 


key: chroma:document
string_value:
to support an innovative compiler [ 26]. Three distinct projects began in 1981 and 1982 to use variants of Scheme for courses at MIT, Yale, and Indiana Univer- sity [21,17,10]. An introductory computer science text- book using Scheme was published in 1984 [ 1]. As Scheme became more widespread, local dialects be- gan to diverge until students and researchers occasion- ally found it diﬃcult 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 [ 4] was published at MIT and Indiana Uni- versity in the summer of 1985. Further revision took place in the spring of 1986 [ 23], and in the spring of 1988 [ 6]. The present report reﬂects further revisions agreed upon in a meeting at Xerox PARC in June 1992. We intend this report to belong to the entire Scheme com-munity, and so we grant permission to copy it in whole or in part without fee. In particular, 


key: chroma:document
string_value:
we encourage implementors of Scheme to use this report as a starting point for manuals and other documentation, modifying it as necessary. Acknowledgements We would like to thank the following people for their help: Alan Bawden, Michael Blair, George Carrette, Andy Cromarty, Pavel Curtis, Jeﬀ Dalton, Olivier Danvy, Ken Dickey, Bruce Duba, Marc Feeley, Andy Freeman, Richard Gabriel, Yekta G¨ ursel, Ken Haase, Robert Hieb, Paul Hudak, Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim Philbin, John Ramsdell, Mike Shaﬀ, Jonathan Shapiro, Julie Sussman, Perry Wagle, 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 [30]. We gladly acknowledge the inﬂuence of manuals for MIT Scheme [ 17], T [22], Scheme 84 [ 11], Common Lisp [ 27], and Algol 60 [ 18]. We also thank Betty Dexter


key: chroma:document
string_value:
 for the extreme eﬀort she put into setting this report in T EX, and Donald Knuth for de- signing the program that caused her troubles. The Artiﬁcial Intelligence Laboratory of the Massachusetts Institute of Technology, the Computer Science Department of Indiana University, the Computer and Information Sci- ences Department of the University of Oregon, and the NEC Research Institute supported the preparation of this report. Support for the MIT work was provided in part by the Advanced Research Projects Agency of the Department of Defense under Oﬃce of Naval Research contract N00014- 80-C-0505. Support for the Indiana University work was provided by NSF grants NCS 83-04567 and NCS 83-03325.1. Overview of Scheme 3 DESCRIPTION OF THE LANGUAGE 1. Overview of Scheme 1.1. Semantics This section gives an overview of Scheme’s semantics. A detailed informal semantics is the subject of chapters 3 through 6. For reference purposes, section 7.2provides a formal semantics of Scheme. Following Algol, Scheme is a statically


key: chroma:document
string_value:
 scoped program- ming language. Each use of a variable is associated with a lexically apparent binding of that variable. Scheme has latent as opposed to manifest types. Types are associated with values (also called objects) rather than with variables. (Some authors refer to languages with latent types as weakly typed or dynamically typed lan- guages.) Other languages with latent types are APL, Snobol, and other dialects of Lisp. Languages with mani- fest types (sometimes referred to as strongly typed or stat- ically typed languages) include Algol 60, Pascal, and C. All objects created in the course of a Scheme computation, including procedures and continuations, have unlimited ex- tent. 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. Other languages in which most objects have unlimited exte


key: chroma:document
string_value:
nt in- clude APL and other Lisp dialects. Implementations of Scheme are required to be properly tail-recursive. This allows the execution of an iterative computation in constant space, even if the iterative compu- tation is described by a syntactically recursive procedure. Thus with a properly tail-recursive implementation, iter- ation can be expressed using the ordinary procedure-call mechanics, so that special iteration constructs are useful only as syntactic sugar. See section 3.5. Scheme procedures are objects in their own right. Pro- cedures can be created dynamically, stored in data struc- tures, returned as results of procedures, and so on. Other languages with these properties include Common Lisp and ML. One distinguishing feature of Scheme is that continuations, which in most other languages only operate behind the scenes, also have “ﬁrst-class” status. Continuations are useful for implementing a wide variety of advanced control constructs, including non-local exits, backtracking, and coroutines. See


key: chroma:document
string_value:
 section 6.4. Arguments to Scheme procedures are always passed by value, which means that the actual argument expressions are evaluated before the procedure gains control, whether the procedure needs the result of the evaluation or not.ML, C, and APL are three other languages that always pass arguments by value. This is distinct from the lazy- evaluation semantics of Haskell, or the call-by-name se- mantics of Algol 60, where an argument expression is not evaluated unless its value is needed by the procedure. Scheme’s model of arithmetic is designed to remain as in- dependent as possible of the particular ways in which num- bers 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 be- tween 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 cor- responds to the mathematical ideal, and inexa


key: chroma:document
string_value:
ct arithmetic on approximations. As in Common Lisp, exact arithmetic is not limited to integers. 1.2. Syntax Scheme, like most dialects of Lisp, employs a fully paren- thesized preﬁx notation for programs and (other) data; the grammar of Scheme generates a sublanguage of the lan- guage used for data. An important consequence of this sim- ple, uniform representation is the susceptibility of Scheme programs and data to uniform treatment by other Scheme programs. For example, the eval procedure evaluates a Scheme program expressed as data. Theread procedure performs syntactic as well as lexical decomposition of the data it reads. The read procedure parses its input as data (section 7.1.2 ), not as program. The formal syntax of Scheme is described in section 7.1. 1.3. Notation and terminology 1.3.1. Primitive, library, and optional features It is required that every implementation of Scheme support all features that are not marked as being optional . Imple- mentations are free to omit optional features of Scheme 


key: chroma:document
string_value:
or to add extensions, provided the extensions are not in conﬂict with the language reported here. In particular, implementations must support portable code by providing a syntactic mode that preempts no lexical conventions of this report. To aid in understanding and implementing Scheme, some features are marked as library . These can be easily imple- mented in terms of the other, primitive, features. They are redundant in the strict sense of the word, but they capture common patterns of usage, and are therefore provided as convenient abbreviations.4 Revised5Scheme 1.3.2. Error situations and unspeciﬁed behavior When speaking of an error situation, this report uses the phrase “an error is signalled” to indicate that implemen- tations must detect and report the error. If such wording does not appear in the discussion of an error, then imple- mentations are not required to detect or report the error, though they are encouraged to do so. An error situation that implementations are not required to detect is usuall


key: chroma:document
string_value:
y referred to simply as “an error.” For example, it is an error for a procedure to be passed an argument that the procedure is not explicitly speciﬁed to handle, even though such domain errors are seldom men- tioned in this report. Implementations may extend a pro- cedure’s domain of deﬁnition to include such arguments. This report uses the phrase “may report a violation of an implementation restriction” to indicate circumstances un- der which an implementation is permitted to report that it is unable to continue execution of a correct program be- cause of some restriction imposed by the implementation. Implementation restrictions are of course discouraged, but implementations are encouraged to report violations of im- plementation restrictions. For example, an implementation may report a violation of an implementation restriction if it does not have enough storage to run a program. If the value of an expression is said to be “unspeciﬁed,” then the expression must evaluate to some object without signalling an


key: chroma:document
string_value:
 error, but the value depends on the imple- mentation; this report explicitly does not say what value should be returned. 1.3.3. Entry format Chapters 4and6are organized into entries. Each entry de- scribes one language feature or a group of related features, where a feature is either a syntactic construct or a built-in procedure. An entry begins with one or more header lines of the form template category for required, primitive features, or template qualiﬁer category where qualiﬁer is either “library” or “optional” as deﬁned in section 1.3.1 . Ifcategory is “syntax”, the entry describes an expression type, and the template gives the syntax of the expression type. Components of expressions are designated by syn- tactic variables, which are written using angle brackets, for example,⟨expression⟩,⟨variable⟩. Syntactic variables should be understood to denote segments of program text; for example,⟨expression⟩stands for any string of charac- ters which is a syntactically valid expression. The notation⟨thing 1⟩... 


key: chroma:document
string_value:
indicates zero or more occurrences of a ⟨thing⟩, and ⟨thing 1⟩⟨thing 2⟩... indicates one or more occurrences of a ⟨thing⟩. Ifcategory is “procedure”, then the entry describes a pro- cedure, and the header line gives a template for a call to the procedure. Argument names in the template are italicized . Thus the header line (vector-ref vector k) procedure indicates that the built-in procedure vector-ref takes two arguments, a vector vector and an exact non-negative in- teger k(see below). The header lines (make-vector k) procedure (make-vector k ﬁll) procedure indicate that the make-vector procedure must be deﬁned to take either one or two arguments. It is an error for an operation to be presented with an ar- gument that it is not speciﬁed to handle. For succinctness, we follow the convention that if an argument name is also the name of a type listed in section 3.2, then that argu- ment must be of the named type. For example, the header line forvector-ref given above dictates that the ﬁrst ar- gument to vector


key: chroma:document
string_value:
-ref must be a vector. The following naming conventions also imply type restrictions: obj any object list,list1,... listj,... list (see section 6.3.2 ) z,z1,... zj,... complex number x,x1,... xj,... real number y,y1,... yj,... real number q,q1,... qj,... rational number n,n1,... nj,... integer k,k1,... kj,... exact non-negative integer 1.3.4. Evaluation examples The symbol “=⇒” used in program examples should be read “evaluates to.” For example, (* 5 8) =⇒40 means that the expression (* 5 8) evaluates to the ob- ject40. Or, more precisely: the expression given by the sequence of characters “ (* 5 8) ” evaluates, in the initial environment, to an object that may be represented exter- nally by the sequence of characters “ 40”. See section 3.3 for a discussion of external representations of objects. 1.3.5. Naming conventions By convention, the names of procedures that always return a boolean value usually end in “ ?”. Such procedures are called predicates.2. Lexical conventions 5 By convention, the names of proc


key: chroma:document
string_value:
edures that store values into previously allocated locations (see section 3.4) usually end in “!”. Such procedures are called mutation proce- dures. By convention, the value returned by a mutation procedure is unspeciﬁed. By convention, “ ->” appears within the names of proce- dures that take an object of one type and return an anal- ogous 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. 2. Lexical conventions 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 7.1. Upper and lower case forms of a letter are never distin- guished except within character and string constants. For example, Foois the same identiﬁer as FOO, and#x1AB is the same number as #X1ab . 2.1. Identiﬁers Most identiﬁers allowed by other programming languages are also acceptable to Scheme. The precise rules for form- ing identiﬁers vary among implementations of


key: chroma:document
string_value:
 Scheme, but in all implementations a sequence of letters, digits, and “ex- tended alphabetic characters” that begins with a character that cannot begin a number is an identiﬁer. In addition, +,-, and...are identiﬁers. Here are some examples of identiﬁers: lambda q list->vector soup + V17a <=? a34kTMNs the-word-recursion-has-many-meanings Extended alphabetic characters may be used within iden- tiﬁers as if they were letters. The following are extended alphabetic characters: ! $ % & * + - . / : < = > ? @ ^ _ ~ See section 7.1.1 for a formal syntax of identiﬁers. Identiﬁers have two uses within Scheme programs: •Any identiﬁer may be used as a variable or as a syn- tactic keyword (see sections 3.1and4.3). •When an identiﬁer appears as a literal or within a literal (see section 4.1.2 ), it is being used to denote a symbol (see section 6.3.3 ).2.2. Whitespace and comments Whitespace characters are spaces and newlines. (Imple- mentations typically provide additional whitespace char- acters such as tab or page break


key: chroma:document
string_value:
.) 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 identiﬁer or number, but is otherwise insigniﬁ- cant. Whitespace may occur between any two tokens, but not within a token. Whitespace may also occur inside a string, where it is signiﬁcant. A semicolon ( ;) indicates the start of a comment. The comment continues to the end of the line on which the semicolon appears. Comments are invisible to Scheme, but the end of the line is visible as whitespace. This prevents a comment from appearing in the middle of an identiﬁer or number. ;;; The FACT procedure computes the factorial ;;; of a non-negative integer. (define fact (lambda (n) (if (= n 0) 1 ;Base case: return 1 (* n (fact (- n 1)))))) 2.3. Other notations For a description of the notations used for numbers, see section 6.2. . + - These are used in numbers, and may also occur anywhere in an identiﬁer except as the ﬁrst charac- ter. A delimited plus or minus si


key: chroma:document
string_value:
gn by itself is also an identiﬁer. A delimited period (not occurring within a number or identiﬁer) is used in the notation for pairs (section 6.3.2 ), and to indicate a rest-parameter in a formal parameter list (section 4.1.4 ). A delimited se- quence of three successive periods is also an identiﬁer. ( )Parentheses are used for grouping and to notate lists (section 6.3.2 ). ’The single quote character is used to indicate literal data (section 4.1.2 ). `The backquote character is used to indicate almost- constant data (section 4.2.6 ). , ,@ The character comma and the sequence comma at- sign are used in conjunction with backquote (sec- tion4.2.6 ). "The double quote character is used to delimit strings (section 6.3.5 ).6 Revised5Scheme \Backslash is used in the syntax for character constants (section 6.3.4 ) and as an escape character within string constants (section 6.3.5 ). [ ] { } | Left and right square brackets and curly braces and vertical bar are reserved for possible future exten- sions to the language


key: chroma:document
string_value:
. #Sharp sign is used for a variety of purposes depending on the character that immediately follows it: #t #f These are the boolean constants (section 6.3.1 ). #\This introduces a character constant (section 6.3.4 ). #(This introduces a vector constant (section 6.3.6 ). Vec- tor constants are terminated by ). #e #i #b #o #d #x These are used in the notation for numbers (section 6.2.4 ). 3. Basic concepts 3.1. Variables, syntactic keywords, and re- gions An identiﬁer may name a type of syntax, or it may name a location where a value can be stored. An identiﬁer that names a type of syntax is called a syntactic keyword and is said to be bound to that syntax. An identiﬁer that names a location is called a variable and is said to be bound to that location. The set of all visible bindings in eﬀect at some point in a program is known as the environment in eﬀect 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 sometim


key: chroma:document
string_value:
es 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 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 key- words are listed in section 4.3. The most fundamental of the variable binding constructs is the lambda expression, because all other variable binding constructs can be ex- plained in terms of lambda expressions. The other variable binding constructs are let,let* ,letrec , anddoexpres- sions (see sections 4.1.4 ,4.2.2 , and 4.2.4 ). Like Algol and Pascal, and unlike most other dialects of Lisp except for Common Lisp, Scheme is a statically scoped language with block structure. To each place where an identiﬁer is bound in a program there corresponds a region of the program text within which the bi


key: chroma:document
string_value:
nding is visible.The region is determined by the particular binding con- struct that establishes the binding; if the binding is estab- lished by a lambda expression, for example, then its region is the entire lambda expression. Every mention of an iden- tiﬁer refers to the binding of the identiﬁer that established the innermost of the regions containing the use. If there is no binding of the identiﬁer whose region contains the use, then the use refers to the binding for the variable in the top level environment, if any (chapters 4and6); if there is no binding for the identiﬁer, it is said to be unbound . 3.2. Disjointness of types No object satisﬁes more than one of the following predi- cates: boolean? pair? symbol? number? char? string? vector? port? procedure? These predicates deﬁne the types boolean ,pair,symbol , number ,char (orcharacter ),string ,vector ,port, and pro- cedure . The empty list is a special object of its own type; it satisﬁes none of the above predicates. Although there is a separate bool


key: chroma:document
string_value:
ean type, any Scheme value can be used as a boolean value for the purpose of a conditional test. As explained in section 6.3.1 , 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. 3.3. External representations An important concept in Scheme (and Lisp) is that of the external representation of an object as a sequence of char- acters. For example, an external representation of the inte- ger 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 neces- sarily unique. The integer 28 also has representations “#e28.000 ” and “#x1c ”, and the list in the previous para- graph also has the representations “ ( 08 13 ) ” and “(8 . (13 . ())) ” (see section 6.3.2 ). Many objects have standard external representations, but some, such as procedures, do not have 


key: chroma:document
string_value:
standard represen- tations (although particular implementations may deﬁne representations for them). An external representation may be written in a program to obtain the corresponding object (see quote , section 4.1.2 ).3. Basic concepts 7 External representations can also be used for input and output. The procedure read (section 6.6.2 ) parses ex- ternal representations, and the procedure write (sec- tion6.6.3 ) generates them. Together, they provide an elegant and powerful input/output facility. Note that the sequence of characters “ (+ 2 6) ” isnotan external representation of the integer 8, even though it isan expression evaluating to the integer 8; rather, it is an exter- nal representation of a three-element 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 may not be obvious out of context whether a given sequ


key: chroma:document
string_value:
ence of char- acters 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 6. 3.4. Storage model Variables and objects such as pairs, vectors, and strings implicitly denote locations or sequences of locations. A string, for example, denotes as many locations as there are characters in the string. (These locations need not correspond to a full machine word.) A new value may be stored into one of these locations using the string-set! 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,vector-ref , orstring-ref , is equivalent in the sense of eqv? (section 6.1) to the object last stored in


key: chroma:document
string_value:
 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 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. In many systems it is desirable for constants (i.e. the val- ues of literal expressions) to reside in read-only-memory. To express this, it is convenient to imagine that every object that denotes locations is associated with a ﬂag telling whether that object is mutable or immutable. In such systems literal constants and the strings returned by symbol->string are immutable objects, while all objectscreated 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


key: chroma:document
string_value:
 by an immutable object. 3.5. Proper tail recursion Implementations of Scheme are required to be properly tail- recursive . Procedure calls that occur in certain syntactic contexts deﬁned below are ‘tail calls’. A Scheme imple- mentation is properly tail-recursive if it supports an un- bounded number of active tail calls. A call is active if the called procedure may still return. Note that this in- cludes calls that may be returned from either by the cur- rent continuation or by continuations captured earlier by call-with-current-continuation 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 deﬁnition of proper tail recur- sion can be found in [ 8]. 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 


key: chroma:document
string_value:
might use a new con- tinuation 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 tail-recursive implementation re- turns to that continuation directly. Proper tail recursion was one of the central ideas in Steele and Sussman’s original version of Scheme. Their ﬁrst Scheme in- terpreter implemented both functions and actors. Control ﬂow was expressed using actors, which diﬀered 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 ﬁnished 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. Atail call is a procedure call that occurs in a tail con- text. Tail contexts are deﬁned inductively. Note that a tail context is always determined with respect to a p


key: chroma:document
string_value:
articular lambda expression. •The last expression within the body of a lambda ex- pression, shown as ⟨tail expression⟩below, occurs in a tail context. (lambda⟨formals⟩ ⟨deﬁnition⟩*⟨expression⟩*⟨tail expression⟩) •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 in8 Revised5Scheme the grammar given in chapter 7by replacing some oc- currences of⟨expression⟩with⟨tail expression⟩. Only those rules that contain tail contexts are shown here. (if⟨expression⟩ ⟨tail expression⟩ ⟨tail expression⟩) (if⟨expression⟩ ⟨tail expression⟩) (cond⟨cond clause⟩+) (cond⟨cond clause⟩*(else⟨tail sequence⟩)) (case⟨expression⟩ ⟨case clause⟩+) (case⟨expression⟩ ⟨case clause⟩* (else⟨tail sequence⟩)) (and⟨expression⟩*⟨tail expression⟩) (or⟨expression⟩*⟨tail expression⟩) (let (⟨binding spec⟩*)⟨tail body⟩) (let⟨variable⟩(⟨binding spec⟩*)⟨tail body⟩) (let* (⟨binding spec⟩*)⟨tail body⟩) (letrec (⟨binding spec⟩*)⟨tail body⟩) (let-sy


key: chroma:document
string_value:
ntax (⟨syntax spec⟩*)⟨tail body⟩) (letrec-syntax ( ⟨syntax spec⟩*)⟨tail body⟩) (begin⟨tail sequence⟩) (do (⟨iteration spec⟩*) (⟨test⟩ ⟨tail sequence⟩) ⟨expression⟩*) where ⟨cond clause⟩ −→(⟨test⟩ ⟨tail sequence⟩) ⟨case clause⟩ −→((⟨datum⟩*)⟨tail sequence⟩) ⟨tail body⟩ −→ ⟨ deﬁnition⟩*⟨tail sequence⟩ ⟨tail sequence⟩ −→ ⟨ expression⟩*⟨tail expression⟩ •If acond expression is in a tail context, and has a clause of the form (⟨expression 1⟩=>⟨expression 2⟩) then the (implied) call to the procedure that results from the evaluation of ⟨expression 2⟩is in a tail context. ⟨expression 2⟩itself is not in a tail context. Certain built-in procedures are also required to perform tail calls. The ﬁrst argument passed to apply and to call-with-current-continuation , and the second argu- ment passed to call-with-values , must be called via a tail call. Similarly, eval must evaluate its 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 cal


key: chroma:document
string_value:
ls to gorhare tail calls. The reference to xis 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 are allowed, but not required, to recog- nize that some non-tail calls, such as the call to habove, can be evaluated as though they were tail calls. In the example above, theletexpression could be compiled as a tail call to h. (The possibility of hreturning an unexpected number of values can be ignored, because in that case the eﬀect of the letis explicitly unspeciﬁed and implementation-dependent.) 4. Expressions Expression types are categorized as primitive orderived . Primitive expression types include variables and procedure calls. Derived expression types are not semantically prim- itive, but can instead be deﬁned as macros. With the ex- ception of quasiquote , whose macro deﬁnition is complex, the derived expressions are classiﬁed as library features. Suitable deﬁnitions are given in section 7.3. 4.1. Primitive expre


key: chroma:document
string_value:
ssion types 4.1.1. Variable references ⟨variable⟩ syntax An expression consisting of a variable (section 3.1) 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) x =⇒28 4.1.2. Literal expressions (quote⟨datum⟩) syntax ’⟨datum⟩ syntax ⟨constant⟩ syntax (quote⟨datum⟩)evaluates to⟨datum⟩.⟨Datum⟩may be any external representation of a Scheme object (see sec- tion3.3). 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)4. Expressions 9 (quote⟨datum⟩)may 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) ’’a =⇒(quote a) Numerical constants, string constants, character constants, and boolean constants evaluate “to themselves”; they need not be quoted. ’"abc" =⇒"abc" "abc" =⇒"abc" ’145932 =⇒145


key: chroma:document
string_value:
932 145932 =⇒145932 ’#t =⇒#t #t =⇒#t As noted in section 3.4, it is an error to alter a constant (i.e. the value of a literal expression) using a mutation pro- cedure like set-car! orstring-set! . 4.1.3. Procedure calls (⟨operator⟩ ⟨operand 1⟩...) syntax A procedure call is written by simply enclosing in paren- theses expressions for the procedure to be called and the arguments to be passed to it. The operator and operand expressions are evaluated (in an unspeciﬁed order) and the resulting procedure is passed the resulting arguments. (+ 3 4) =⇒7 ((if #f + *) 3 4) =⇒12 A number of procedures are available as the values of vari- ables in the initial environment; for example, the addition and multiplication procedures in the above examples are the values of the variables +and*. New procedures are cre- ated by evaluating lambda expressions (see section 4.1.4 ). Procedure calls may return any number of values (see values in section 6.4). With the exception of values the procedures available in the initial environm


key: chroma:document
string_value:
ent return one value or, for procedures such as apply , pass on the values returned by a call to one of their arguments. Procedure calls are also called combinations . Note: In contrast to other dialects of Lisp, the order of evaluation is unspeciﬁed, and the operator expression and the operand expressions are always evaluated with the same evalu- ation rules. Note: Although the order of evaluation is otherwise unspeci- ﬁed, the eﬀect 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 diﬀerently for each procedure call.Note: In many dialects of Lisp, the empty combination, (), is a legitimate expression. In Scheme, combinations must have at least one subexpression, so ()is not a syntactically valid expression. 4.1.4. Procedures (lambda⟨formals⟩ ⟨body⟩) syntax Syntax:⟨Formals⟩should be a formal arguments list as described below, and ⟨body⟩should be a sequence of one or more expressi


key: chroma:document
string_value:
ons. Semantics: Alambda expression evaluates to a procedure. The environment in eﬀect 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 evalu- ated will be extended by binding the variables in the formal argument list to fresh locations, the corresponding actual argument values will be stored in those locations, and the expressions in the body of the lambda expression will be evaluated sequentially in the extended environment. The result(s) of the last expression in the body will be returned as the result(s) of the procedure call. (lambda (x) (+ x x)) =⇒ a procedure ((lambda (x) (+ x x)) 4) =⇒8 (define reverse-subtract (lambda (x y) (- y x))) (reverse-subtract 7 10) =⇒3 (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (add4 6) =⇒10 ⟨Formals⟩should have one of the following forms: •(⟨variable 1⟩...): The procedure takes a ﬁxed num- ber of arguments; when the procedure


key: chroma:document
string_value:
 is called, the arguments will be stored in the bindings of the corre- sponding variables. • ⟨variable⟩: The procedure takes any number of ar- guments; when the procedure is called, the sequence of actual arguments is converted into a newly allo- cated list, and the list is stored in the binding of the ⟨variable⟩. •(⟨variable 1⟩...⟨variablen⟩.⟨variablen+1⟩): If a space-delimited period precedes the last variable, then the procedure takes nor more arguments, where n is the number of formal arguments before the period (there must be 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.10 Revised5Scheme 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 wit


key: chroma:document
string_value:
h a storage location, in order to make eqv? andeq?work on procedures (see section 6.1). 4.1.5. Conditionals (if⟨test⟩ ⟨consequent⟩ ⟨alternate⟩) syntax (if⟨test⟩ ⟨consequent⟩) syntax Syntax:⟨Test⟩,⟨consequent⟩, and⟨alternate⟩may be arbi- trary expressions. Semantics: Anifexpression is evaluated as follows: ﬁrst, ⟨test⟩is evaluated. If it yields a true value (see sec- tion6.3.1 ), then⟨consequent⟩is evaluated and its value(s) is(are) returned. Otherwise ⟨alternate⟩is evaluated and its value(s) is(are) returned. If ⟨test⟩yields a false value and no⟨alternate⟩is speciﬁed, then the result of the expression is unspeciﬁed. (if (> 3 2) ’yes ’no) =⇒yes (if (> 2 3) ’yes ’no) =⇒no (if (> 3 2) (- 3 2) (+ 3 2)) =⇒1 4.1.6. Assignments (set!⟨variable⟩ ⟨expression⟩) syntax ⟨Expression⟩is evaluated, and the resulting value is stored in the location to which ⟨variable⟩is bound.⟨Variable⟩ must be bound either in some region enclosing the set! expression or at top level. The result of the set! expression is unspeciﬁed. (define x


key: chroma:document
string_value:
 2) (+ x 1) =⇒3 (set! x 4) =⇒ unspeciﬁed (+ x 1) =⇒5 4.2. Derived expression types The constructs in this section are hygienic, as discussed in section 4.3. For reference purposes, section 7.3gives macro deﬁnitions that will convert most of the constructs described in this section into the primitive constructs de- scribed in the previous section.4.2.1. Conditionals (cond⟨clause 1⟩ ⟨clause 2⟩...) library syntax Syntax: Each⟨clause⟩should be of the form (⟨test⟩ ⟨expression 1⟩...) where⟨test⟩is any expression. Alternatively, a ⟨clause⟩ may be of the form (⟨test⟩=>⟨expression⟩) The last⟨clause⟩may be an “else clause,” which has the form (else⟨expression 1⟩ ⟨expression 2⟩...). Semantics: Acond expression is evaluated by evaluating the⟨test⟩expressions of successive ⟨clause⟩s in order until one of them evaluates to a true value (see section 6.3.1 ). When a⟨test⟩evaluates to a true value, then the remain- ing⟨expression⟩s in its⟨clause⟩are evaluated in order, and the result(s) of the last ⟨expression⟩in the⟨clause⟩ 


key: chroma:document
string_value:
is(are) returned as the result(s) of the entire cond expres- sion. If the selected ⟨clause⟩contains only the ⟨test⟩and no ⟨expression⟩s, then the value of the ⟨test⟩is returned as the result. If the selected ⟨clause⟩uses the=>alternate form, then the⟨expression⟩is evaluated. Its value must be a pro- cedure that accepts one argument; this procedure is then called on the value of the ⟨test⟩and the value(s) returned by this procedure is(are) returned by the cond expression. If all⟨test⟩s evaluate to false values, and there is no else clause, then the result of the conditional expression is un- speciﬁed; if there is an else clause, then its ⟨expression⟩s are evaluated, and the value(s) of the last one is(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 1⟩ ⟨clause 2⟩...) library syntax Syntax:⟨Key⟩may be any expression. Each ⟨clause⟩ should have the form ((⟨da


key: chroma:document
string_value:
tum 1⟩...)⟨expression 1⟩ ⟨expression 2⟩...), where each⟨datum⟩is an external representation of some object. All the ⟨datum⟩s must be distinct. The last ⟨clause⟩may be an “else clause,” which has the form (else⟨expression 1⟩ ⟨expression 2⟩...). Semantics: Acase expression is evaluated as follows. ⟨Key⟩is evaluated and its result is compared against each ⟨datum⟩. If the result of evaluating ⟨key⟩is equivalent (in the sense of eqv? ; see section 6.1) to a⟨datum⟩, then the expressions in the corresponding ⟨clause⟩are evaluated from left to right and the result(s) of the last expression in4. Expressions 11 the⟨clause⟩is(are) returned as the result(s) of the case ex- pression. If the result of evaluating ⟨key⟩is diﬀerent from every⟨datum⟩, then if there is an else clause its expres- sions are evaluated and the result(s) of the last is(are) the result(s) of the case expression; otherwise the result of the case expression is unspeciﬁed. (case (* 2 3) ((2 3 5 7) ’prime) ((1 4 6 8 9) ’composite)) =⇒composite (case (car


key: chroma:document
string_value:
 ’(c d)) ((a) ’a) ((b) ’b)) =⇒ unspeciﬁed (case (car ’(c d)) ((a e i o u) ’vowel) ((w y) ’semivowel) (else ’consonant)) =⇒consonant (and⟨test1⟩...) library syntax The⟨test⟩expressions are evaluated from left to right, and the value of the ﬁrst expression that evaluates to a false value (see section 6.3.1 ) is returned. Any remaining ex- pressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then #tis returned. (and (= 2 2) (> 2 1)) =⇒#t (and (= 2 2) (< 2 1)) =⇒#f (and 1 2 ’c ’(f g)) =⇒(f g) (and) =⇒#t (or⟨test1⟩...) library syntax The⟨test⟩expressions are evaluated from left to right, and the value of the ﬁrst expression that evaluates to a true value (see section 6.3.1 ) is returned. Any remaining ex- pressions are not evaluated. If all expressions evaluate to false values, the value of the last expression is returned. If there are no expressions then #fis returned. (or (= 2 2) (> 2 1)) =⇒#t (or (= 2 2) (< 2 1)) =


key: chroma:document
string_value:
⇒#t (or #f #f #f) =⇒#f (or (memq ’b ’(a b c)) (/ 3 0)) =⇒(b c) 4.2.2. Binding constructs The three binding constructs let,let* , andletrec give Scheme a block structure, like Algol 60. The syntax of the three constructs is identical, but they diﬀer in the regions they establish for their variable bindings. In a letex- pression, the initial values are computed before any of the variables become bound; in a let* expression, the bind- ings and evaluations are performed sequentially; while in a letrec expression, all the bindings are in eﬀect while theirinitial values are being computed, thus allowing mutually recursive deﬁnitions. (let⟨bindings⟩ ⟨body⟩) library syntax Syntax:⟨Bindings⟩should have the form ((⟨variable 1⟩ ⟨init1⟩)...), where each⟨init⟩is an expression, and ⟨body⟩should be a sequence of one or more expressions. It is an error for a ⟨variable⟩to appear more than once in the list of variables being bound. Semantics: The⟨init⟩s are evaluated in the current envi- ronment (in some unspeciﬁed order), the


key: chroma:document
string_value:
 ⟨variable⟩s are bound to fresh locations holding the results, the ⟨body⟩is evaluated in the extended environment, and the value(s) of the last expression of ⟨body⟩is(are) returned. Each bind- ing of a⟨variable⟩has⟨body⟩as its region. (let ((x 2) (y 3)) (* x y)) =⇒6 (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))) =⇒35 See also named let, section 4.2.4 . (let*⟨bindings⟩ ⟨body⟩) library syntax Syntax:⟨Bindings⟩should have the form ((⟨variable 1⟩ ⟨init1⟩)...), and⟨body⟩should be a sequence of one or more expres- sions. Semantics: Let* 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 thelet* expression to the right of the binding. Thus the second binding is done in an environment in which the ﬁrst binding is visible, and so on. (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))) =⇒70 (letrec⟨bindings⟩ ⟨body⟩) library syntax Syntax:⟨Bindings⟩should have the form ((⟨variable 1⟩ ⟨init1⟩)...), and⟨bo


key: chroma:document
string_value:
dy⟩should be a sequence of one or more expres- sions. It is an error for a ⟨variable⟩to appear more than once in the list of variables being bound. Semantics: The⟨variable⟩s are bound to fresh locations holding undeﬁned values, the ⟨init⟩s are evaluated in the12 Revised5Scheme resulting environment (in some unspeciﬁed order), each ⟨variable⟩is assigned to the result of the corresponding ⟨init⟩, the⟨body⟩is evaluated in the resulting environment, and the value(s) of the last expression in ⟨body⟩is(are) re- turned. Each binding of a ⟨variable⟩has the entire letrec expression as its region, making it possible to deﬁne mutu- ally 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: it must be possible to evaluate each ⟨init⟩without assigning or refer- ring to the value of any ⟨variable⟩. If this restriction is violated, then it is an error. The restriction is necessa


key: chroma:document
string_value:
ry because Scheme passes arguments by value rather than by name. In the most common uses of letrec , all the⟨init⟩s arelambda expressions and the restriction is satisﬁed au- tomatically. 4.2.3. Sequencing (begin⟨expression 1⟩ ⟨expression 2⟩...)library syntax The⟨expression⟩s are evaluated sequentially from left to right, and the value(s) of the last ⟨expression⟩is(are) re- turned. This expression type is used to sequence side ef- fects such as input and output. (define x 0) (begin (set! x 5) (+ x 1)) =⇒6 (begin (display "4 plus 1 equals ") (display (+ 4 1))) =⇒ unspeciﬁed and prints 4 plus 1 equals 5 4.2.4. Iteration (do ((⟨variable 1⟩ ⟨init1⟩ ⟨step 1⟩) library syntax ...) (⟨test⟩ ⟨expression⟩...) ⟨command⟩...) Dois an iteration construct. It speciﬁes 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 atermination condition is met, the loop exits after evaluating the⟨expression⟩s. Doexpressions are evaluated as follows: The ⟨init


key: chroma:document
string_value:
⟩ex- pressions are evaluated (in some unspeciﬁed order), the ⟨variable⟩s are bound to fresh locations, the results of the⟨init⟩expressions are stored in the bindings of the ⟨variable⟩s, and then the iteration phase begins. Each iteration begins by evaluating ⟨test⟩; if the result is false (see section 6.3.1 ), then the⟨command⟩expressions are evaluated in order for eﬀect, the ⟨step⟩expressions are evaluated in some unspeciﬁed order, the ⟨variable⟩s are bound to fresh locations, the results of the ⟨step⟩s are stored in the bindings of the ⟨variable⟩s, and the next iter- ation begins. If⟨test⟩evaluates to a true value, then the ⟨expression⟩s are evaluated from left to right and the value(s) of the last⟨expression⟩is(are) returned. If no ⟨expression⟩s are present, then the value of the doexpression is unspeciﬁed. The region of the binding of a ⟨variable⟩consists of the entiredoexpression except for the ⟨init⟩s. It is an error for a⟨variable⟩to appear more than once in the list of do variables. A⟨step⟩may be omit


key: chroma:document
string_value:
ted, in which case the eﬀect is the same as if (⟨variable⟩ ⟨init⟩ ⟨variable⟩)had been written instead of (⟨variable⟩ ⟨init⟩). (do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) =⇒#(0 1 2 3 4) (let ((x ’(1 3 5 7 9))) (do ((x x (cdr x)) (sum 0 (+ sum (car x)))) ((null? x) sum))) =⇒25 (let⟨variable⟩ ⟨bindings⟩ ⟨body⟩) library syntax “Namedlet” is a variant on the syntax of letwhich pro- vides a more general looping construct than doand may also be used to express recursions. It has the same syn- tax and semantics as ordinary letexcept that⟨variable⟩ is bound within⟨body⟩to a procedure whose formal argu- ments are the bound variables and whose body is ⟨body⟩. Thus the execution of ⟨body⟩may 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) (loop (cdr numbers) (cons (car numbers) nonneg) neg)) ((< (car numbers) 0)4. Expressions 13 (loop (cdr numbers) nonne


key: chroma:document
string_value:
g (cons (car numbers) neg))))) =⇒((6 1 3) (-5 -2)) 4.2.5. Delayed evaluation (delay⟨expression⟩) library syntax Thedelay construct is used together with the proce- dureforce to implement lazy evaluation orcall by need . (delay⟨expression⟩)returns an object called a promise which at some point in the future may be asked (by the force procedure) to evaluate ⟨expression⟩, and deliver the resulting value. The eﬀect of ⟨expression⟩returning multi- ple values is unspeciﬁed. See the description of force (section 6.4) for a more com- plete description of delay . 4.2.6. Quasiquotation (quasiquote⟨qq template⟩) syntax `⟨qq template⟩ syntax “Backquote” or “quasiquote” expressions are useful for constructing a list or vector structure when most 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 th


key: chroma:document
string_value:
e comma is evaluated (“unquoted”) and its result is inserted into the structure instead of the comma and the expres- sion. If a comma appears followed immediately by an at- sign (@), then the following expression must evaluate to a list; the opening and closing parentheses of the list are then “stripped away” and the elements of the list are in- serted in place of the comma at-sign expression sequence. A comma at-sign should only appear within a list or vector ⟨qq template⟩. `(list ,(+ 1 2) 4) =⇒(list 3 4) (let ((name ’a)) `(list ,name ’,name)) =⇒(list a (quote a)) `(a ,(+ 1 2) ,@(map abs ’(4 -5 6)) b) =⇒(a 3 4 5 6 b) `(( foo ,(- 10 3)) ,@(cdr ’(c)) . ,(car ’(cons))) =⇒((foo 7) . cons) `#(10 5 ,(sqrt 4) ,@(map sqrt ’(16 9)) 8) =⇒#(10 5 2 4 3 8) Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nest- ing level as the outermost backquote. The nesting level in- creases by one inside each successive quasiquotation, and decreases by one inside each unquotatio


key: chroma:document
string_value:
n.`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) =⇒(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) 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 (unquote-splicing ⟨expression⟩). The ex- ternal syntax generated by write for two-element lists whose car is one of these symbols may vary between im- plementations. (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)) Unpredictable behavior can result if any of the symbols quasiquote ,unquote , orunquote-splicing appear in po- sitions within a⟨qq template⟩otherwise than as described above. 4.3. Macros Scheme programs can deﬁne and use new derived expres- sion types, called macros . Program-deﬁned expression types have the syntax (⟨keyword⟩ ⟨datum⟩...) where⟨keyword⟩is a


key: chroma:document
string_value:
n identiﬁer that uniquely determines the expression type. This identiﬁer is called the syntactic keyword , or simply keyword , of the macro. The number of the⟨datum⟩s, and their syntax, depends on the expression type. Each instance of a macro is called a useof the macro. The set of rules that speciﬁes how a use of a macro is transcribed into a more primitive expression is called the transformer of the macro. The macro deﬁnition facility consists of two parts: •A set of expressions used to establish that certain iden- tiﬁers are macro keywords, associate them with macro transformers, and control the scope within which a macro is deﬁned, and •a pattern language for specifying macro transformers. The syntactic keyword of a macro may shadow variable bindings, and local variable bindings may shadow keyword bindings. All macros deﬁned using the pattern language are “hygienic” and “referentially transparent” and thus preserve Scheme’s lexical scoping [ 14,15,2,7,9]:14 Revised5Scheme •If a macro transformer inserts a


key: chroma:document
string_value:
 binding for an identi- ﬁer (variable or keyword), the identiﬁer will in eﬀect be renamed throughout its scope to avoid conﬂicts with other identiﬁers. Note that a define at top level may or may not introduce a binding; see section 5.2. •If a macro transformer inserts a free reference to an identiﬁer, the reference refers to the binding that was visible where the transformer was speciﬁed, regardless of any local bindings that may surround the use of the macro. 4.3.1. Binding constructs for syntactic keywords Let-syntax andletrec-syntax are analogous to letand letrec , but they bind syntactic keywords to macro trans- formers instead of binding variables to locations that con- tain values. Syntactic keywords may also be bound at top level; see section 5.3. (let-syntax⟨bindings⟩ ⟨body⟩) syntax Syntax:⟨Bindings⟩should have the form ((⟨keyword⟩ ⟨transformer spec⟩)...) Each⟨keyword⟩is an identiﬁer, each ⟨transformer spec⟩ is an instance of syntax-rules , and⟨body⟩should be a sequence of one or more expressions. It 


key: chroma:document
string_value:
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 envi- ronment obtained by extending the syntactic environment of thelet-syntax expression with macros whose keywords are the⟨keyword⟩s, bound to the speciﬁed transformers. Each binding of a ⟨keyword⟩has⟨body⟩as its region. (let-syntax ((when (syntax-rules () ((when test stmt1 stmt2 ...) (if test (begin stmt1 stmt2 ...)))))) (let ((if #t)) (when if (set! if ’now)) if)) =⇒now (let ((x ’outer)) (let-syntax ((m (syntax-rules () ((m) x)))) (let ((x ’inner)) (m)))) =⇒outer (letrec-syntax ⟨bindings⟩ ⟨body⟩) syntax Syntax: Same as for let-syntax . Semantics: The⟨body⟩is expanded in the syntactic envi- ronment obtained by extending the syntactic environmentof theletrec-syntax expression with macros whose key- words are the⟨keyword⟩s, bound to the speciﬁed trans- formers. Each binding of a ⟨keyword⟩has the⟨bindings⟩ as well as the⟨body⟩within its region, so the transformers can trans


key: chroma:document
string_value:
cribe expressions into uses of the macros intro- duced by the letrec-syntax expression. (letrec-syntax ((my-or (syntax-rules () ((my-or) #f) ((my-or e) e) ((my-or e1 e2 ...) (let ((temp e1)) (if temp temp (my-or e2 ...))))))) (let ((x #f) (y 7) (temp 8) (let odd?) (if even?)) (my-or x (let temp) (if y) y))) =⇒7 4.3.2. Pattern language A⟨transformer spec⟩has the following form: (syntax-rules⟨literals⟩ ⟨syntax rule⟩...) Syntax:⟨Literals⟩is a list of identiﬁers and each ⟨syntax rule⟩should be of the form (⟨pattern⟩ ⟨template⟩) The⟨pattern⟩in a⟨syntax rule⟩is a list⟨pattern⟩that begins with the keyword for the macro. A⟨pattern⟩is either an identiﬁer, a constant, or one of the following (⟨pattern⟩...) (⟨pattern⟩ ⟨pattern⟩... .⟨pattern⟩) (⟨pattern⟩...⟨pattern⟩ ⟨ellipsis⟩) #(⟨pattern⟩...) #(⟨pattern⟩...⟨pattern⟩ ⟨ellipsis⟩) and a template is either an identiﬁer, a constant, or one of the following (⟨element⟩...) (⟨element⟩ ⟨element⟩... .⟨template⟩) #(⟨element⟩...) where an⟨element⟩is a⟨template⟩optionally followed b


key: chroma:document
string_value:
y an⟨ellipsis⟩and an⟨ellipsis⟩is the identiﬁer “ ...” (which cannot be used as an identiﬁer in either a template or a pattern). Semantics: An instance of syntax-rules produces a new macro transformer by specifying a sequence of hygienic4. Expressions 15 rewrite rules. A use of a macro whose keyword is associated with a transformer speciﬁed by syntax-rules is matched against the patterns contained in the ⟨syntax rule⟩s, be- ginning with the leftmost ⟨syntax rule⟩. When a match is found, the macro use is transcribed hygienically according to the template. An identiﬁer that appears in the pattern of a ⟨syntax rule⟩ is a pattern variable , unless it is the keyword that begins the pattern, is listed in ⟨literals⟩, or is the identiﬁer “ ...”. 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⟩. The keyword at the beginning of the pattern in a ⟨syntax rule⟩is not involved i


key: chroma:document
string_value:
n the matching and is not considered a pattern variable or literal identiﬁer. Rationale: The scope of the keyword is determined by the expression or syntax deﬁnition that binds it to the associated macro transformer. If the keyword were a pattern variable or literal identiﬁer, then the template that follows the pattern would be within its scope regardless of whether the keyword were bound by let-syntax or byletrec-syntax . Identiﬁers that appear in ⟨literals⟩are interpreted as literal identiﬁers to be matched against corresponding subforms of the input. A subform in the input matches a literal identiﬁer if and only if it is an identiﬁer and either both its occurrence in the macro expression and its occurrence in the macro deﬁnition have the same lexical binding, or the two identiﬁers are equal and both have no lexical binding. A subpattern followed by ...can match zero or more el- ements of the input. It is an error for ...to appear in ⟨literals⟩. Within a pattern the identiﬁer ...must follow the last element


key: chroma:document
string_value:
 of a nonempty sequence of subpatterns. More formally, an input form Fmatches a pattern Pif and only if: •Pis a non-literal identiﬁer; or •Pis a literal identiﬁer and Fis an identiﬁer with the same binding; or •Pis a list(P1... Pn)andFis a list ofnforms that matchP1throughPn, respectively; or •Pis an improper list (P1P2... Pn.Pn+1)and Fis a list or improper list of nor more forms that matchP1throughPn, respectively, and whose nth “cdr” matches Pn+1; or •Pis of the form (P1... PnPn+1⟨ellipsis⟩)where ⟨ellipsis⟩is the identiﬁer ...andFis a proper list of at least nforms, the ﬁrst nof which match P1 throughPn, respectively, and each remaining element ofFmatchesPn+1; or•Pis a vector of the form #(P1... Pn)andFis a vector ofnforms that match P1throughPn; or •Pis of the form #(P1... PnPn+1⟨ellipsis⟩)where ⟨ellipsis⟩is the identiﬁer ...andFis a vector of nor more forms the ﬁrst nof which match P1throughPn, respectively, and each remaining element of Fmatches Pn+1; or •Pis a datum and Fis equal to Pin the sense of the


key: chroma:document
string_value:
 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 subforms they match in the input. Pattern variables that occur in subpatterns followed by one or more instances of the identiﬁer ...are allowed only in subtemplates that are followed by as many instances of .... They are replaced in the output by all of the subforms they match in the input, distributed as indicated. It is an error if the output cannot be built up as speciﬁed. Identiﬁers that appear in the template but are not pattern variables or the identiﬁer ...are inserted into the output as literal identiﬁers. If a literal identiﬁer is inserted as a free identiﬁer then it refers to the binding of that identiﬁer within whose scope the instance of syntax-rules appears. If a literal identiﬁer is inserted as a bo


key: chroma:document
string_value:
und identiﬁer then it is in eﬀect renamed to prevent inadvertent captures of free identiﬁers. As an example, if letandcond are deﬁned as in section 7.3 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 top-level identiﬁer =>, which the macro transformer treats as a syn- tactic 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.16 Revised5Scheme 5. Program structure 5.1. Programs A Scheme program consists of a sequence of expressions, deﬁnitions, and syntax deﬁnitions. Expressions are de- scribed in chapter 4; deﬁnitions and syntax deﬁnitions are the subject of the rest of the present chapter. Programs are typically stored in ﬁles or entered inter- actively to a running Scheme system, although other paradigm


key: chroma:document
string_value:
s are possible; questions of user interface lie out- side the scope of this report. (Indeed, Scheme would still be useful as a notation for expressing computational methods even in the absence of a mechanical implementation.) Deﬁnitions and syntax deﬁnitions occurring at the top level of a program can be interpreted declaratively. They cause bindings to be created in the top level environment or mod- ify the value of existing top-level bindings. Expressions occurring at the top level of a program are interpreted im- peratively; they are executed in order when the program is invoked or loaded, and typically perform some kind of initialization. At the top level of a program (begin⟨form 1⟩...)is equivalent to the sequence of expressions, deﬁnitions, and syntax deﬁnitions that form the body of the begin . 5.2. Deﬁnitions Deﬁnitions are valid in some, but not all, contexts where expressions are allowed. They are valid only at the top level of a⟨program⟩and at the beginning of a ⟨body⟩. A deﬁnition should have one 


key: chroma:document
string_value:
of the following forms: •(define⟨variable⟩ ⟨expression⟩) •(define (⟨variable⟩ ⟨formals⟩)⟨body⟩) ⟨Formals⟩should be either a sequence of zero or more variables, or a sequence of one or more variables fol- lowed by a space-delimited period and another vari- able (as in a lambda expression). This form is equiv- alent to (define⟨variable⟩ (lambda (⟨formals⟩)⟨body⟩)). •(define (⟨variable⟩.⟨formal⟩)⟨body⟩) ⟨Formal⟩should be a single variable. This form is equivalent to (define⟨variable⟩ (lambda⟨formal⟩ ⟨body⟩)).5.2.1. Top level deﬁnitions At the top level of a program, a deﬁnition (define⟨variable⟩ ⟨expression⟩) has essentially the same eﬀect as the assignment expres- sion (set!⟨variable⟩ ⟨expression⟩) if⟨variable⟩is bound. If⟨variable⟩is not bound, however, then the deﬁnition 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))) (add3 3) =⇒6 (define first car) (first ’(1 2)) =⇒1 Some implemen


key: chroma:document
string_value:
tations of Scheme use an initial environ- ment in which all possible variables are bound to locations, most of which contain undeﬁned values. Top level deﬁni- tions in such an implementation are truly equivalent to assignments. 5.2.2. Internal deﬁnitions Deﬁnitions may occur at the beginning of a ⟨body⟩(that is, the body of a lambda ,let,let* ,letrec ,let-syntax , orletrec-syntax expression or that of a deﬁnition of an appropriate form). Such deﬁnitions are known as internal deﬁnitions as opposed to the top level deﬁnitions described above. The variable deﬁned by an internal deﬁnition is 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))) (foo (+ x 3))) =⇒45 A⟨body⟩containing internal deﬁnitions can always be con- verted into a completely equivalent letrec expression. For example, the letexpression in the above example is equiv- alent to (


key: chroma:document
string_value:
let ((x 5)) (letrec ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3)))) Just as for the equivalent letrec expression, it must be possible to evaluate each ⟨expression⟩of every internal def- inition in a⟨body⟩without assigning or referring to the value of any⟨variable⟩being deﬁned. Wherever an internal deﬁnition may occur (begin ⟨deﬁnition 1⟩...)is equivalent to the sequence of deﬁni- tions that form the body of the begin .6. Standard procedures 17 5.3. Syntax deﬁnitions Syntax deﬁnitions are valid only at the top level of a ⟨program⟩. They have the following form: (define-syntax ⟨keyword⟩ ⟨transformer spec⟩) ⟨Keyword⟩is an identiﬁer, and the ⟨transformer spec⟩ should be an instance of syntax-rules . The top-level syn- tactic environment is extended by binding the ⟨keyword⟩ to the speciﬁed transformer. There is no define-syntax analogue of internal deﬁni- tions. Although macros may expand into deﬁnitions and syntax deﬁnitions in any context that permits them, it is an error for a 


key: chroma:document
string_value:
deﬁnition or syntax deﬁnition to shadow a syntactic keyword whose meaning is needed to determine whether some form in the group of forms that contains the shad- owing deﬁnition is in fact a deﬁnition, or, for internal def- initions, is needed to determine the boundary between the group and the expressions that follow the group. For ex- ample, the following are errors: (define define 3) (begin (define begin list)) (let-syntax ((foo (syntax-rules () ((foo (proc args ...) body ...) (define proc (lambda (args ...) body ...)))))) (let ((x 3)) (foo (plus x y) (+ x y)) (define foo x) (plus foo x))) 6. Standard procedures This chapter describes Scheme’s built-in procedures. The initial (or “top level”) Scheme environment starts out with a number of variables bound to locations containing useful values, most of which are primitive procedures that ma- nipulate data. For example, the variable absis bound to (a location initially containing) a procedure of one argu- ment that computes the absolute value of a number, and 


key: chroma:document
string_value:
the variable +is bound to a procedure that computes sums. Built-in procedures that can easily be written in terms of other built-in procedures are identiﬁed as “library proce- dures”. A program may use a top-level deﬁnition to bind any vari- able. It may subsequently alter any such binding by an assignment (see 4.1.6 ). These operations do not modify the behavior of Scheme’s built-in procedures. Altering anytop-level binding that has not been introduced by a deﬁni- tion has an unspeciﬁed eﬀect on the behavior of the built-in procedures. 6.1. Equivalence predicates Apredicate is a procedure that always returns a boolean value (#tor#f). An equivalence predicate is the compu- tational analogue of a mathematical equivalence relation (it is symmetric, reﬂexive, and transitive). Of the equiva- lence predicates described in this section, eq?is the ﬁnest or most discriminating, and equal? is the coarsest. Eqv? is slightly less discriminating than eq?. (eqv? obj1obj2) procedure Theeqv? procedure deﬁnes a useful equiva


key: chroma:document
string_value:
lence relation on objects. Brieﬂy, it returns #tifobj1and obj2should normally be regarded as the same object. This relation is left slightly open to interpretation, but the following par- tial speciﬁcation of eqv? holds for all implementations of Scheme. Theeqv? procedure returns #tif: •obj1and obj2are both #tor both#f. •obj1and obj2are both symbols and (string=? (symbol->string obj1) (symbol->string obj2)) =⇒#t Note: This assumes that neither obj1norobj2is an “un- interned symbol” as alluded to in section 6.3.3 . This re- port does not presume to specify the behavior of eqv? on implementation-dependent extensions. •obj1andobj2are both numbers, are numerically equal (see=, section 6.2), and are either both exact or both inexact. •obj1and obj2are both characters and are the same character according to the char=? procedure (sec- tion6.3.4 ). •both obj1and obj2are the empty list. •obj1andobj2are pairs, vectors, or strings that denote the same locations in the store (section 3.4). •obj1and obj2are procedures whos


key: chroma:document
string_value:
e location tags are equal (section 4.1.4 ). Theeqv? procedure returns #fif: •obj1and obj2are of diﬀerent types (section 3.2).18 Revised5Scheme •one of obj1and obj2is#tbut the other is #f. •obj1and obj2are symbols but (string=? (symbol->string obj1) (symbol->string obj2)) =⇒#f •one of obj1and obj2is an exact number but the other is an inexact number. •obj1and obj2are numbers for which the =procedure returns#f. •obj1andobj2are characters for which the char=? pro- cedure returns #f. •one of obj1and obj2is the empty list but the other is not. •obj1andobj2are pairs, vectors, or strings that denote distinct locations. •obj1andobj2are procedures that would behave diﬀer- ently (return diﬀerent value(s) or have diﬀerent side eﬀects) for some arguments. (eqv? ’a ’a) =⇒#t (eqv? ’a ’b) =⇒#f (eqv? 2 2) =⇒#t (eqv? ’() ’()) =⇒#t (eqv? 100000000 100000000) =⇒#t (eqv? (cons 1 2) (cons 1 2)) =⇒#f (eqv? (lambda () 1) (lambda () 2)) =⇒#f (eqv? #f ’nil) =⇒#f (let ((p (lambda (x) x))) (eqv? p p)) =⇒#t The following examples illust


key: chroma:document
string_value:
rate 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? "" "") =⇒ unspeciﬁed (eqv? ’#() ’#()) =⇒ unspeciﬁed (eqv? (lambda (x) x) (lambda (x) x)) =⇒ unspeciﬁed (eqv? (lambda (x) x) (lambda (y) y)) =⇒ unspeciﬁed The next set of examples shows the use of eqv? with pro- cedures that have local state. Gen-counter must return a distinct procedure every time, since each procedure has its own internal counter. Gen-loser , however, returns equiv- alent procedures each time, since the local state does not aﬀect the value or side eﬀects of the procedures.(define gen-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (let ((g (gen-counter))) (eqv? g g)) =⇒#t (eqv? (gen-counter) (gen-counter)) =⇒#f (define gen-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (let ((g (gen-loser))) (eqv? g g)) =⇒#t (eqv? (gen-loser) (gen-loser)) =⇒ unspeciﬁed (letrec ((f (lambda () (if (eq


key: chroma:document
string_value:
v? f g) ’both ’f))) (g (lambda () (if (eqv? f g) ’both ’g)))) (eqv? f g)) =⇒ unspeciﬁed (letrec ((f (lambda () (if (eqv? f g) ’f ’both))) (g (lambda () (if (eqv? f g) ’g ’both)))) (eqv? f g)) =⇒#f Since it is an error to modify constant objects (those re- turned by literal expressions), implementations are per- mitted, though not required, to share structure between constants where appropriate. Thus the value of eqv? on constants is sometimes implementation-dependent. (eqv? ’(a) ’(a)) =⇒ unspeciﬁed (eqv? "a" "a") =⇒ unspeciﬁed (eqv? ’(b) (cdr ’(a b))) =⇒ unspeciﬁed (let ((x ’(a))) (eqv? x x)) =⇒#t Rationale: The above deﬁnition of eqv? allows implementa- tions latitude in their treatment of procedures and literals: im- plementations are free either to detect or to 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. (eq? obj1obj2) procedure Eq?is 


key: chroma:document
string_value:
similar to eqv? except that in some cases it is capable of discerning distinctions ﬁner than those detectable by eqv? . Eq?andeqv? are guaranteed to have the same behavior on symbols, booleans, the empty list, pairs, procedures, and non-empty strings and vectors. Eq?’s behavior on numbers and characters is implementation-dependent, but it will al- ways return either true or false, and will return true only wheneqv? would also return true. Eq?may also behave diﬀerently from eqv? on empty vectors and empty strings.6. Standard procedures 19 (eq? ’a ’a) =⇒#t (eq? ’(a) ’(a)) =⇒ unspeciﬁed (eq? (list ’a) (list ’a)) =⇒#f (eq? "a" "a") =⇒ unspeciﬁed (eq? "" "") =⇒ unspeciﬁed (eq? ’() ’()) =⇒#t (eq? 2 2) =⇒ unspeciﬁed (eq? #\A #\A) =⇒ unspeciﬁed (eq? car car) =⇒#t (let ((n (+ 2 3))) (eq? n n)) =⇒ unspeciﬁed (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 eﬃciently than eqv?, for example, as a simp


key: chroma:document
string_value:
le pointer com- parison instead of as some more complicated operation. One reason is that it may not be possible to compute eqv? of two numbers in constant time, whereas eq?implemented as pointer comparison will always ﬁnish in constant time. Eq?may be used likeeqv? in applications using procedures to implement objects with state since it obeys the same constraints as eqv?. (equal? obj1obj2) library procedure Equal? recursively compares the contents of pairs, vectors, and strings, applying eqv? on other objects such as num- bers and symbols. A rule of thumb is that objects are generally equal? if they print the same. Equal? may fail to terminate if its arguments are circular data structures. (equal? ’a ’a) =⇒#t (equal? ’(a) ’(a)) =⇒#t (equal? ’(a (b) c) ’(a (b) c)) =⇒#t (equal? "abc" "abc") =⇒#t (equal? 2 2) =⇒#t (equal? (make-vector 5 ’a) (make-vector 5 ’a)) =⇒#t (equal? (lambda (x) x) (lambda (y) y)) =⇒ unspeciﬁed 6.2. Numbers Numerical computation has traditionally been neglected by the Lisp community. Unt


key: chroma:document
string_value:
il Common Lisp there was no carefully thought out strategy for organizing numerical computation, and with the exception of the MacLisp sys- tem [20] little eﬀort was made to execute numerical code eﬃciently. This report recognizes the excellent work of the Common Lisp committee and accepts many of their rec- ommendations. In some ways this report simpliﬁes and generalizes their proposals in a manner consistent with the purposes of Scheme.It is important to distinguish between the mathemati- cal 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. Machine representations such as ﬁxed point and ﬂoating point are referred to by names such as ﬁxnum and ﬂonum . 6.2.1. Numerical types Mathematically, numbers may be arranged into a tower of subtypes in which each level is a subset of 


key: chroma:document
string_value:
the level above it: number complex real rational integer For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex. The same is true of the Scheme numbers that model 3. For Scheme numbers, these types are deﬁned by the predicates number? ,complex? ,real? , rational? , andinteger? . There is no simple relationship between a number’s type and its representation inside a computer. Although most implementations of Scheme will oﬀer at least two diﬀerent representations of 3, these diﬀerent 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 ﬁxnum, ﬂonum, and perhaps other representations for numbers, this should not be apparent to a casual programmer writing simple programs. It is necessary, however, to distinguish between numbers that are represented exactly and those that may not be. For example, indexes into data structures must be known ex


key: chroma:document
string_value:
actly, as must some polynomial coeﬃcients in a symbolic algebra system. On the other hand, the results of measure- ments are inherently inexact, and irrational numbers may be approximated by rational and therefore inexact approx- imations. 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. 6.2.2. Exactness Scheme numbers are either exact orinexact . A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations. A number20 Revised5Scheme 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. If two implementations produce exact results for a com- putation that did not involve inexact intermediate results, the two ultimate results will be mathematically equivalent. This is 


key: chroma:document
string_value:
generally not true of computations involving inex- act numbers since approximate methods such as ﬂoating point 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 ex- act 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. See sec- tion6.2.3 . With the exception of inexact->exact , the operations de- scribed 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 unaﬀected 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. 6.2.3. Implementation restrictions Im


key: chroma:document
string_value:
plementations of Scheme are not required to implement the whole tower of subtypes given in section 6.2.1 , but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, an implementation in which all numbers are real may still be 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 diﬀerent from the supported range for inex- act numbers of that type. For example, an implementation that uses ﬂonums to represent all its inexact real numbers may support a practically unbounded range of exact inte- gers and rationals while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the ﬂonum format. Furthermore the gaps between the representable inexact integers and ra- tionals are likely to be very large in such an implementatio


key: chroma:document
string_value:
n as the limits of this range are approached. An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists, vectors, and strings or that may result from computing the length of a list, vector, or string. The length ,vector-length , andstring-length proceduresmust 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, will indeed be read as an exact integer, regardless of any implementation restrictions that may apply outside this range. Finally, the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation: + - * quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt Implementations are encouraged


key: chroma:document
string_value:
, but not required, to sup- port exact integers and exact rationals of practically unlim- ited size and precision, and to implement the above proce- dures 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 vio- lation of an implementation restriction or it may silently coerce its result to an inexact number. Such a coercion may cause an error later. An implementation may use ﬂoating point and other ap- proximate representation strategies for inexact numbers. This report recommends, but does not require, that the IEEE 32-bit and 64-bit ﬂoating point standards be followed by implementations that use ﬂonum representations, and that implementations using other representations should match or exceed the precision achievable using these ﬂoat- ing point standards [ 12]. In particular, implementations that use ﬂonum represen- tations must follow these 


key: chroma:document
string_value:
rules: A ﬂonum result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation. It is desirable (but not required) for potentially inexact oper- ations such as sqrt , when applied to exact arguments, to produce exact answers whenever possible (for example the square root of an exact 4 ought to be an exact 2). If, how- ever, an exact number is operated upon so as to produce an inexact result (as by sqrt ), and if the result is represented as a ﬂonum, then the most precise ﬂonum format available must be used; but if the result is represented in some other way then the representation must have at least as much precision as the most precise ﬂonum format available. 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 and6. Standard procedures 21 polar notations for complex numbers. If 


key: chroma:document
string_value:
an implementa- tion 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. 6.2.4. Syntax of numerical constants The syntax of the written representations for numbers is described formally in section 7.1.1 . Note that case is not signiﬁcant in numerical constants. A number may be written in binary, octal, decimal, or hex- adecimal by the use of a radix preﬁx. The radix preﬁxes are#b(binary), #o(octal),#d(decimal), and #x(hexadec- imal). With no radix preﬁx, a number is assumed to be expressed in decimal. A numerical constant may be speciﬁed to be either exact or inexact by a preﬁx. The preﬁxes are #efor exact, and #i for inexact. An exactness preﬁx may appear before or after any radix preﬁx that is used. If the written representation of a number has no exactness preﬁx, the constant may be either inexact or exact. It is inexact if it contains a decim


key: chroma:document
string_value:
al point, an exponent, or a “ #” character in the place of a digit, otherwise it is exact. In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant. For this purpose, numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation. The letters s,f,d, andlspecify the use of short ,single ,double , and long precision, respec- tively. (When fewer than four internal inexact represen- tations exist, the four size speciﬁcations are mapped onto those available. For example, an implementation with two internal representations may map short and single together and long and double together.) In addition, the exponent markerespeciﬁes the default precision for the implemen- tation. The default precision has at least as much precision asdouble , but implementations may wish to allow this de- fault to be set by the user. 3.14159265358979F0 Round to single — 3.141593 0.6L0 Extend to long — .600000000000000 6.2.


key: chroma:document
string_value:
5. Numerical operations The reader is referred to section 1.3.3 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 canbe represented without loss of accuracy; the inexact con- stants were chosen so that this is likely to be true in imple- mentations that use ﬂonums 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 non-numbers. They return #tif 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, 


key: chroma:document
string_value:
if a type predicate is false of a number, then all lower type predicates are also false of that number. Ifzis an inexact complex number, then (real?z)is true if and only if (zero? (imag-part z))is true. Ifxis an inexact real number, then (integer? x)is true if and only if(=x(roundx)). (complex? 3+4i) =⇒#t (complex? 3) =⇒#t (real? 3) =⇒#t (real? -2.5+0.0i) =⇒#t (real? #e1e10) =⇒#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 num- bers is unreliable, since any inaccuracy may aﬀect the result. Note: In many implementations the rational? procedure will be the same as real? , and the complex? procedure will be the same as number? , but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non-complex numbers. (exact?z) procedure (inexact? z) procedure These numerical predicates provide tests for the exactness of a quanti


key: chroma:document
string_value:
ty. For any Scheme number, precisely one of these predicates is true. (=z1z2z3...) procedure (<x1x2x3...) procedure (>x1x2x3...) procedure (<=x1x2x3...) procedure (>=x1x2x3...) procedure These procedures return #tif their arguments are (respec- tively): equal, monotonically increasing, monotonically de- creasing, monotonically nondecreasing, or monotonically nonincreasing.22 Revised5Scheme These predicates are required to be transitive. Note: The traditional implementations of these predicates in Lisp-like languages are not transitive. Note: While it is not an error to compare inexact numbers using these predicates, the results may be unreliable because a small inaccuracy may aﬀect the result; this is especially true of =andzero? . When in doubt, consult a numerical analyst. (zero?z) library procedure (positive? x) library procedure (negative? x) library procedure (odd?n) library procedure (even?n) library procedure These numerical predicates test a number for a particular property, returning #tor#f. See note


key: chroma:document
string_value:
 above. (maxx1x2...) library procedure (minx1x2...) library 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 aﬀect the result, which is possible only in unusual implementations). If minormaxis 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. (+z1...) procedure (*z1...) procedure These procedures return the sum or product of their argu- ments. (+ 3 4) =⇒7 (+ 3) =⇒3 (+) =⇒0 (* 4) =⇒4 (*) =⇒1 (-z1z2) procedure (-z) procedure (-z1z2...) optional procedure (/z1z2) procedure (/z) procedure (/z1z2...) optional procedure With two or more arguments, these procedures return the diﬀerence or quotient of their arguments, assoc


key: chroma:document
string_value:
iating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument.(- 3 4) =⇒-1 (- 3 4 5) =⇒-6 (- 3) =⇒-3 (/ 3 4 5) =⇒3/20 (/ 3) =⇒1/3 (abs x) library procedure Absreturns the absolute value of its argument. (abs -7) =⇒7 (quotient n1n2) procedure (remainder n1n2) procedure (modulon1n2) procedure These procedures implement number-theoretic (integer) di- vision.n2should be non-zero. All three procedures return integers. If n1/n2is an integer: (quotient n1n2) =⇒n1/n2 (remainder n1n2) =⇒0 (modulon1n2) =⇒0 Ifn1/n2is not an integer: (quotient n1n2) =⇒nq (remainder n1n2) =⇒nr (modulon1n2) =⇒nm wherenqisn1/n2rounded towards zero, 0 <|nr|<|n2|, 0<|nm|<|n2|,nrandnmdiﬀer from n1by a multiple of n2,nrhas the same sign as n1, andnmhas the same sign asn2. From this we can conclude that for integers n1andn2with n2not equal to 0, (=n1(+ (*n2(quotient n1n2)) (remainder n1n2))) =⇒#t provided all numbers involved in that computation are ex- act. (modulo 13 4) =⇒1 (remainder 13 4


key: chroma:document
string_value:
) =⇒1 (modulo -13 4) =⇒3 (remainder -13 4) =⇒-1 (modulo 13 -4) =⇒-3 (remainder 13 -4) =⇒1 (modulo -13 -4) =⇒-1 (remainder -13 -4) =⇒-1 (remainder -13 -4.0) =⇒-1.0 ; inexact6. Standard procedures 23 (gcdn1...) library procedure (lcmn1...) library procedure These procedures return the greatest common divisor or least common multiple of their arguments. The result is always non-negative. (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 denom- inator is always positive. The denominator of 0 is deﬁned to be 1. (numerator (/ 6 4)) =⇒3 (denominator (/ 6 4)) =⇒2 (denominator (exact->inexact (/ 6 4))) =⇒2.0 (floor x) procedure (ceiling x) procedure (truncate x) procedure (round x) procedure These procedures return integers. Floor returns the largest integer not larger


key: chroma:document
string_value:
 than x.Ceiling returns the smallest integer not smaller than x.Truncate returns the integer closest to xwhose absolute value is not larger than the absolute value of x.Round returns the closest inte- ger tox, rounding to even when xis halfway between two integers. Rationale: Round rounds to even for consistency with the de- fault rounding mode speciﬁed by the IEEE ﬂoating point stan- dard. 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 should be passed to the inexact->exact procedure. (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) library procedure Rationalize returns the simplest rational number diﬀer- ing fromxby no more than y. A rational number r1is simpler than another rational number r2ifr1=p1/q1and r2=p2/q2(in lowest terms) and |p1|≤|


key: chroma:document
string_value:
p2|and|q1|≤|q2|. 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 ev- ery other rational number in that interval (the simpler 2 /5 lies between 2 /7 and 3/5). Note that 0 = 0 /1 is the sim- plest rational of all. (rationalize (inexact->exact .3) 1/10) =⇒1/3 ; exact (rationalize .3 1/10) =⇒#i1/3 ; inexact (expz) procedure (logz) procedure (sinz) procedure (cosz) procedure (tanz) procedure (asinz) procedure (acosz) procedure (atanz) procedure (atany x) procedure These procedures are part of every implementation that supports general real numbers; they compute the usual transcendental functions. Logcomputes the natural log- arithm ofz(not the base ten logarithm). Asin ,acos , andatan compute arcsine (sin−1), arccosine (cos−1), and arctangent (tan−1), respectively. The two-argument vari- ant ofatan computes (angle (make-rectangular x y)) (see below), even in implementations that don’t supp


key: chroma:document
string_value:
ort general complex numbers. In general, the mathematical functions log, arcsine, arc- cosine, and arctangent are multiply deﬁned. The value of logzis deﬁned to be the one whose imaginary part lies in the range from−π(exclusive) to π(inclusive). log 0 is un- deﬁned. With log deﬁned this way, the values of sin−1z, cos−1z, and tan−1zare according to the following for- mulæ: sin−1z=−ilog(iz+√ 1−z2) cos−1z=π/2−sin−1z tan−1z= (log(1 +iz)−log(1−iz))/(2i) The above speciﬁcation follows [ 27], which in turn cites [ 19]; 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.24 Revised5Scheme (sqrtz) procedure Returns the principal square root of z. The result will have either positive real part, or zero real part and non-negative imaginary part. (exptz1z2) procedure Returnsz1raised to the power z2. Forz1̸= 0 z1z2=ez2logz1 0zis 1 ifz= 0 and 0 otherwise. (make-rectangu


key: chroma:document
string_value:
lar x1x2) procedure (make-polar x3x4) procedure (real-part z) procedure (imag-part z) procedure (magnitude z) procedure (anglez) procedure These procedures are part of every implementation that supports general complex numbers. Suppose x1,x2,x3, andx4are real numbers and zis a complex number such that z=x1+x2i=x3·eix4 Then (make-rectangular x1x2) =⇒z (make-polar x3x4) =⇒z (real-part z) =⇒x1 (imag-part z) =⇒x2 (magnitude z) =⇒ |x3| (anglez) =⇒xangle where−π < xangle≤πwithxangle =x4+ 2πnfor some integern. Rationale: Magnitude is the same as absfor a real argu- ment, but absmust be present in all implementations, whereas magnitude need only be present in implementations that sup- port general complex numbers. (exact->inexact z) procedure (inexact->exact z) procedure Exact->inexact returns an inexact representation of z. The value returned is the inexact number that is numeri- cally closest to the argument. If an exact argument has no reasonably close inexact equivalent, then a violation of an implementation rest


key: chroma:document
string_value:
riction may be reported. Inexact->exact returns an exact representation of z. The value returned is the exact number that is numerically clos- est to the argument. If an inexact argument has no rea- sonably close exact equivalent, then a violation of an im- plementation restriction may be reported. These procedures implement the natural one-to-one corre- spondence between exact and inexact integers throughout an implementation-dependent range. See section 6.2.3 .6.2.6. Numerical input and output (number->string z) procedure (number->string z radix) procedure Radix must be an exact integer, either 2, 8, 10, or 16. If omitted,radix defaults to 10. The procedure number-> string 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 number) (radixradix)) (eqv? number (string->number (number->string number radix) radix))) is true. It is an error if no possible result makes this ex- pression true. Ifzis inexact, the radix is 10, a


key: chroma:document
string_value:
nd the above expression can be satisﬁed 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 [3,5]; otherwise the format of the result is unspeciﬁed. The result returned by number->string never contains an explicit radix preﬁx. Note: The error case can occur only when zis not a complex number or is a complex number with a non-rational real or imaginary part. Rationale: Ifzis an inexact number represented using ﬂonums, and the radix is 10, then the above expression is normally satis- ﬁed by a result containing a decimal point. The unspeciﬁed case allows for inﬁnities, NaNs, and non-ﬂonum representations. (string->number string) procedure (string->number string radix ) procedure Returns a number of the maximally precise representation expressed by the given string .Radix must be an exact integer, either 2, 8, 10, or 16. If supplied, radix is a de


key: chroma:document
string_value:
fault radix that may be overridden by an explicit radix preﬁx in string (e.g."#o177" ). Ifradix is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number, then string->number returns#f. (string->number "100") =⇒100 (string->number "100" 16) =⇒256 (string->number "1e2") =⇒100.0 (string->number "15##") =⇒1500.0 Note: The domain of string->number may be restricted by implementations in the following ways. String->number is per- mitted to return #fwheneverstring contains an explicit radix preﬁx. If all numbers supported by an implementation are real,6. Standard procedures 25 thenstring->number is permitted to return #fwheneverstring 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 #fwhenever an ex- ponent marker or explicit exactness preﬁx is used, or if a # appears in place of a digit. If all


key: chroma:document
string_value:
 inexact numbers are integers, thenstring->number may return #fwhenever a decimal point is used. 6.3. Other data types This section describes operations on some of Scheme’s non- numeric data types: booleans, pairs, lists, symbols, char- acters, strings and vectors. 6.3.1. Booleans The standard boolean objects for true and false are written as#tand#f. What really matters, though, are the objects that the Scheme conditional expressions ( if,cond ,and, or,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 standard Scheme values, only #fcounts as false in conditional expressions. Except for #f, all standard Scheme values, including #t, pairs, the empty list, sym- bols, numbers, strings, vectors, and procedures, count as true. Note: Programmers accustomed to other dialects of Lisp should be aware that 


key: chroma:document
string_value:
Scheme distinguishes both #fand the empty list 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) library procedure Notreturns#tifobjis false, and returns #fotherwise. (not #t) =⇒#f (not 3) =⇒#f (not (list 3)) =⇒#f (not #f) =⇒#t (not ’()) =⇒#f (not (list)) =⇒#f (not ’nil) =⇒#f(boolean? obj) library procedure Boolean? returns#tifobjis either#tor#fand returns #fotherwise. (boolean? #f) =⇒#t (boolean? 0) =⇒#f (boolean? ’()) =⇒#f 6.3.2. Pairs and lists Apair(sometimes called a dotted pair ) is a record structure with two ﬁelds called the car and cdr ﬁelds (for historical reasons). Pairs are created by the procedure cons . The car and cdr ﬁelds are accessed by the procedures carand cdr. The car and cdr ﬁelds are assigned by the procedures set-car! andset-cdr! . Pairs are used primarily to represent lists. A list can be deﬁned recursively as either the empty list or a pair whose cdr is a list. More precisely, the set of lis


key: chroma:document
string_value:
ts is deﬁned as the smallest set Xsuch that •The empty list is in X. •Iflistis in X, then any pair whose cdr ﬁeld contains listis also in X. The objects in the car ﬁelds of successive pairs of a list are the elements of the list. For example, a two-element list is a pair whose car is the ﬁrst 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 deﬁnitions imply that all lists have ﬁnite length and are terminated by the empty list. The most general notation (external representation) for Scheme pairs is the “dotted” notation (c1.c2)where c1 is the value of the car ﬁeld and c2is the value of the cdr ﬁeld. For example (4 . 5) is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the external repre- sentation of a pair, not an expression that 


key: chroma:document
string_value:
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 (a . (b . (c . (d . (e . ())))))26 Revised5Scheme 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: (a b c . d) is equivalent to (a . (b . (c . d))) Whether a given pair is a list depends upon what is stored in the cdr ﬁeld. When the set-cdr! procedure is used, an object can be a list one moment and not the next: (define x (list ’a ’b ’c)) (define y x) y =⇒(a b c) (list? y) =⇒#t (set-cdr! x 4) =⇒ unspeciﬁed x =⇒(a . 4) (eqv? x y) =⇒#t y =⇒(a . 4) (list? y) =⇒#f (set-cdr! x x) =⇒ unspeciﬁed (list? x) =⇒#f Within literal expressions and representations of ob- jects read by the read procedure, the forms ’⟨datum⟩, 


key: chroma:document
string_value:
`⟨datum⟩,,⟨datum⟩, and,@⟨datum⟩denote two-ele- ment lists whose ﬁrst elements are the symbols quote , quasiquote ,unquote , andunquote-splicing , respec- tively. The second element in each case is ⟨datum⟩. This convention is supported so that arbitrary Scheme pro- grams may be represented as lists. That is, according to Scheme’s grammar, every ⟨expression⟩is also a⟨datum⟩ (see section 7.1.2 ). Among other things, this permits the use of the read procedure to parse Scheme programs. See section 3.3. (pair? obj) procedure Pair? returns#tifobjis a pair, and otherwise returns #f. (pair? ’(a . b)) =⇒#t (pair? ’(a b c)) =⇒#t (pair? ’()) =⇒#f (pair? ’#(a b)) =⇒#f (cons obj1obj2) procedure Returns a newly allocated pair whose car is obj1and whose cdr is obj2. The pair is guaranteed to be diﬀerent (in the sense ofeqv? ) 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 cont


key: chroma:document
string_value:
ents of the car ﬁeld 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 ﬁeld 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 (set-car! pair obj) procedure Stores objin the car ﬁeld of pair. The value returned by set-car! is unspeciﬁed. (define (f) (list ’not-a-constant-list)) (define (g) ’(constant-list)) (set-car! (f) 3) =⇒ unspeciﬁed (set-car! (g) 3) =⇒ error (set-cdr! pair obj) procedure Stores objin the cdr ﬁeld of pair. The value returned by set-cdr! is unspeciﬁed. (caar pair) library procedure (cadr pair) library procedure ...... (cdddar pair) library procedure (cddddr pair) library procedure These procedures are compositions of carandcdr, where for example caddr could be deﬁned by (define caddr (lambda (x) (car (cdr (cdr x))))) . Arbitrary compositions, up to four d


key: chroma:document
string_value:
eep, are provided. There are twenty-eight of these procedures in all. (null? obj) library procedure Returns#tifobjis the empty list, otherwise returns #f. (list? obj) library procedure Returns#tifobjis a list, otherwise returns #f. By deﬁni- tion, all lists have ﬁnite length and are terminated by the empty list.6. Standard procedures 27 (list? ’(a b c)) =⇒#t (list? ’()) =⇒#t (list? ’(a . b)) =⇒#f (let ((x (list ’a))) (set-cdr! x x) (list? x)) =⇒#f (list obj...) library procedure Returns a newly allocated list of its arguments. (list ’a (+ 3 4) ’c) =⇒(a 7 c) (list) =⇒() (length list) library procedure Returns the length of list. (length ’(a b c)) =⇒3 (length ’(a (b) (c d e))) =⇒3 (length ’()) =⇒0 (append list...) library procedure Returns a list consisting of the elements of the ﬁrst list followed by the elements of the other lists. (append ’(x) ’(y)) =⇒(x y) (append ’(a) ’(b c d)) =⇒(a b c d) (append ’(a (b)) ’((c))) =⇒(a (b) (c)) The resulting list is always newly allocated, except that it shares structure w


key: chroma:document
string_value:
ith the last listargument. The last argument may actually be any object; an improper list results if the last argument is not a proper list. (append ’(a b) ’(c . d)) =⇒(a b c . d) (append ’() ’a) =⇒a (reverse list) library procedure Returns a newly allocated list consisting of the elements of listin reverse order. (reverse ’(a b c)) =⇒(c b a) (reverse ’(a (b c) d (e (f)))) =⇒((e (f)) d (b c) a) (list-tail listk) library procedure Returns the sublist of listobtained by omitting the ﬁrst k elements. It is an error if listhas fewer than kelements. List-tail could be deﬁned by (define list-tail (lambda (x k) (if (zero? k) x (list-tail (cdr x) (- k 1)))))(list-ref listk) library procedure Returns the kth element of list. (This is the same as the car of(list-tail listk).) It is an error if listhas fewer thankelements. (list-ref ’(a b c d) 2) =⇒c (list-ref ’(a b c d) (inexact->exact (round 1.8))) =⇒c (memq obj list) library procedure (memv obj list) library procedure (member obj list) library procedure These procedu


key: chroma:document
string_value:
res return the ﬁrst sublist of listwhose car isobj, where the sublists of listare the non-empty lists returned by (list-tail list k)forkless than the length oflist. Ifobjdoes not occur in list, then#f(not the empty list) is returned. Memq useseq?to compare objwith the elements of list, whilememv useseqv? andmember uses equal? . (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) ’(b (a) c)) =⇒((a) c) (memq 101 ’(100 101 102)) =⇒ unspeciﬁed (memv 101 ’(100 101 102)) =⇒(101 102) (assq obj alist) library procedure (assv obj alist) library procedure (assoc obj alist) library procedure Alist (for “association list”) must be a list of pairs. These procedures ﬁnd the ﬁrst pair in alist whose car ﬁeld is obj, and returns that pair. If no pair in alist hasobjas its car, then#f(not the empty list) is returned. Assq useseq?to compare objwith the car ﬁelds of the pairs in alist, while assv useseqv? andassoc usesequal? . (define e ’((a 1) (b 2)


key: chroma:document
string_value:
 (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)) (assq 5 ’((2 3) (5 7) (11 13))) =⇒ unspeciﬁed (assv 5 ’((2 3) (5 7) (11 13))) =⇒(5 7) Rationale: Although they are ordinarily used as predicates, memq,memv,member ,assq,assv, andassoc do not have question marks in their names because they return useful values rather than just #tor#f.28 Revised5Scheme 6.3.3. Symbols 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. This is exactly the property needed to represent identiﬁers in programs, and so most implementations of Scheme use them internally for that purpose. Symbols are useful for many other applica- tions; for instance, they may be used the way enumerated values are used in Pascal. The rules for writing a symbol are exactly the same as the rules for writing an identiﬁer; see sections 2.1and7.


key: chroma:document
string_value:
1.1 . It is guaranteed that any symbol that has been returned as part of a literal expression, or read using the read proce- dure, and subsequently written out using the write proce- dure, will read back in as the identical symbol (in the sense ofeqv? ). Thestring->symbol procedure, however, can create symbols for which this write/read invariance may not hold because their names contain special characters or letters in the non-standard case. Note: Some implementations of Scheme have a feature known as “slashiﬁcation” in order to guarantee write/read invariance for all symbols, but historically the most important use of this feature has been to compensate for the lack of a string data type. Some implementations also have “uninterned symbols”, which defeat write/read invariance even in implementations with slashiﬁcation, and also generate exceptions to the rule that two symbols are the same if and only if their names are spelled the same. (symbol? obj) procedure Returns#tifobjis a symbol, otherwise returns #f. 


key: chroma:document
string_value:
(symbol? ’foo) =⇒#t (symbol? (car ’(a b))) =⇒#t (symbol? "bar") =⇒#f (symbol? ’nil) =⇒#t (symbol? ’()) =⇒#f (symbol? #f) =⇒#f (symbol->string symbol) procedure Returns the name of symbol as a string. If the symbol was part of an object returned as the value of a literal expression (section 4.1.2 ) or by a call to the read proce- dure, and its name contains alphabetic characters, then the string returned will contain characters in the implementa- tion’s preferred standard case—some implementations will prefer upper case, others lower case. If the symbol was re- turned by string->symbol , the case of characters in the string returned will be the same as the case in the string that was passed to string->symbol . It is an error to apply mutation procedures like string-set! to strings returned by this procedure.The following examples assume that the implementation’s standard case is lower case: (symbol->string ’flying-fish) =⇒"flying-fish" (symbol->string ’Martin) =⇒"martin" (symbol->string (string->symbol "Malvin


key: chroma:document
string_value:
a")) =⇒"Malvina" (string->symbol string) procedure Returns the symbol whose name is string . This procedure can create symbols with names containing special charac- ters or letters in the non-standard case, but it is usually a bad idea to create such symbols because in some imple- mentations of Scheme they cannot be read as themselves. Seesymbol->string . The following examples assume that the implementation’s standard case is lower case: (eq? ’mISSISSIppi ’mississippi) =⇒#t (string->symbol "mISSISSIppi") =⇒the symbol with name "mISSISSIppi" (eq? ’bitBlt (string->symbol "bitBlt")) =⇒#f (eq? ’JollyWog (string->symbol (symbol->string ’JollyWog))) =⇒#t (string=? "K. Harper, M.D." (symbol->string (string->symbol "K. Harper, M.D."))) =⇒#t 6.3.4. Characters Characters are objects that represent printed characters such as letters and digits. Characters are written using the notation #\⟨character⟩or#\⟨character name⟩. For exam- ple: #\a ; lower case letter #\A ; upper case letter #\( ; left parenthesis #\ ; the space


key: chroma:document
string_value:
 character #\space ; the preferred way to write a space #\newline ; the newline character Case is signiﬁcant in #\⟨character⟩, but not in #\⟨character name⟩. If⟨character⟩in#\⟨character⟩is alphabetic, then the character following ⟨character⟩must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of6. Standard procedures 29 characters “ #\space ” could be taken to be either a repre- sentation 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 self-evaluating. That is, they do not have to be quoted in programs. Some of the procedures that operate on characters ignore the diﬀerence between upper case and lower case. The pro- cedures that ignore case have “ -ci” (for “case insensitive”) embedded in their names. (char? obj) procedure Returns#tifobjis a character, otherwise returns #f. (char=? char 1char 2) procedure (char<? char 1c


key: chroma:document
string_value:
har 2) procedure (char>? char 1char 2) procedure (char<=? char 1char 2) procedure (char>=? char 1char 2) procedure These procedures impose a total ordering on the set of characters. It is guaranteed that under this ordering: •The upper case characters are in order. For example, (char<? #\A #\B) returns#t. •The lower case characters are in order. For example, (char<? #\a #\b) returns#t. •The digits are in order. For example, (char<? #\0 #\9) returns#t. •Either all the digits precede all the upper case letters, or vice versa. •Either all the digits precede all the lower case letters, or vice versa. Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numerical predicates. (char-ci=? char 1char 2) library procedure (char-ci<? char 1char 2) library procedure (char-ci>? char 1char 2) library procedure (char-ci<=? char 1char 2) library procedure (char-ci>=? char 1char 2) library procedure These procedures are similar to char=? et cetera, but they treat uppe


key: chroma:document
string_value:
r case and lower case letters as the same. For example, (char-ci=? #\A #\a) returns#t. Some imple- mentations may generalize these procedures to take more than two arguments, as with the corresponding numerical predicates.(char-alphabetic? char) library procedure (char-numeric? char) library procedure (char-whitespace? char) library procedure (char-upper-case? letter) library procedure (char-lower-case? letter) library procedure These procedures return #tif their arguments are alpha- betic, numeric, whitespace, upper case, or lower case char- acters, respectively, otherwise they return #f. The follow- ing remarks, which are speciﬁc to the ASCII character set, are intended only as a guide: The alphabetic characters are the 52 upper and lower case letters. The numeric charac- ters are the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and carriage return. (char->integer char) procedure (integer->char n) procedure Given a character, char->integer returns an exact inte- ger re


key: chroma:document
string_value:
presentation of the character. Given an exact inte- ger that is the image of a character under char->integer , integer->char returns that character. These procedures implement order-preserving isomorphisms between the set of characters under the char<=? ordering and some subset of the integers under the <=ordering. That is, if (char<=?a b)=⇒#tand(<=x y)=⇒#t andxandyare in the domain of integer->char , then (<= (char->integer a) (char->integer b)) =⇒#t (char<=? (integer->char x) (integer->char y))=⇒#t (char-upcase char) library procedure (char-downcase char) library procedure These procedures return a character char 2such that (char-ci=? char char 2). In addition, if char is alpha- betic, then the result of char-upcase is upper case and the result of char-downcase is lower case. 6.3.5. Strings Strings are sequences of characters. Strings are written as sequences of characters enclosed within doublequotes ("). A doublequote can be written inside a string only by escaping it with a backslash ( \), as in "The wor


key: chroma:document
string_value:
d \"recursion\" has many meanings." A backslash can be written inside a string only by escaping it with another backslash. Scheme does not specify the eﬀect of a backslash within a string that is not followed by a doublequote or backslash.30 Revised5Scheme A string constant may continue from one line to the next, but the exact contents of such a string are unspeciﬁed. The length of a string is the number of characters that it contains. This number is an exact, non-negative integer that is ﬁxed when the string is created. The valid indexes of a string are the exact non-negative integers less than the length of the string. The ﬁrst character of a string has index 0, the second has index 1, and so on. In phrases such as “the characters of string beginning with index start and ending with index end,” it is understood that the index start is inclusive and the index endis ex- clusive. Thus if start and endare the same index, a null substring is referred to, and if start is zero and endis the length of string , then


key: chroma:document
string_value:
 the entire string is referred to. Some of the procedures that operate on strings ignore the diﬀerence between upper and lower case. The versions that ignore case have “ -ci” (for “case insensitive”) embedded in their names. (string? obj) procedure Returns#tifobjis a string, otherwise returns #f. (make-string k) procedure (make-string kchar) procedure Make-string returns a newly allocated string of length k. Ifchar is given, then all elements of the string are ini- tialized to char, otherwise the contents of the string are unspeciﬁed. (string char...) library procedure Returns a newly allocated string composed of the argu- ments. (string-length string) procedure Returns the number of characters in the given string . (string-ref stringk) procedure kmust be a valid index of string .String-ref returns characterkofstring using zero-origin indexing. (string-set! string k char ) procedure kmust be a valid index of string .String-set! stores char in elementkofstring and returns an unspeciﬁed value. (define (f) (make


key: chroma:document
string_value:
-string 3 #\*)) (define (g) "***") (string-set! (f) 0 #\?) =⇒ unspeciﬁed (string-set! (g) 0 #\?) =⇒ error (string-set! (symbol->string ’immutable) 0 #\?) =⇒ error(string=? string 1string 2) library procedure (string-ci=? string 1string 2) library procedure Returns#tif the two strings are the same length and con- tain the same characters in the same positions, otherwise returns#f.String-ci=? treats upper and lower case let- ters as though they were the same character, but string=? treats upper and lower case as distinct characters. (string<? string 1string 2) library procedure (string>? string 1string 2) library procedure (string<=? string 1string 2) library procedure (string>=? string 1string 2) library procedure (string-ci<? string 1string 2) library procedure (string-ci>? string 1string 2) library procedure (string-ci<=? string 1string 2) library procedure (string-ci>=? string 1string 2) library procedure These procedures are the lexicographic extensions to strings of the corresponding orderings on characte


key: chroma:document
string_value:
rs. For example, string<? is the lexicographic ordering on strings induced by the ordering char<? on characters. If two strings diﬀer in length but are the same up to the length of the shorter string, the shorter string is considered to be lexicographically less than the longer string. Implementations may generalize these and the string=? andstring-ci=? procedures to take more than two argu- ments, as with the corresponding numerical predicates. (substring string start end ) library procedure String must be a string, and start and endmust be exact integers satisfying 0≤start≤end≤(string-length string). Substring returns a newly allocated string formed from the characters of string beginning with index start (inclu- sive) and ending with index end(exclusive). (string-append string...) library procedure Returns a newly allocated string whose characters form the concatenation of the given strings. (string->list string) library procedure (list->string list) library procedure String->list returns a newly allocated


key: chroma:document
string_value:
 list of the charac- ters that make up the given string. List->string returns a newly allocated string formed from the characters in the listlist, which must be a list of characters. String->list andlist->string are inverses so far as equal? is con- cerned. (string-copy string) library procedure Returns a newly allocated copy of the given string .6. Standard procedures 31 (string-fill! string char ) library procedure Stores char in every element of the given string and returns an unspeciﬁed value. 6.3.6. Vectors Vectors are heterogenous structures whose elements are in- dexed by integers. A vector typically occupies less space than a list of the same length, and the average time re- quired 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 non-negative integer that is ﬁxed when the vector is created. The valid indexes of a vector are the exact non-negative integers less than the length of t


key: chroma:document
string_value:
he vector. The ﬁrst 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 following: #(0 (2 2 2 2) "Anna") Note that this is the external representation of a vector, not an expression evaluating to a vector. Like list constants, vector constants must be quoted: ’#(0 (2 2 2 2) "Anna") =⇒#(0 (2 2 2 2) "Anna") (vector? obj) procedure Returns#tifobjis a vector, otherwise returns #f. (make-vector k) procedure (make-vector k ﬁll) procedure Returns a newly allocated vector of kelements. If a second argument is given, then each element is initialized to ﬁll. Otherwise the initial contents of each element is unspeci- ﬁed. (vector obj...) library procedure Returns a newly allocated vector whose elements contain the given arguments. Analogous to list . (


key: chroma:document
string_value:
vector ’a ’b ’c) =⇒#(a b c) (vector-length vector) procedure Returns the number of elements in vector as an exact in- teger. (vector-ref vector k) procedure kmust be a valid index of vector .Vector-ref returns the contents of element kofvector .(vector-ref ’#(1 1 2 3 5 8 13 21) 5) =⇒8 (vector-ref ’#(1 1 2 3 5 8 13 21) (let ((i (round (* 2 (acos -1))))) (if (inexact? i) (inexact->exact i) i))) =⇒13 (vector-set! vector k obj ) procedure kmust be a valid index of vector .Vector-set! stores obj in elementkofvector . The value returned by vector-set! is unspeciﬁed. (let ((vec (vector 0 ’(2 2 2 2) "Anna"))) (vector-set! vec 1 ’("Sue" "Sue")) vec) =⇒#(0 ("Sue" "Sue") "Anna") (vector-set! ’#(0 1 2) 1 "doe") =⇒ error; constant vector (vector->list vector) library procedure (list->vector list) library procedure Vector->list returns a newly allocated list of the objects contained in the elements of vector .List->vector returns a newly created vector initialized to the elements of the list list. (vector->list ’#(dah dah 


key: chroma:document
string_value:
didah)) =⇒(dah dah didah) (list->vector ’(dididit dah)) =⇒#(dididit dah) (vector-fill! vector ﬁll ) library procedure Stores ﬁllin every element of vector . The value returned byvector-fill! is unspeciﬁed. 6.4. Control features This chapter describes various primitive procedures which control the ﬂow of program execution in special ways. The procedure? predicate is also described here. (procedure? obj) procedure Returns#tifobjis a procedure, otherwise returns #f. (procedure? car) =⇒#t (procedure? ’car) =⇒#f (procedure? (lambda (x) (* x x))) =⇒#t (procedure? ’(lambda (x) (* x x))) =⇒#f (call-with-current-continuation procedure?) =⇒#t32 Revised5Scheme (apply proc arg 1...args) procedure Proc must be a procedure and args must be a list. Calls proc with the elements of the list (append (list arg1 ...)args)as the actual arguments. (apply + (list 3 4)) =⇒7 (define compose (lambda (f g) (lambda args (f (apply g args))))) ((compose sqrt *) 12 75) =⇒30 (map proc list 1list2...) library procedure The lists must be list


key: chroma:document
string_value:
s, and procmust be a procedure taking as many arguments as there are lists and returning a single value. If more than one listis given, then they must all be the same length. Mapapplies proc element-wise to the elements of the lists and returns a list of the results, in order. The dynamic order in which proc is applied to the elements of the lists is unspeciﬁed. (map cadr ’((a b) (d e) (g h))) =⇒(b e h) (map (lambda (n) (expt n n)) ’(1 2 3 4 5)) =⇒(1 4 27 256 3125) (map + ’(1 2 3) ’(4 5 6)) =⇒(5 7 9) (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) ’(a b))) =⇒(1 2) or(2 1) (for-each proc list 1list2...) library procedure The arguments to for-each are like the arguments to map, butfor-each calls proc for its side eﬀects rather than for its values. Unlike map,for-each is guaranteed to call proc on the elements of the lists in order from the ﬁrst ele- ment(s) to the last, and the value returned by for-each is unspeciﬁed. (let ((v (make-vector 5))) (for-each (lambda (i) (vector-set! v i (* 


key: chroma:document
string_value:
i i))) ’(0 1 2 3 4)) v) =⇒#(0 1 4 9 16) (force promise) library procedure Forces the value of promise (seedelay , section 4.2.5 ). If no value has been computed for the promise, then a value iscomputed and returned. The value of the promise is cached (or “memoized”) so that if it is forced a second time, the previously computed value is returned. (force (delay (+ 1 2))) =⇒3 (let ((p (delay (+ 1 2)))) (list (force p) (force p))) =⇒(3 3) (define a-stream (letrec ((next (lambda (n) (cons n (delay (next (+ n 1))))))) (next 0))) (define head car) (define tail (lambda (stream) (force (cdr stream)))) (head (tail (tail a-stream))) =⇒2 Force anddelay are mainly intended for programs written in functional style. The following examples should not be considered to illustrate good programming style, but they 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 (delay (begin (set! count (+ count 1)) (if (> count x) count (force p))))) (defi


key: chroma:document
string_value:
ne x 5) p =⇒ a promise (force p) =⇒6 p =⇒ a promise, still (begin (set! x 10) (force p)) =⇒6 Here is a possible implementation of delay andforce . Promises are implemented here as procedures of no argu- ments, and force simply calls its argument: (define force (lambda (object) (object))) We deﬁne the expression (delay⟨expression⟩) to have the same meaning as the procedure call (make-promise (lambda () ⟨expression⟩)) as follows (define-syntax delay (syntax-rules () ((delay expression) (make-promise (lambda () expression))))),6. Standard procedures 33 wheremake-promise is deﬁned as follows: (define make-promise (lambda (proc) (let ((result-ready? #f) (result #f)) (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? #t) (set! result x) result)))))))) Rationale: A promise may refer to its own value, as in the last example above. Forcing such a promise may cause the promise to be forced a second time before the value of the ﬁrst force has been computed. This com


key: chroma:document
string_value:
plicates the deﬁnition of make-promise . Various extensions to this semantics of delay andforce are supported in some implementations: •Callingforce 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 #tor to#f, depending on the implementation: (eqv? (delay 1) 1) =⇒ unspeciﬁed (pair? (delay (cons 1 2))) =⇒ unspeciﬁed •Some implementations may implement “implicit forc- ing,” where the value of a promise is forced by primi- tive procedures like cdr and +: (+ (delay (* 3 7)) 13) =⇒34 (call-with-current-continuation proc) procedure Proc must be a procedure of one argument. The procedure call-with-current-continuation packages up the cur- rent continuation (see the rationale below) as an “escape procedure” and passes it as an argument to proc. The es- cape procedure is a Scheme procedure that, if it is later called, will 


key: chroma:document
string_value:
abandon whatever continuation is in eﬀect at that later time and will instead use the continuation that was in eﬀect when the escape procedure was created. Call- ing the escape procedure may cause the invocation of before and after thunks installed using dynamic-wind . The escape procedure accepts the same number of ar- guments as the continuation to the original call tocall-with-current-continuation . Except for continua- tions created by the call-with-values procedure, all con- tinuations take exactly one value. The eﬀect of passing no value or more than one value to continuations that were not created by call-with-values is unspeciﬁed. The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired. The following examples show only the most common ways in which call-with-current-continuation is used. If all real uses were as simple as these examples, there would be no need f


key: chroma:document
string_value:
or a procedure with the power of call-with-current-continuation . (call-with-current-continuation (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) ’(54 0 37 -3 245 19)) #t)) =⇒-3 (define list-length (lambda (obj) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (obj) (cond ((null? obj) 0) ((pair? obj) (+ (r (cdr obj)) 1)) (else (return #f)))))) (r obj)))))) (list-length ’(1 2 3 4)) =⇒4 (list-length ’(a b . c)) =⇒#f Rationale: A common use of call-with-current-continuation is for structured, non-local exits from loops or procedure bodies, but in factcall-with-current-continuation is extremely useful for implementing a wide variety of advanced control structures. Whenever a Scheme expression is evaluated there is a contin- uation wanting the result of the expression. The continuation represents an entire (default) future for the computation. If the expression is evaluated at top level, for example, then the con- tinuation might take the result, print it on the screen, prompt


key: chroma:document
string_value:
 for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions speciﬁed 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 top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and pro- grammers do not think much about them. On rare occasions, however, a programmer may need to deal with continuations ex- plicitly.Call-with-current-continuation allows Scheme pro-34 Revised5Scheme grammers to do that by creating a procedure that acts just like the current continuation. Most programming languages incorporate one or more special- purpose escape constructs with names like exit,return , or evengoto. In 1965, however, Peter Landin [ 16] invented a general purpose escape operator called the J-operator. John Reynolds [ 24] described a simpler but equally powerful con- struct in 1972. The catch special form described by Sussma


key: chroma:document
string_value:
n and Steele in the 1975 report on Scheme is exactly the same as Reynolds’s construct, though its name came from a less general construct in MacLisp. Several Scheme implementors noticed that the full power of the catch construct could be provided by a procedure instead of by a special syntactic construct, and the namecall-with-current-continuation was coined in 1982. This name is descriptive, but opinions diﬀer on the merits of such a long name, and some people use the name call/cc in- stead. (values obj...) procedure Delivers all of its arguments to its continuation. Except for continuations created by the call-with-values pro- cedure, all continuations take exactly one value. Values might be deﬁned as follows: (define (values . things) (call-with-current-continuation (lambda (cont) (apply cont things)))) (call-with-values producer consumer ) procedure Calls its producer argument with no values and a contin- uation that, when passed some values, calls the consumer procedure with those values as arguments. Th


key: chroma:document
string_value:
e continua- tion for the call to consumer is the continuation of the call tocall-with-values . (call-with-values (lambda () (values 4 5)) (lambda (a b) b)) =⇒5 (call-with-values * -) =⇒-1 (dynamic-wind before thunk after ) procedure Calls thunk without arguments, returning the result(s) of this call. Before and after are called, also without ar- guments, as required by the following rules (note that in the absence of calls to continuations captured using call-with-current-continuation 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 be- tween when the call is initiated and when it returns. InScheme, because of call-with-current-continuation , the dynamic extent of a call may not be a single, connected time period. It is deﬁned as follows: •The dynamic extent is entered when execution of the body of the called proc


key: chroma:document
string_value:
edure begins. •The dynamic extent is also entered when exe- cution is not within the dynamic extent and a continuation is invoked that was captured (using call-with-current-continuation ) during the dy- namic 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 dynamic-wind occurs within the dynamic extent of the call to thunk and then a continuation is in- voked in such a way that the after s from these two invoca- tions ofdynamic-wind are both to be called, then the after associated with the second (inner) call to dynamic-wind is called ﬁrst. If a second call to dynamic-wind occurs within the dy- namic extent of the call to thunk and then a continua- tion is invoked in such a way that the before s from these two invocations of dynamic-wind are both to be called, then the before associated with the ﬁrst (outer) call to dynamic-wind is call


key: chroma:document
string_value:
ed ﬁrst. If invoking a continuation requires calling the before from one call to dynamic-wind and the after from another, then theafter is called ﬁrst. The eﬀect of using a captured continuation to enter or exit the dynamic extent of a call to before orafter is undeﬁned. (let ((path ’()) (c #f)) (let ((add (lambda (s) (set! path (cons s path))))) (dynamic-wind (lambda () (add ’connect)) (lambda () (add (call-with-current-continuation (lambda (c0) (set! c c0) ’talk1)))) (lambda () (add ’disconnect))) (if (< (length path) 4) (c ’talk2) (reverse path)))) =⇒(connect talk1 disconnect connect talk2 disconnect)6. Standard procedures 35 6.5.Eval (eval expression environment-speciﬁer ) procedure Evaluates expression in the speciﬁed environment and re- turns its value. Expression must be a valid Scheme expres- sion represented as data, and environment-speciﬁer must be a value returned by one of the three procedures de- scribed below. Implementations may extend eval to allow non-expression programs (deﬁnitions) as the ﬁ


key: chroma:document
string_value:
rst argument and to allow other values as environments, with the re- striction that eval is not allowed to create new bindings in the environments associated with null-environment or scheme-report-environment . (eval ’(* 7 3) (scheme-report-environment 5)) =⇒21 (let ((f (eval ’(lambda (f x) (f x x)) (null-environment 5)))) (f + 10)) =⇒20 (scheme-report-environment version) procedure (null-environment version) procedure Version must be the exact integer 5, corresponding to this revision of the Scheme report (the Revised5Report on Scheme). Scheme-report-environment returns a speciﬁer for an environment that is empty except for all bindings de- ﬁned in this report that are either required or both optional and supported by the implementation. Null-environment returns a speciﬁer for an environment that is empty except for the (syntactic) bindings for all syntactic keywords de- ﬁned in this report that are either required or both optional and supported by the implementation. Other values of version can be used to s


key: chroma:document
string_value:
pecify environments matching past revisions of this report, but their support is not required. An implementation will signal an error if version is neither 5nor another value supported by the implementation. The eﬀect of assigning (through the use of eval ) a vari- able bound in a scheme-report-environment (for exam- plecar) is unspeciﬁed. Thus the environments speciﬁed byscheme-report-environment may be immutable. (interaction-environment) optional procedure This procedure returns a speciﬁer for the environment that contains implementation-deﬁned bindings, typically a su- perset of those listed in the report. The intent is that this procedure will return the environment in which the imple- mentation would evaluate expressions dynamically typed by the user.6.6. Input and output 6.6.1. Ports Ports represent input and output devices. To Scheme, an input port is a Scheme object that can deliver characters upon command, while an output port is a Scheme object that can accept characters. (call-with-input-file stri


key: chroma:document
string_value:
ng proc )library procedure (call-with-output-file string proc )library procedure String should be a string naming a ﬁle, and proc should be a procedure that accepts one argument. For call-with-input-file , the ﬁle should already exist; for call-with-output-file , the eﬀect is unspeciﬁed if the ﬁle already exists. These procedures call proc with one ar- gument: the port obtained by opening the named ﬁle for input or output. If the ﬁle cannot be opened, an error is signalled. If proc returns, then the port is closed automati- cally and the value(s) yielded by the proc is(are) returned. Ifproc does not return, then the port will 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 un- limited extent, it is possible to escape from the current con- tinuation but later to escape back in. If implementations were permitted to close the port on any escape from the current continuation, then it


key: chroma:document
string_value:
 would be impossible to write portable code using both call-with-current-continuation andcall-with-input-file orcall-with-output-file . (input-port? obj) procedure (output-port? obj) procedure Returns#tifobjis an input port or output port respec- tively, otherwise returns #f. (current-input-port) procedure (current-output-port) procedure Returns the current default input or output port. (with-input-from-file string thunk ) optional procedure (with-output-to-file string thunk ) optional procedure String should be a string naming a ﬁle, and proc should be a procedure of no arguments. For with-input-from-file , the ﬁle should already exist; for with-output-to-file , the eﬀect is unspeciﬁed if the ﬁle already exists. The ﬁle is opened for input or output, an input or output port connected to it is made the default value returned bycurrent-input-port orcurrent-output-port (and is36 Revised5Scheme used by(read) ,(write obj), and so forth), and the thunk is called with no arguments. When the thunk returns, the port 


key: chroma:document
string_value:
is closed and the previous default is restored. With-input-from-file andwith-output-to-file re- turn(s) the value(s) yielded by thunk . If an escape pro- cedure is used to escape from the continuation of these procedures, their behavior is implementation dependent. (open-input-file ﬁlename) procedure Takes a string naming an existing ﬁle and returns an input port capable of delivering characters from the ﬁle. If the ﬁle cannot be opened, an error is signalled. (open-output-file ﬁlename) procedure Takes a string naming an output ﬁle to be created and returns an output port capable of writing characters to a new ﬁle by that name. If the ﬁle cannot be opened, an error is signalled. If a ﬁle with the given name already exists, the eﬀect is unspeciﬁed. (close-input-port port) procedure (close-output-port port) procedure Closes the ﬁle associated with port, rendering the port in- capable of delivering or accepting characters. These rou- tines have no eﬀect if the ﬁle has already been closed. The value returned is u


key: chroma:document
string_value:
nspeciﬁed. 6.6.2. Input (read) library procedure (read port) library procedure Read converts external representations of Scheme objects into the objects themselves. That is, it is a parser for the nonterminal⟨datum⟩(see sections 7.1.2 and6.3.2 ).Read returns the next object parsable from the given input port, updating port to point to the ﬁrst character past the end of the external representation of the object. If an end of ﬁle is encountered in the input before any char- acters are found that can begin an object, then an end of ﬁle object is returned. The port remains open, and fur- ther attempts to read will also return an end of ﬁle object. If an end of ﬁle is encountered after the beginning of an object’s external representation, but the external represen- tation is incomplete and therefore not parsable, an error is signalled. The port argument may be omitted, in which case it de- faults to the value returned by current-input-port . It is an error to read from a closed port.(read-char) procedure (read-cha


key: chroma:document
string_value:
r port) procedure Returns the next character available from the input port, updating the port to point to the following character. If no more characters are available, an end of ﬁle object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port . (peek-char) procedure (peek-char port) procedure Returns the next character available from the input port, without updating the port to point to the following char- acter. If no more characters are available, an end of ﬁle object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port . Note: The value returned by a call to peek-char is the same as the value that would have been returned by a call to read-char with the same port. The only diﬀerence is that the very next call toread-char orpeek-char on that port will return the value returned by the preceding call to peek-char . In particular, a call topeek-char on an interactive port will hang waiting for input whenever a 


key: chroma:document
string_value:
call to read-char would have hung. (eof-object? obj) procedure Returns#tifobjis an end of ﬁle object, otherwise returns #f. The precise set of end of ﬁle objects will vary among implementations, but in any case no end of ﬁle object will ever be an object that can be read in using read . (char-ready?) procedure (char-ready? port) procedure Returns#tif a character is ready on the input port and returns#fotherwise. If char-ready returns#tthen the nextread-char operation on the given port is guaranteed not to hang. If the port is at end of ﬁle then char-ready? returns#t.Port may be omitted, in which case it defaults to the value returned by current-input-port . Rationale: Char-ready? exists to make it possible for a pro- gram 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 as- serted by char-ready? cannot be rubbed out. If char-ready? were to return #fat end of ﬁle, a port at end 


key: chroma:document
string_value:
of ﬁle would be indistinguishable from an interactive port that has no ready characters. 6.6.3. Output6. Standard procedures 37 (write obj) library procedure (write obj port) library procedure Writes a written representation of objto the given port. Strings that appear in the written representation are en- closed in doublequotes, and within those strings backslash and doublequote characters are escaped by backslashes. Character objects are written using the #\notation. Write returns an unspeciﬁed value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port . (display obj) library procedure (display obj port) library procedure Writes a representation of objto the given port. Strings that appear in the written representation are not enclosed in doublequotes, and no characters are escaped within those strings. Character objects appear in the represen- tation as if written by write-char instead of by write . Display returns an unspeciﬁed value. The port argument 


key: chroma:document
string_value:
may be omitted, in which case it defaults to the value re- turned by current-output-port . Rationale: Write is intended for producing machine-readable output and display is for producing human-readable output. Implementations that allow “slashiﬁcation” within symbols will probably want write but notdisplay to slashify funny charac- ters in symbols. (newline) library procedure (newline port) library procedure Writes an end of line to port. Exactly how this is done diﬀers from one operating system to another. Returns an unspeciﬁed value. The port argument may be omit- ted, in which case it defaults to the value returned by current-output-port . (write-char char) procedure (write-char char port ) procedure Writes the character char (not an external representa- tion of the character) to the given port and returns an unspeciﬁed value. The port argument may be omit- ted, in which case it defaults to the value returned by current-output-port . 6.6.4. System interface Questions of system interface generally fall outs


key: chroma:document
string_value:
ide of the domain of this report. However, the following operations are important enough to deserve description here. (load ﬁlename) optional procedure Filename should be a string naming an existing ﬁle con- taining Scheme source code. The load procedure reads ex- pressions and deﬁnitions from the ﬁle and evaluates themsequentially. It is unspeciﬁed whether the results of the expressions are printed. The load procedure does not aﬀect the values returned by current-input-port and current-output-port .Load returns an unspeciﬁed value. Rationale: For portability, load must operate on source ﬁles. Its operation on other kinds of ﬁles necessarily varies among implementations. (transcript-on ﬁlename) optional procedure (transcript-off) optional procedure Filename must be a string naming an output ﬁle to be cre- ated. The eﬀect of transcript-on is to open the named ﬁle for output, and to cause a transcript of subsequent interaction between the user and the Scheme system to be written to the ﬁle. The transcript is en


key: chroma:document
string_value:
ded by a call totranscript-off , which closes the transcript ﬁle. Only one transcript may be in progress at any time, though some implementations may relax this restriction. The values re- turned by these procedures are unspeciﬁed.38 Revised5Scheme 7. Formal syntax and semantics This chapter provides formal descriptions of what has al- ready been described informally in previous chapters of this report. 7.1. Formal syntax This section provides a formal syntax for Scheme written in an extended BNF. All spaces in the grammar are for legibility. Case is insignif- icant; for example, #x1A and#X1a are equivalent.⟨empty⟩ stands for the empty string. The following extensions to BNF are used to make the de- scription more concise: ⟨thing⟩* means zero or more occur- rences of⟨thing⟩; and⟨thing⟩+means at least one ⟨thing⟩. 7.1.1. Lexical structure This section describes how individual tokens (identiﬁers, numbers, etc.) are formed from sequences of characters. The following sections describe how expressions and pro- gra


key: chroma:document
string_value:
ms are formed from sequences of tokens. ⟨Intertoken space⟩may occur on either side of any token, but not within a token. Tokens which require implicit termination (identiﬁers, numbers, characters, and dot) may be terminated by any ⟨delimiter⟩, but not necessarily by anything else. The following ﬁve characters are reserved for future exten- sions to the language: [ ] { } | ⟨token⟩ −→ ⟨ identiﬁer⟩ | ⟨ boolean⟩ | ⟨ number⟩ | ⟨character⟩ | ⟨ string⟩ |(|)|#(|’|`|,|,@|. ⟨delimiter⟩ −→ ⟨ whitespace⟩ |(|)|"|; ⟨whitespace⟩ −→ ⟨ space or newline⟩ ⟨comment⟩ −→;⟨all subsequent characters up to a line break⟩ ⟨atmosphere⟩ −→ ⟨ whitespace⟩ | ⟨ comment⟩ ⟨intertoken space⟩ −→ ⟨ atmosphere⟩* ⟨identiﬁer⟩ −→ ⟨ initial⟩ ⟨subsequent⟩* | ⟨peculiar identiﬁer ⟩ ⟨initial⟩ −→ ⟨ letter⟩ | ⟨ special initial⟩ ⟨letter⟩ −→a|b|c|...|z ⟨special initial⟩ −→!|$|%|&|*|/|:|<|= |>|?|^|_|~ ⟨subsequent⟩ −→ ⟨ initial⟩ | ⟨ digit⟩ | ⟨special subsequent ⟩ ⟨digit⟩ −→0|1|2|3|4|5|6|7|8|9 ⟨special subsequent ⟩ −→+|-|.|@ ⟨peculiar identiﬁer ⟩ −→+|-|...⟨synta


key: chroma:document
string_value:
ctic keyword ⟩ −→ ⟨ expression keyword ⟩ |else|=>|define |unquote|unquote-splicing ⟨expression keyword ⟩ −→quote|lambda|if |set!|begin|cond|and|or|case |let|let*|letrec|do|delay |quasiquote ⟨variable⟩ −→ ⟨ any⟨identiﬁer⟩that isn’t also a⟨syntactic keyword ⟩⟩ ⟨boolean⟩ −→#t|#f ⟨character⟩ −→#\⟨any character⟩ |#\⟨character name⟩ ⟨character name⟩ −→space|newline ⟨string⟩ −→"⟨string element⟩*" ⟨string element⟩ −→ ⟨ any character other than "or\⟩ |\"|\\ ⟨number⟩ −→ ⟨ num 2⟩| ⟨num 8⟩ | ⟨num 10⟩| ⟨num 16⟩ The following rules for ⟨numR⟩,⟨complexR⟩,⟨realR⟩, ⟨urealR⟩,⟨uintegerR⟩, and⟨preﬁxR⟩should be repli- cated forR= 2,8,10,and 16. There are no rules for ⟨decimal 2⟩,⟨decimal 8⟩, and⟨decimal 16⟩, which means that numbers containing decimal points or exponents must be in decimal radix. ⟨numR⟩ −→ ⟨ preﬁxR⟩ ⟨complexR⟩ ⟨complexR⟩ −→ ⟨ realR⟩ | ⟨ realR⟩@⟨realR⟩ | ⟨realR⟩+⟨urealR⟩i| ⟨realR⟩-⟨urealR⟩i | ⟨realR⟩+ i| ⟨realR⟩- i |+⟨urealR⟩i|-⟨urealR⟩i|+ i|- i ⟨realR⟩ −→ ⟨ sign⟩ ⟨urealR⟩ ⟨urealR⟩ −→ ⟨ uintegerR⟩ | ⟨uintegerR⟩/⟨u


key: chroma:document
string_value:
integerR⟩ | ⟨decimalR⟩ ⟨decimal 10⟩ −→ ⟨ uinteger 10⟩ ⟨suﬃx⟩ |.⟨digit 10⟩+#*⟨suﬃx⟩ | ⟨digit 10⟩+.⟨digit 10⟩*#*⟨suﬃx⟩ | ⟨digit 10⟩+#+. #*⟨suﬃx⟩ ⟨uintegerR⟩ −→ ⟨ digitR⟩+#* ⟨preﬁxR⟩ −→ ⟨ radixR⟩ ⟨exactness⟩ | ⟨exactness⟩ ⟨radixR⟩ ⟨suﬃx⟩ −→ ⟨ empty⟩ | ⟨exponent marker⟩ ⟨sign⟩ ⟨digit 10⟩+ ⟨exponent marker⟩ −→e|s|f|d|l ⟨sign⟩ −→ ⟨ empty⟩ |+|- ⟨exactness⟩ −→ ⟨ empty⟩ |#i|#e ⟨radix 2⟩ −→#b ⟨radix 8⟩ −→#o ⟨radix 10⟩ −→ ⟨ empty⟩ |#d7. Formal syntax and semantics 39 ⟨radix 16⟩ −→#x ⟨digit 2⟩ −→0|1 ⟨digit 8⟩ −→0|1|2|3|4|5|6|7 ⟨digit 10⟩ −→ ⟨ digit⟩ ⟨digit 16⟩ −→ ⟨ digit 10⟩ |a|b|c|d|e|f 7.1.2. External representations ⟨Datum⟩is what the read procedure (section 6.6.2 ) suc- cessfully parses. Note that any string that parses as an ⟨expression⟩will also parse as a ⟨datum⟩. ⟨datum⟩ −→ ⟨ simple datum⟩ | ⟨ compound datum ⟩ ⟨simple datum⟩ −→ ⟨ boolean⟩ | ⟨ number⟩ | ⟨character⟩ | ⟨ string⟩ | ⟨ symbol⟩ ⟨symbol⟩ −→ ⟨ identiﬁer⟩ ⟨compound datum ⟩ −→ ⟨ list⟩ | ⟨ vector⟩ ⟨list⟩ −→(⟨datum⟩*)|(⟨datum⟩+.⟨datum⟩) | ⟨abbreviation⟩ ⟨abbr


key: chroma:document
string_value:
eviation⟩ −→ ⟨ abbrev preﬁx⟩ ⟨datum⟩ ⟨abbrev preﬁx⟩ −→’|`|,|,@ ⟨vector⟩ −→#(⟨datum⟩*) 7.1.3. Expressions ⟨expression⟩ −→ ⟨ variable⟩ | ⟨literal⟩ | ⟨procedure call⟩ | ⟨lambda expression ⟩ | ⟨conditional⟩ | ⟨assignment⟩ | ⟨derived expression ⟩ | ⟨macro use⟩ | ⟨macro block⟩ ⟨literal⟩ −→ ⟨ quotation⟩ | ⟨ self-evaluating⟩ ⟨self-evaluating⟩ −→ ⟨ boolean⟩ | ⟨ number⟩ | ⟨character⟩ | ⟨ string⟩ ⟨quotation⟩ −→’⟨datum⟩ |(quote⟨datum⟩) ⟨procedure call⟩ −→(⟨operator⟩ ⟨operand⟩*) ⟨operator⟩ −→ ⟨ expression⟩ ⟨operand⟩ −→ ⟨ expression⟩ ⟨lambda expression ⟩ −→(lambda⟨formals⟩ ⟨body⟩) ⟨formals⟩ −→(⟨variable⟩*)| ⟨variable⟩ |(⟨variable⟩+.⟨variable⟩) ⟨body⟩ −→ ⟨ deﬁnition⟩*⟨sequence⟩ ⟨sequence⟩ −→ ⟨ command⟩*⟨expression⟩ ⟨command⟩ −→ ⟨ expression⟩ ⟨conditional⟩ −→(if⟨test⟩ ⟨consequent⟩ ⟨alternate⟩) ⟨test⟩ −→ ⟨ expression⟩ ⟨consequent⟩ −→ ⟨ expression⟩ ⟨alternate⟩ −→ ⟨ expression⟩ | ⟨ empty⟩⟨assignment⟩ −→(set!⟨variable⟩ ⟨expression⟩) ⟨derived expression ⟩ −→ (cond⟨cond clause⟩+) |(cond⟨cond clause⟩*(else⟨sequence⟩)) |(case⟨expres


key: chroma:document
string_value:
sion⟩ ⟨case clause⟩+) |(case⟨expression⟩ ⟨case clause⟩* (else⟨sequence⟩)) |(and⟨test⟩*) |(or⟨test⟩*) |(let (⟨binding spec⟩*)⟨body⟩) |(let⟨variable⟩(⟨binding spec⟩*)⟨body⟩) |(let* (⟨binding spec⟩*)⟨body⟩) |(letrec (⟨binding spec⟩*)⟨body⟩) |(begin⟨sequence⟩) |(do (⟨iteration spec⟩*) (⟨test⟩ ⟨do result⟩) ⟨command⟩*) |(delay⟨expression⟩) | ⟨quasiquotation⟩ ⟨cond clause⟩ −→(⟨test⟩ ⟨sequence⟩) |(⟨test⟩) |(⟨test⟩=>⟨recipient⟩) ⟨recipient⟩ −→ ⟨ expression⟩ ⟨case clause⟩ −→((⟨datum⟩*)⟨sequence⟩) ⟨binding spec⟩ −→(⟨variable⟩ ⟨expression⟩) ⟨iteration spec⟩ −→(⟨variable⟩ ⟨init⟩ ⟨step⟩) |(⟨variable⟩ ⟨init⟩) ⟨init⟩ −→ ⟨ expression⟩ ⟨step⟩ −→ ⟨ expression⟩ ⟨do result⟩ −→ ⟨ sequence⟩ | ⟨ empty⟩ ⟨macro use⟩ −→(⟨keyword⟩ ⟨datum⟩*) ⟨keyword⟩ −→ ⟨ identiﬁer⟩ ⟨macro block⟩ −→ (let-syntax (⟨syntax spec⟩*)⟨body⟩) |(letrec-syntax ( ⟨syntax spec⟩*)⟨body⟩) ⟨syntax spec⟩ −→(⟨keyword⟩ ⟨transformer spec⟩) 7.1.4. Quasiquotations The following grammar for quasiquote expressions is not context-free. It is presented as a recipe for generatin


key: chroma:document
string_value:
g an inﬁnite number of production rules. Imagine a copy of the following rules for D= 1,2,3,....Dkeeps track of the nesting depth. ⟨quasiquotation⟩ −→ ⟨ quasiquotation 1⟩ ⟨qq template 0⟩ −→ ⟨ expression⟩40 Revised5Scheme ⟨quasiquotation D⟩ −→`⟨qq template D⟩ |(quasiquote⟨qq template D⟩) ⟨qq template D⟩ −→ ⟨ simple datum⟩ | ⟨list qq template D⟩ | ⟨vector qq template D⟩ | ⟨unquotation D⟩ ⟨list qq template D⟩ −→(⟨qq template or splice D⟩*) |(⟨qq template or splice D⟩+.⟨qq template D⟩) |’⟨qq template D⟩ | ⟨quasiquotation D+ 1⟩ ⟨vector qq template D⟩ −→#(⟨qq template or splice D⟩*) ⟨unquotation D⟩ −→,⟨qq template D−1⟩ |(unquote⟨qq template D−1⟩) ⟨qq template or splice D⟩ −→ ⟨ qq template D⟩ | ⟨splicing unquotation D⟩ ⟨splicing unquotation D⟩ −→,@⟨qq template D−1⟩ |(unquote-splicing ⟨qq template D−1⟩) In⟨quasiquotation⟩s, a⟨list qq template D⟩can some- times be confused with either an ⟨unquotation D⟩or a⟨splicing unquotation D⟩. The interpretation as an ⟨unquotation⟩or⟨splicing unquotation D⟩takes prece- dence. 7.1


key: chroma:document
string_value:
.5. Transformers ⟨transformer spec⟩ −→ (syntax-rules ( ⟨identiﬁer⟩*)⟨syntax rule⟩*) ⟨syntax rule⟩ −→(⟨pattern⟩ ⟨template⟩) ⟨pattern⟩ −→ ⟨ pattern identiﬁer⟩ |(⟨pattern⟩*) |(⟨pattern⟩+.⟨pattern⟩) |(⟨pattern⟩*⟨pattern⟩ ⟨ellipsis⟩) |#(⟨pattern⟩*) |#(⟨pattern⟩*⟨pattern⟩ ⟨ellipsis⟩) | ⟨pattern datum⟩ ⟨pattern datum⟩ −→ ⟨ string⟩ | ⟨character⟩ | ⟨boolean⟩ | ⟨number⟩ ⟨template⟩ −→ ⟨ pattern identiﬁer⟩ |(⟨template element ⟩*) |(⟨template element ⟩+.⟨template⟩) |#(⟨template element ⟩*) | ⟨template datum⟩ ⟨template element ⟩ −→ ⟨ template⟩ | ⟨template⟩ ⟨ellipsis⟩ ⟨template datum⟩ −→ ⟨ pattern datum⟩ ⟨pattern identiﬁer⟩ −→ ⟨ any identiﬁer except ...⟩ ⟨ellipsis⟩ −→ ⟨ the identiﬁer ...⟩ 7.1.6. Programs and deﬁnitions ⟨program⟩ −→ ⟨ command or deﬁnition ⟩*⟨command or deﬁnition ⟩ −→ ⟨ command⟩ | ⟨deﬁnition⟩ | ⟨syntax deﬁnition⟩ |(begin⟨command or deﬁnition ⟩+) ⟨deﬁnition⟩ −→(define⟨variable⟩ ⟨expression⟩) |(define (⟨variable⟩ ⟨def formals⟩)⟨body⟩) |(begin⟨deﬁnition⟩*) ⟨def formals⟩ −→ ⟨ variable⟩* | ⟨variable⟩*.⟨variable⟩ ⟨


key: chroma:document
string_value:
syntax deﬁnition⟩ −→ (define-syntax ⟨keyword⟩ ⟨transformer spec⟩) 7.2. Formal semantics This section provides a formal denotational semantics for the primitive expressions of Scheme and selected built-in procedures. The concepts and notation used here are de- scribed in [ 29]; the notation is summarized below: ⟨...⟩ sequence formation s↓k k th member of the sequence s(1-based) #s length of sequence s s§t concatenation of sequences sandt s†k drop the ﬁrst kmembers of sequence s t→a,b McCarthy conditional “if tthenaelseb” ρ[x/i] substitution “ ρwithxfori” xinD injection of xinto domain D x|D projection of xto domain D The reason that expression continuations take sequences of values instead of single values is to simplify the formal treatment of procedure calls and multiple return values. The boolean ﬂag associated with pairs, vectors, and strings will be true for mutable objects and false for immutable objects. The order of evaluation within a call is unspeciﬁed. We mimic that here by applying arbitrary permut


key: chroma:document
string_value:
ations per- mute and unpermute , which must be inverses, to the argu- ments in a call before and after they are evaluated. This is not quite right since it suggests, incorrectly, that the order of evaluation is constant throughout a program (for any given number of arguments), but it is a closer approxima- tion to the intended semantics than a left-to-right evalua- tion would be. The storage allocator new is implementation-dependent, but it must obey the following axiom: if newσ∈L, then σ(newσ|L)↓2 =false. The deﬁnition of Kis omitted because an accurate deﬁni- tion ofKwould complicate the semantics without being very interesting. If P is a program in which all variables are deﬁned before being referenced or assigned, then the meaning of P is E[ [((lambda ( I*)P’)⟨undeﬁned⟩...)] ]7. Formal syntax and semantics 41 where I* is the sequence of variables deﬁned in P, P′is the sequence of expressions obtained by replacing every deﬁni- tion in P by an assignment, ⟨undeﬁned⟩is an expression that evaluates to undeﬁne


key: chroma:document
string_value:
d , andEis the semantic function that assigns meaning to expressions. 7.2.1. Abstract syntax K∈Con constants, including quotations I∈Ide identiﬁers (variables) E∈Exp expressions Γ∈Com = Exp commands Exp−→ K|I|(E0E*) |(lambda ( I*)Γ* E 0) |(lambda ( I*.I)Γ* E 0) |(lambda I Γ* E 0) |(if E0E1E2)|(if E0E1) |(set! I E) 7.2.2. Domain equations α∈L locations ν∈N natural numbers T={false, true} booleans Q symbols H characters R numbers Ep=L×L×T pairs Ev=L*×T vectors Es=L*×T strings M={false, true, null, undeﬁned, unspeciﬁed } miscellaneous φ∈F=L×(E*→K→C) procedure values ϵ∈E=Q+H+R+Ep+Ev+Es+M+F expressed values σ∈S=L→(E×T) stores ρ∈U= Ide→L environments θ∈C=S→A command continuations κ∈K=E*→C expression continuations A answers X errors 7.2.3. Semantic functions K: Con→E E: Exp→U→K→C E* : Exp*→U→K→C C: Com*→U→C→C Deﬁnition ofKdeliberately omitted. E[ [K] ] =λρκ. send (K[ [K] ])κE[ [I] ] =λρκ. hold(lookupρI) (single (λϵ.ϵ =undeﬁned→ wrong “undeﬁned variable” , sendϵκ)) E[ [(E0E*)] ] = λρκ.E*(permute (⟨E0⟩§E*)) ρ (λϵ*.((λ


key: chroma:document
string_value:
ϵ*.applicate (ϵ*↓1) (ϵ*†1)κ) (unpermuteϵ*))) E[ [(lambda ( I*)Γ* E 0)] ] = λρκ.λσ. newσ∈L→ send (⟨newσ|L, λϵ*κ′.#ϵ* = #I*→ tievals (λα*.(λρ′.C[ [Γ*] ]ρ′(E[ [E0] ]ρ′κ′)) (extendsρI*α*)) ϵ*, wrong “wrong number of arguments” ⟩ inE) κ (update (newσ|L)unspeciﬁedσ), wrong “out of memory” σ E[ [(lambda ( I*.I)Γ* E 0)] ] = λρκ.λσ. newσ∈L→ send (⟨newσ|L, λϵ*κ′.#ϵ*≥#I*→ tievalsrest (λα*.(λρ′.C[ [Γ*] ]ρ′(E[ [E0] ]ρ′κ′)) (extendsρ(I*§⟨I⟩)α*)) ϵ* (#I*), wrong “too few arguments” ⟩inE) κ (update (newσ|L)unspeciﬁedσ), wrong “out of memory” σ E[ [(lambda I Γ* E 0)] ] =E[ [(lambda ( .I)Γ* E 0)] ] E[ [(ifE0E1E2)] ] = λρκ.E[ [E0] ]ρ(single (λϵ.truishϵ→E[ [E1] ]ρκ, E[ [E2] ]ρκ)) E[ [(ifE0E1)] ] = λρκ.E[ [E0] ]ρ(single (λϵ.truishϵ→E[ [E1] ]ρκ, send unspeciﬁed κ)) Here and elsewhere, any expressed value other than undeﬁned may be used in place of unspeciﬁed . E[ [(set! I E)] ] = λρκ.E[ [E] ]ρ(single (λϵ.assign (lookupρI) ϵ (send unspeciﬁed κ))) E*[ [ ] ] =λρκ.κ⟨⟩ E*[ [E0E*] ] = λρκ.E[ [E0] ]ρ(single (λϵ0.E*[ [E*] ]ρ(λϵ*.κ(⟨ϵ0⟩§ϵ*


key: chroma:document
string_value:
)))) C[ [ ] ] =λρθ.θ C[ [Γ0Γ*] ] =λρθ.E[ [Γ0] ]ρ(λϵ*.C[ [Γ*] ]ρθ)42 Revised5Scheme 7.2.4. Auxiliary functions lookup :U→Ide→L lookup =λρI.ρI extends :U→Ide*→L*→U extends = λρI*α*.#I* = 0→ρ, extends (ρ[(α*↓1)/(I*↓1)]) (I*†1) (α*†1) wrong :X→C [implementation-dependent] send :E→K→C send =λϵκ.κ⟨ϵ⟩ single : (E→C)→K single = λψϵ*.#ϵ* = 1→ψ(ϵ*↓1), wrong “wrong number of return values” new:S→(L+{error}) [implementation-dependent] hold:L→K→C hold=λακσ. send (σα↓1)κσ assign :L→E→C→C assign =λαϵθσ.θ (updateαϵσ) update :L→E→S→S update =λαϵσ.σ [⟨ϵ,true⟩/α] tievals : (L*→C)→E*→C tievals = λψϵ*σ.#ϵ* = 0→ψ⟨⟩σ, newσ∈L→tievals (λα*.ψ(⟨newσ|L⟩§α*)) (ϵ*†1) (update (newσ|L)(ϵ*↓1)σ), wrong “out of memory” σ tievalsrest : (L*→C)→E*→N→C tievalsrest = λψϵ*ν.list(dropﬁrstϵ*ν) (single (λϵ.tievalsψ((takeﬁrstϵ*ν)§⟨ϵ⟩))) dropﬁrst =λln.n = 0→l,dropﬁrst (l†1)(n−1) takeﬁrst =λln.n = 0→⟨⟩,⟨l↓1⟩§(takeﬁrst (l†1)(n−1)) truish :E→T truish =λϵ.ϵ =false→false,true permute : Exp*→Exp* [implementation-dependent] unpermute :E*→E* [inverse of permute 


key: chroma:document
string_value:
] applicate :E→E*→K→C applicate = λϵϵ*κ.ϵ∈F→(ϵ|F↓2)ϵ*κ,wrong “bad procedure” onearg : (E→K→C)→(E*→K→C) onearg = λζϵ*κ.#ϵ* = 1→ζ(ϵ*↓1)κ, wrong “wrong number of arguments” twoarg : (E→E→K→C)→(E*→K→C) twoarg = λζϵ*κ.#ϵ* = 2→ζ(ϵ*↓1)(ϵ*↓2)κ, wrong “wrong number of arguments”list:E*→K→C list= λϵ*κ.#ϵ* = 0→send nullκ, list(ϵ*†1)(single (λϵ.cons⟨ϵ*↓1,ϵ⟩κ)) cons :E*→K→C cons = twoarg (λϵ1ϵ2κσ.newσ∈L→ (λσ′.newσ′∈L→ send (⟨newσ|L,newσ′|L,true⟩ inE) κ (update (newσ′|L)ϵ2σ′), wrong “out of memory” σ′) (update (newσ|L)ϵ1σ), wrong “out of memory” σ) less:E*→K→C less= twoarg (λϵ1ϵ2κ.(ϵ1∈R∧ϵ2∈R)→ send (ϵ1|R<ϵ2|R→true,false)κ, wrong “non-numeric argument to <”) add:E*→K→C add= twoarg (λϵ1ϵ2κ.(ϵ1∈R∧ϵ2∈R)→ send ((ϵ1|R+ϵ2|R) inE)κ, wrong “non-numeric argument to +”) car:E*→K→C car= onearg (λϵκ.ϵ∈Ep→hold(ϵ|Ep↓1)κ, wrong “non-pair argument to car”) cdr:E*→K→C [similar to car] setcar :E*→K→C setcar = twoarg (λϵ1ϵ2κ.ϵ1∈Ep→ (ϵ1|Ep↓3)→assign (ϵ1|Ep↓1) ϵ2 (send unspeciﬁed κ), wrong “immutable argument to set-car! ”, wrong “non-pair argu


key: chroma:document
string_value:
ment to set-car! ”) eqv:E*→K→C eqv= twoarg (λϵ1ϵ2κ.(ϵ1∈M∧ϵ2∈M)→ send (ϵ1|M=ϵ2|M→true,false)κ, (ϵ1∈Q∧ϵ2∈Q)→ send (ϵ1|Q=ϵ2|Q→true,false)κ, (ϵ1∈H∧ϵ2∈H)→ send (ϵ1|H=ϵ2|H→true,false)κ, (ϵ1∈R∧ϵ2∈R)→ send (ϵ1|R=ϵ2|R→true,false)κ, (ϵ1∈Ep∧ϵ2∈Ep)→ send ((λp1p2.((p1↓1) = (p2↓1)∧ (p1↓2) = (p2↓2))→true, false) (ϵ1|Ep) (ϵ2|Ep)) κ,7. Formal syntax and semantics 43 (ϵ1∈Ev∧ϵ2∈Ev)→..., (ϵ1∈Es∧ϵ2∈Es)→..., (ϵ1∈F∧ϵ2∈F)→ send ((ϵ1|F↓1) = (ϵ2|F↓1)→true,false) κ, send falseκ) apply :E*→K→C apply = twoarg (λϵ1ϵ2κ.ϵ1∈F→valueslist⟨ϵ2⟩(λϵ*.applicateϵ1ϵ*κ), wrong “bad procedure argument to apply ”) valueslist :E*→K→C valueslist = onearg (λϵκ.ϵ∈Ep→ cdr⟨ϵ⟩ (λϵ*.valueslist ϵ* (λϵ*.car⟨ϵ⟩(single (λϵ.κ (⟨ϵ⟩§ϵ*))))), ϵ=null→κ⟨⟩, wrong “non-list argument to values-list ”) cwcc :E*→K→C [call-with-current-continuation ] cwcc = onearg (λϵκ.ϵ∈F→ (λσ.newσ∈L→ applicateϵ ⟨⟨newσ|L,λϵ*κ′.κϵ*⟩inE⟩ κ (update (newσ|L) unspeciﬁed σ), wrong “out of memory” σ), wrong “bad procedure argument”) values :E*→K→C values =λϵ*κ.κϵ * cwv:E*→K→C [call-with-values ] cwv


key: chroma:document
string_value:
= twoarg (λϵ1ϵ2κ.applicateϵ1⟨⟩(λϵ*.applicateϵ2ϵ*)) 7.3. Derived expression types This section gives macro deﬁnitions for the derived expres- sion types in terms of the primitive expression types (lit- eral, variable, call, lambda ,if,set! ). See section 6.4for a possible deﬁnition of delay . (define-syntax cond (syntax-rules (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 temp (cond 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 ...))))) (define-syntax case (syntax-rules (else) ((case (key ...) clauses ...) (let ((atom-key (key ...))) (case atom-key clauses


key: chroma:document
string_value:
 ...))) ((case key (else result1 result2 ...)) (begin result1 result2 ...)) ((case key ((atoms ...) result1 result2 ...)) (if (memv key ’(atoms ...)) (begin result1 result2 ...))) ((case key ((atoms ...) result1 result2 ...) clause clauses ...) (if (memv key ’(atoms ...)) (begin result1 result2 ...) (case key clause clauses ...))))) (define-syntax and (syntax-rules () ((and) #t) ((and test) test) ((and test1 test2 ...) (if test1 (and test2 ...) #f)))) (define-syntax or (syntax-rules () ((or) #f) ((or test) test) ((or test1 test2 ...) (let ((x test1)) (if x x (or test2 ...)))))) (define-syntax let (syntax-rules () ((let ((name val) ...) body1 body2 ...) ((lambda (name ...) body1 body2 ...) val ...)) ((let tag ((name val) ...) body1 body2 ...) ((letrec ((tag (lambda (name ...) body1 body2 ...))) tag)44 Revised5Scheme val ...)))) (define-syntax let* (syntax-rules () ((let* () body1 body2 ...) (let () body1 body2 ...)) ((let* ((name1 val1) (name2 val2) ...) body1 body2 ...) (let ((name1 val1)) (let* ((name2 val2)


key: chroma:document
string_value:
 ...) 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 ob- tain the value stored in the location (no such expression is deﬁned in Scheme). A trick is used to generate the tempo- rary names needed to avoid specifying the order in which the values are evaluated. This could also be accomplished by using an auxiliary macro. (define-syntax letrec (syntax-rules () ((letrec ((var1 init1) ...) body ...) (letrec "generate tempnames" (var1 ...) () ((var1 init1) ...) body ...)) ((letrec "generate tempnames" () (temp1 ...) ((var1 init1) ...) body ...) (let ((var1 <undefined>) ...) (let ((temp1 init1) ...) (set! var1 temp1) ... body ...))) ((letrec "generate tempnames" (x y ...) (temp ...) ((var1 init1) ...) body ...) (letrec "generate tempnames" (y ...) (newtemp temp ...) ((var1 init1) ...) body ...)))) (define-syntax begin (syntax-rules () ((begin exp ...) ((lambda () exp ...))))) The f


key: chroma:document
string_value:
ollowing alternative expansion for begin does not make use of the ability to write more than one expressionin the body of a lambda expression. In any case, note that these rules apply only if the body of the begin contains no deﬁnitions. (define-syntax begin (syntax-rules () ((begin exp) exp) ((begin exp1 exp2 ...) (let ((x exp1)) (begin exp2 ...))))) The following deﬁnition of douses 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 unspeciﬁc value. (define-syntax do (syntax-rules () ((do ((var init step ...) ...) (test expr ...) command ...) (letrec ((loop (lambda (var ...) (if test (begin (if #f #f) expr ...) (begin command ... (loop (do "step" var step ...) ...)))))) (loop init ...))) ((do "step" x) x) ((do "step" x y) y)))Example 45 NOTES Language changes This section enumerates the changes that have been made to Scheme since the “Revised4report” [ 6] was published. •The report is now a superset of the IEEE sta


key: chroma:document
string_value:
ndard for Scheme [ 13]: implementations that conform to the report will also conform to the standard. This required the following changes: –The empty list is now required to count as true. –The classiﬁcation of features as essential or inessential has been removed. There are now three classes of built-in procedures: primitive, li- brary, and optional. The optional procedures are load ,with-input-from-file ,with-output- to-file ,transcript-on ,transcript-off , and interaction-environment , and-and/with more than two arguments. None of these are in the IEEE standard. –Programs are allowed to redeﬁne built-in proce- dures. Doing so will not change the behavior of other built-in procedures. •Port has been added to the list of disjoint types. •The macro appendix has been removed. High-level macros are now part of the main body of the report. The rewrite rules for derived expressions have been replaced with macro deﬁnitions. There are no reserved identiﬁers. •Syntax-rules now allows vector patterns. •Multiple-value


key: chroma:document
string_value:
 returns, eval , anddynamic-wind have been added. •The calls that are required to be implemented in a properly tail-recursive fashion are deﬁned explicitly. •‘@’ can be used within identiﬁers. ‘ |’ is reserved for possible future extensions. ADDITIONAL MATERIAL The Internet Scheme Repository at http://www.cs.indiana.edu/scheme-repository/ contains an extensive Scheme bibliography, as well as pa- pers, programs, implementations, and other material re- lated to Scheme.EXAMPLE Integrate-system integrates the system y′ k=fk(y1,y2,...,yn), k= 1,...,n of diﬀerential equations with the method of Runge-Kutta. The parameter system-derivative is a function that takes a system state (a vector of values for the state vari- ablesy1,...,yn) and produces a system derivative (the val- uesy′ 1,...,y′ n). The parameter initial-state provides an initial system state, and his an initial guess for the length of the integration step. The value returned by integrate-system is an inﬁnite stream of system states. (define integrate-sy


key: chroma:document
string_value:
stem (lambda (system-derivative initial-state h) (let ((next (runge-kutta-4 system-derivative h))) (letrec ((states (cons initial-state (delay (map-streams next states))))) states)))) Runge-Kutta-4 takes a function, f, that produces a system derivative from a system state. Runge-Kutta-4 produces a function that takes a system state and produces a new system state. (define runge-kutta-4 (lambda (f h) (let ((*h (scale-vector h)) (*2 (scale-vector 2)) (*1/2 (scale-vector (/ 1 2))) (*1/6 (scale-vector (/ 1 6)))) (lambda (y) ;; y is a system state (let* ((k0 (*h (f y))) (k1 (*h (f (add-vectors y (*1/2 k0))))) (k2 (*h (f (add-vectors y (*1/2 k1))))) (k3 (*h (f (add-vectors y k2))))) (add-vectors y (*1/6 (add-vectors k0 (*2 k1) (*2 k2) k3)))))))) (define elementwise (lambda (f) (lambda vectors (generate-vector (vector-length (car vectors)) (lambda (i) (apply f (map (lambda (v) (vector-ref v i)) vectors))))))) (define generate-vector (lambda (size proc)46 Revised5Scheme (let ((ans (make-vector size))) (letrec ((loop 


key: chroma:document
string_value:
(lambda (i) (cond ((= i size) ans) (else (vector-set! ans i (proc i)) (loop (+ i 1))))))) (loop 0))))) (define add-vectors (elementwise +)) (define scale-vector (lambda (s) (elementwise (lambda (x) (* x s))))) Map-streams is analogous to map: it applies its ﬁrst argu- ment (a procedure) to all the elements of its second argu- ment (a stream). (define map-streams (lambda (f s) (cons (f (head s)) (delay (map-streams f (tail s)))))) Inﬁnite streams are implemented as pairs whose car holds the ﬁrst element of the stream and whose cdr holds a promise to deliver the rest of the stream. (define head car) (define tail (lambda (stream) (force (cdr stream)))) The following illustrates the use of integrate-system in integrating the system CdvC dt=−iL−vC R LdiL dt=vC which models a damped oscillator. (define damped-oscillator (lambda (R L C) (lambda (state) (let ((Vc (vector-ref state 0)) (Il (vector-ref state 1))) (vector (- 0 (+ (/ Vc (* R C)) (/ Il C))) (/ Vc L)))))) (define the-states (integrate-system (damped-oscill


key: chroma:document
string_value:
ator 10000 1000 .001) ’#(1 0) .01))REFERENCES [1] Harold Abelson and Gerald Jay Sussman with Julie Sussman. Structure and Interpretation of Computer Programs, second edition. MIT Press, Cambridge, 1996. [2] Alan Bawden and Jonathan Rees. Syntactic closures. InProceedings of the 1988 ACM Symposium on Lisp and Functional Programming , pages 86–95. [3] Robert G. Burger and R. Kent Dybvig. Printing ﬂoating-point numbers quickly and accurately. In Proceedings of the ACM SIGPLAN ’96 Conference on Programming Language Design and Implementa- tion, pages 108–116. [4] William Clinger, editor. The revised revised report on Scheme, or an uncommon Lisp. MIT Artiﬁcial Intelligence Memo 848, August 1985. Also published as Computer Science Department Technical Report 174, Indiana University, June 1985. [5] William Clinger. How to read ﬂoating point numbers accurately. In Proceedings of the ACM SIGPLAN ’90 Conference on Programming Language Design and Implementation , pages 92–101. Proceedings pub- lished as SIGPLAN Notices 2


key: chroma:document
string_value:
5(6), June 1990. [6] William Clinger and Jonathan Rees, editors. The revised4report on the algorithmic language Scheme. InACM Lisp Pointers 4(3), pages 1–55, 1991. [7] William Clinger and Jonathan Rees. Macros that work. In Proceedings of the 1991 ACM Conference on Principles of Programming Languages , pages 155– 162. [8] William Clinger. Proper Tail Recursion and Space Eﬃciency. To appear in Proceedings of the 1998 ACM Conference on Programming Language Design and Implementation , June 1998. [9] R. Kent Dybvig, Robert Hieb, and Carl Bruggeman. Syntactic abstraction in Scheme. Lisp and Symbolic Computation 5(4):295–326, 1993. [10] Carol Fessenden, William Clinger, Daniel P. Fried- man, and Christopher Haynes. Scheme 311 version 4 reference manual. Indiana University Computer Sci- ence Technical Report 137, February 1983. Super- seded by [ 11]. [11] D. Friedman, C. Haynes, E. Kohlbecker, and M. Wand. Scheme 84 interim reference manual. Indi- ana University Computer Science Technical Report 153, January 1985.Re


key: chroma:document
string_value:
ferences 47 [12] IEEE Standard 754-1985. IEEE Standard for Binary Floating-Point Arithmetic. IEEE, New York, 1985. [13] IEEE Standard 1178-1990. IEEE Standard for the Scheme Programming Language. IEEE, New York, 1991. [14] Eugene E. Kohlbecker Jr. Syntactic Extensions in the Programming Language Lisp. PhD thesis, Indi- ana University, August 1986. [15] Eugene E. Kohlbecker Jr., Daniel P. Friedman, Matthias Felleisen, and Bruce Duba. Hygienic macro expansion. In Proceedings of the 1986 ACM Con- ference on Lisp and Functional Programming , pages 151–161. [16] Peter Landin. A correspondence between Algol 60 and Church’s lambda notation: Part I. Communica- tions of the ACM 8(2):89–101, February 1965. [17] MIT Department of Electrical Engineering and Com- puter Science. Scheme manual, seventh edition. September 1984. [18] Peter Naur et al. Revised report on the algorith- mic language Algol 60. Communications of the ACM 6(1):1–17, January 1963. [19] Paul Penﬁeld, Jr. Principal values and branch cuts in complex APL.


key: chroma:document
string_value:
 In APL ’81 Conference Proceed- ings, pages 248–256. ACM SIGAPL, San Fran- cisco, September 1981. Proceedings published as APL Quote Quad 12(1), ACM, September 1981. [20] Kent M. Pitman. The revised MacLisp manual (Sat- urday evening edition). MIT Laboratory for Com- puter Science Technical Report 295, May 1983. [21] 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 Sym- posium on Lisp and Functional Programming , pages 114–122. [22] Jonathan A. Rees, Norman I. Adams IV, and James R. Meehan. The T manual, fourth edition. Yale University Computer Science Department, January 1984. [23] Jonathan Rees and William Clinger, editors. The revised3report on the algorithmic language Scheme. InACM SIGPLAN Notices 21(12), pages 37–79, De- cember 1986. [24] John Reynolds. Deﬁnitional interpreters for higher order programming languages. In ACM Conference Proceedings , pages 717–740. ACM, 1972.[25] Guy Lewis Steele Jr. and Gerald Jay Su


key: chroma:document
string_value:
ssman. The revised report on Scheme, a dialect of Lisp. MIT Ar- tiﬁcial Intelligence Memo 452, January 1978. [26] Guy Lewis Steele Jr. Rabbit: a compiler for Scheme. MIT Artiﬁcial Intelligence Laboratory Technical Re- port 474, May 1978. [27] Guy Lewis Steele Jr. Common Lisp: The Language, second edition. Digital Press, Burlington MA, 1990. [28] Gerald Jay Sussman and Guy Lewis Steele Jr. Scheme: an interpreter for extended lambda calcu- lus. MIT Artiﬁcial Intelligence Memo 349, December 1975. [29] Joseph E. Stoy. Denotational Semantics: The Scott- Strachey Approach to Programming Language The- ory.MIT Press, Cambridge, 1977. [30] Texas Instruments, Inc. TI Scheme Language Ref- erence Manual. Preliminary version 1.0, November 1985.48 Revised5Scheme ALPHABETIC INDEX OF DEFINITIONS OF CONCEPTS, KEYWORDS, AND PROCEDURES The principal entry for each term, procedure, or keyword is listed ﬁrst, separated from the other entries by a semicolon. !5 ’8;26 *22 +22;5,42 ,13;26 ,@13 -22;5 ->5 ...5;14 /22 ;5 <21;42 <=21 =2


key: chroma:document
string_value:
1;22 =>10 >21 >=21 ?4 ‘13 abs22;24 acos 23 and11;43 angle 24 append 27 apply 32;8,43 asin 23 assoc 27 assq 27 assv 27 atan 23 #b21;38 backquote 13 begin 12;16,44 binding 6 binding construct 6 boolean? 25;6 bound 6 caar 26 cadr 26 call9 call by need 13 call-with-current-continuation 33;8,34,43 call-with-input-file 35 call-with-output-file 35 call-with-values 34;8,43 call/cc 34 car26;42case 10;43 catch 34 cdddar 26 cddddr 26 cdr26 ceiling 23 char->integer 29 char-alphabetic? 29 char-ci<=? 29 char-ci<? 29 char-ci=? 29 char-ci>=? 29 char-ci>? 29 char-downcase 29 char-lower-case? 29 char-numeric? 29 char-ready? 36 char-upcase 29 char-upper-case? 29 char-whitespace? 29 char<=? 29 char<? 29 char=? 29 char>=? 29 char>? 29 char? 29;6 close-input-port 36 close-output-port 36 combination 9 comma 13 comment 5;38 complex? 21;19 cond 10;15,43 cons 26 constant 7 continuation 33 cos23 current-input-port 35 current-output-port 35 #d21 define 16;14 define-syntax 17 deﬁnition 16 delay 13;32 denominator 23 display 37 do12;44 dot


key: chroma:document
string_value:
ted pair 25 dynamic-wind 34;33 #e21;38Index 49 else 10 empty list 25;6,26 eof-object? 36 eq?18;10 equal? 19 equivalence predicate 17 eqv? 17;7,10,42 error 4 escape procedure 33 eval 35;8 even? 22 exact 17 exact->inexact 24 exact? 21 exactness 19 exp23 expt 24 #f25 false 6;25 floor 23 for-each 32 force 32;13 gcd23 hygienic 13 #i21;38 identiﬁer 5;6,28,38 if10;41 imag-part 24 immutable 7 implementation restriction 4;20 improper list 26 inexact 17 inexact->exact 24;20 inexact? 21 initial environment 17 input-port? 35 integer->char 29 integer? 21;19 interaction-environment 35 internal deﬁnition 16 keyword 13;38 lambda 9;16,41 lazy evaluation 13 lcm23 length 27;20 let11;12,15,16,43 let* 11;16,44 let-syntax 14;16 letrec 11;16,44 letrec-syntax 14;16library 3 library procedure 17 list 27 list->string 30 list->vector 31 list-ref 27 list-tail 27 list? 26 load 37 location 7 log23 macro 13 macro keyword 13 macro transformer 13 macro use 13 magnitude 24 make-polar 24 make-rectangular 24 make-string 30 make-vector 31 map32 


key: chroma:document
string_value:
max22 member 27 memq 27 memv 27 min22 modulo 22 mutable 7 negative? 22 newline 37 nil25 not25 null-environment 35 null? 26 number 19 number->string 24 number? 21;6,19 numerator 23 numerical types 19 #o21;38 object 3 odd? 22 open-input-file 36 open-output-file 36 optional 3 or11;43 output-port? 35 pair 25 pair? 26;6 peek-char 36 port 35 port? 650 Revised5Scheme positive? 22 predicate 17 procedure call 9 procedure? 31;6 promise 13;32 proper tail recursion 7 quasiquote 13;26 quote 8;26 quotient 22 rational? 21;19 rationalize 23 read 36;26,39 read-char 36 real-part 24 real? 21;19 referentially transparent 13 region 6;10,11,12 remainder 22 reverse 27 round 23 scheme-report-environment 35 set! 10;16,41 set-car! 26 set-cdr! 26 setcar 42 simplest rational 23 sin23 sqrt 24 string 30 string->list 30 string->number 24 string->symbol 28 string-append 30 string-ci<=? 30 string-ci<? 30 string-ci=? 30 string-ci>=? 30 string-ci>? 30 string-copy 30 string-fill! 31 string-length 30;20 string-ref 30 string-set! 30;28 string<=? 


key: chroma:document
string_value:
30 string<? 30 string=? 30 string>=? 30 string>? 30 string? 30;6 substring 30 symbol->string 28;7 symbol? 28;6 syntactic keyword 6;5,13,38syntax deﬁnition 17 syntax-rules 14;17 #t25 tail call 7 tan23 token 38 top level environment 17;6 transcript-off 37 transcript-on 37 true 6;10,25 truncate 23 type 6 unbound 6;8,16 unquote 13;26 unquote-splicing 13;26 unspeciﬁed 4 valid indexes 30;31 values 34;9 variable 6;5,8,38 vector 31 vector->list 31 vector-fill! 31 vector-length 31;20 vector-ref 31 vector-set! 31 vector? 31;6 whitespace 5 with-input-from-file 35 with-output-to-file 35 write 37;13 write-char 37 #x21;39 zero? 22................................................................................................................................................................................................................................................................................................................................................................................................................


key: chroma:document
string_value:
                 Structur e and Interpr etation   of Computer Pr ograms second edition          Harold Abelson and Gerald Jay Sussman   with Julie Sussman  foreword by Alan J. Perlis              The MIT Press   Cambridge, Massachusetts     London, EnglandMcGraw-Hill Book Company   New Y ork     St. Louis     San Francisco     Montreal     T oronto This book is one of a series of texts written by faculty of the Electrical Engineering and Computer Science Department at the Massachusetts Institute of T echnology . It was edited and produced by The MIT Press under a joint production-distribution arrangement with the McGraw-Hill Book Company . Ordering Information: North America   Text orders should be addressed to the McGraw-Hill Book Company .   All other orders should be addressed to The MIT Press. Outside North America   All orders should be addressed to The MIT Press or its local distributor . © 1996 by The Massachusetts Institute of T echnology   Second edition All rights reserved. No part of this book may 


key: chroma:document
string_value:
be reproduced in any form or by any electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher . Creative Commons License   This work is licensed under a Creative Commons Attribution- Noncommercial 3.0 Unported License . This book was set by the authors using the L ATEX typesetting system and was printed and bound in the United States of America. Library of Congr ess Cataloging-in-Publication Data Abelson, Harold       Structure and interpretation of computer programs / Harold Abelson   and Gerald Jay Sussman, with Julie Sussman. – 2nd ed.       p. cm. – (Electrical engineering and computer science  series)       Includes bibliographical references and index.       ISBN 0-262-01 153-0 (MIT Press hardcover)       ISBN 0-262-51087-1 (MIT Press paperback)       ISBN 0-07-000484-6 (McGraw-Hill hardcover)       1. Electronic digital computers – Programming. 2. LISP (Computer program language) I. Sussman, Gerald Jay . II.


key: chroma:document
string_value:
 Sussman, Julie. III. T itle. IV. Series: MIT electrical engineering and computer   science series.   QA76.6.A255         1996   005.13'3 – dc20              96-17756     Fourth printing, 1999  This book is dedicated, in respect and admiration, to the spirit that lives in the computer . “I think that it's extraordinarily important that we in computer science keep fun in computing. When it started out, it was an awful lot of fun. Of course, the paying customers got shafted every now and then, and after a while we began to take their complaints seriously . We began to feel as if we really were responsible for the successful, error -free perfect use of these machines. I don't think we are. I think we're responsible for stretching them, setting them of f in new directions, and keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all, I hope we don't become missionaries. Don't feel as if you're Bible salesmen. The world has too many of those already . What you know abo


key: chroma:document
string_value:
ut computing other people will learn. Don't feel as if the key to successful computing is only in your hands. What's in your hands, I think and hope, is intelligence: the ability to see the machine as more than when you were first led up to it, that you can make it more.” Alan J. Perlis (April 1, 1922-February 7, 1990)  Foreword Educators, generals, dieticians, psychologists, and parents program. Armies, students, and some societies are programmed. An assault on lar ge problems employs a succession of programs, most of which spring into existence en route. These programs are rife with issues that appear to be particular to the problem at hand. To appreciate programming as an intellectual activity in its own right you must turn to computer programming; you must read and write computer programs – many of them. It doesn't matter much what the programs are about or what applications they serve. What does matter is how well they perform and how smoothly they fit with other programs in the creation of still greater


key: chroma:document
string_value:
 programs. The programmer must seek both perfection of part and adequacy of collection. In this book the use of “program” is focused on the creation, execution, and study of programs written in a dialect of Lisp for execution on a digital computer . Using Lisp we restrict or limit not what we may program, but only the notation for our program descriptions. Our traf fic with the subject matter of this book involves us with three foci of phenomena: the human mind, collections of computer programs, and the computer . Every computer program is a model, hatched in the mind, of a real or mental process. These processes, arising from human experience and thought, are huge in number , intricate in detail, and at any time only partially understood. They are modeled to our permanent satisfaction rarely by our computer programs. Thus even though our programs are carefully handcrafted discrete collections of symbols, mosaics of interlocking functions, they continually evolve: we change them as our perception of the model


key: chroma:document
string_value:
 deepens, enlar ges, generalizes until the model ultimately attains a metastable place within still another model with which we struggle. The source of the exhilaration associated with computer programming is the continual unfolding within the mind and on the computer of mechanisms expressed as programs and the explosion of perception they generate. If art interprets our dreams, the computer executes them in the guise of programs!For all its power , the computer is a harsh taskmaster . Its programs must be correct, and what we wish to say must be said accurately in every detail. As in every other symbolic activity , we become convinced of program truth through ar gument. Lisp itself can be assigned a semantics (another model, by the way), and if a program's function can be specified, say , in the predicate calculus, the proof methods of logic can be used to make an acceptable correctness ar gument. Unfortunately , as programs get lar ge and complicated, as they almost always do, the adequacy , consistency , a


key: chroma:document
string_value:
nd correctness of the specifications themselves become open to doubt, so that complete formal ar guments of correctness seldom accompany lar ge programs. Since lar ge programs grow from small ones, it is crucial that we develop an arsenal of standard program structures of whose correctness we have become sure – we call them idioms – and learn to combine them into larger structures using or ganizational techniques of proven value. These techniques are treated at length in this book, and understanding them is essential to participation in the Promethean enterprise called programming. More than anything else, the uncovering and mastery of powerful organizational techniques accelerates our ability to create lar ge, significant programs. Conversely , since writing lar ge programs is very taxing, we are stimulated to invent new methods of reducing the mass of function and detail to be fitted into lar ge programs. Unlike programs, computers must obey the laws of physics. If they wish to perform rapidly – a few nanos


key: chroma:document
string_value:
econds per state change – they must transmit electrons only small distances (at most 1 1/2 feet). The heat generated by the huge number of devices so concentrated in space has to be removed. An exquisite engineering art has been developed balancing between multiplicity of function and density of devices. In any event, hardware always operates at a level more primitive than that at which we care to program. The processes that transform our Lisp programs to “machine” programs are themselves abstract models which we program. Their study and creation give a great deal of insight into the or ganizational programs associated with programming arbitrary models. Of course the computer itself can be so modeled. Think of it: the behavior of the smallest physical switching element is modeled by quantum mechanics described by differential equations whose detailed behavior is captured by numericalapproximations represented in computer programs executing on computers composed of ...! It is not merely a matter of tactical co


key: chroma:document
string_value:
nvenience to separately identify the three foci. Even though, as they say , it's all in the head, this logical separation induces an acceleration of symbolic traf fic between these foci whose richness, vitality , and potential is exceeded in human experience only by the evolution of life itself. At best, relationships between the foci are metastable. The computers are never lar ge enough or fast enough. Each breakthrough in hardware technology leads to more massive programming enterprises, new or ganizational principles, and an enrichment of abstract models. Every reader should ask himself periodically “T oward what end, toward what end?” – but do not ask it too often lest you pass up the fun of programming for the constipation of bittersweet philosophy . Among the programs we write, some (but never enough) perform a precise mathematical function such as sorting or finding the maximum of a sequence of numbers, determining primality , or finding the square root. We call such programs algorithms, and a great de


key: chroma:document
string_value:
al is known of their optimal behavior , particularly with respect to the two important parameters of execution time and data storage requirements. A programmer should acquire good algorithms and idioms. Even though some programs resist precise specifications, it is the responsibility of the programmer to estimate, and always to attempt to improve, their performance. Lisp is a survivor , having been in use for about a quarter of a century . Among the active programming languages only Fortran has had a longer life. Both languages have supported the programming needs of important areas of application, Fortran for scientific and engineering computation and Lisp for artificial intelligence. These two areas continue to be important, and their programmers are so devoted to these two languages that Lisp and Fortran may well continue in active use for at least another quarter -century . Lisp changes. The Scheme dialect used in this text has evolved from the original Lisp and dif fers from the latter in several importa


key: chroma:document
string_value:
nt ways, including static scoping for variable binding and permitting functions to yield functions as values. In its semantic structure Scheme is as closely akin to Algol 60 as to early Lisps. Algol 60, never to be an active language again,lives on in the genes of Scheme and Pascal. It would be dif ficult to find two languages that are the communicating coin of two more dif ferent cultures than those gathered around these two languages. Pascal is for building pyramids – imposing, breathtaking, static structures built by armies pushing heavy blocks into place. Lisp is for building or ganisms – imposing, breathtaking, dynamic structures built by squads fitting fluctuating myriads of simpler or ganisms into place. The or ganizing principles used are the same in both cases, except for one extraordinarily important dif ference: The discretionary exportable functionality entrusted to the individual Lisp programmer is more than an order of magnitude greater than that to be found within Pascal enterprises. Lisp progr


key: chroma:document
string_value:
ams inflate libraries with functions whose utility transcends the application that produced them. The list, Lisp's native data structure, is lar gely responsible for such growth of utility . The simple structure and natural applicability of lists are reflected in functions that are amazingly nonidiosyncratic. In Pascal the plethora of declarable data structures induces a specialization within functions that inhibits and penalizes casual cooperation. It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures. As a result the pyramid must stand unchanged for a millennium; the or ganism must evolve or perish. To illustrate this dif ference, compare the treatment of material and exercises within this book with that in any first-course text using Pascal. Do not labor under the illusion that this is a text digestible at MIT only , peculiar to the breed found there. It is precisely what a serious book on programming Lisp must be, no matter who the student


key: chroma:document
string_value:
 is or where it is used. Note that this is a text about programming, unlike most Lisp books, which are used as a preparation for work in artificial intelligence. After all, the critical programming concerns of software engineering and artificial intelligence tend to coalesce as the systems under investigation become larger. This explains why there is such growing interest in Lisp outside of artificial intelligence. As one would expect from its goals, artificial intelligence research generates many significant programming problems. In other programming cultures this spate of problems spawns new languages. Indeed, in any verylarge programming task a useful or ganizing principle is to control and isolate traf fic within the task modules via the invention of language. These languages tend to become less primitive as one approaches the boundaries of the system where we humans interact most often. As a result, such systems contain complex language-processing functions replicated many times. Lisp has such a simple s


key: chroma:document
string_value:
yntax and semantics that parsing can be treated as an elementary task. Thus parsing technology plays almost no role in Lisp programs, and the construction of language processors is rarely an impediment to the rate of growth and change of lar ge Lisp systems. Finally , it is this very simplicity of syntax and semantics that is responsible for the burden and freedom borne by all Lisp programmers. No Lisp program of any size beyond a few lines can be written without being saturated with discretionary functions. Invent and fit; have fits and reinvent! We toast the Lisp programmer who pens his thoughts within nests of parentheses. Alan J. Perlis   New Haven, Connecticut  Preface to the Second Edition Is it possible that software is not like anything else, that it is meant to be discarded: that the whole point is to always see it as a soap bubble? Alan J. Perlis The material in this book has been the basis of MIT's entry-level computer science subject since 1980. We had been teaching this material for four years wh


key: chroma:document
string_value:
en the first edition was published, and twelve more years have elapsed until the appearance of this second edition. We are pleased that our work has been widely adopted and incorporated into other texts. We have seen our students take the ideas and programs in this book and build them in as the core of new computer systems and languages. In literal realization of an ancient Talmudic pun, our students have become our builders. We are lucky to have such capable students and such accomplished builders. In preparing this edition, we have incorporated hundreds of clarifications suggested by our own teaching experience and the comments of colleagues at MIT and elsewhere. We have redesigned most of the major programming systems in the book, including the generic-arithmetic system, the interpreters, the register -machine simulator , and the compiler; and we have rewritten all the program examples to ensure that any Scheme implementation conforming to the IEEE Scheme standard (IEEE 1990) will be able to run the code. 


key: chroma:document
string_value:
This edition emphasizes several new themes. The most important of these is the central role played by dif ferent approaches to dealing with time in computational models: objects with state, concurrent programming, functional programming, lazy evaluation, and nondeterministic programming. We have included new sections on concurrency and nondeterminism, and we have tried to integrate this theme throughout the book.The first edition of the book closely followed the syllabus of our MIT  one- semester subject. With all the new material in the second edition, it will not be possible to cover everything in a single semester , so the instructor will have to pick and choose. In our own teaching, we sometimes skip the section on logic programming (section 4.4), we have students use the register -machine simulator but we do not cover its implementation (section 5.2), and we give only a cursory overview of the compiler (section 5.5). Even so, this is still an intense course. Some instructors may wish to cover only the fi


key: chroma:document
string_value:
rst three or four chapters, leaving the other material for subsequent courses. The W orld-W ide-W eb site www-mitpress.mit.edu/sicp  provides support for users of this book. This includes programs from the book, sample programming assignments, supplementary materials, and downloadable implementations of the Scheme dialect of Lisp.  Preface to the First Edition A computer is like a violin. You can imagine a novice trying first a phonograph and then a violin. The latter , he says, sounds terrible. That is the ar gument we have heard from our humanists and most of our computer scientists. Computer programs are good, they say , for particular purposes, but they aren't flexible. Neither is a violin, or a typewriter , until you learn how to use it. Marvin Minsky , “Why Programming Is a Good   Medium for Expressing Poorly-Understood and Sloppily- Formulated Ideas” “The Structure and Interpretation of Computer Programs” is the entry-level subject in computer science at the Massachusetts Institute of T echnology . It 


key: chroma:document
string_value:
is required of all students at MIT who major in electrical engineering or in computer science, as one-fourth of the “common core curriculum,” which also includes two subjects on circuits and linear systems and a subject on the design of digital systems. We have been involved in the development of this subject since 1978, and we have taught this material in its present form since the fall of 1980 to between 600 and 700 students each year . Most of these students have had little or no prior formal training in computation, although many have played with computers a bit and a few have had extensive programming or hardware-design experience. Our design of this introductory computer -science subject reflects two major concerns. First, we want to establish the idea that a computer language is not just a way of getting a computer to perform operations but rather that it is a novel formal medium for expressing ideas about methodology . Thus, programs must be written for people to read, and only incidentally for machin


key: chroma:document
string_value:
es to execute. Second, we believe that the essential material to be addressed by a subject at this level is not the syntax of particular programming-language constructs, nor clever algorithms for computing particular functions ef ficiently , nor even the mathematical analysis ofalgorithms and the foundations of computing, but rather the techniques used to control the intellectual complexity of lar ge software systems. Our goal is that students who complete this subject should have a good feel for the elements of style and the aesthetics of programming. They should have command of the major techniques for controlling complexity in a lar ge system. They should be capable of reading a 50-page-long program, if it is written in an exemplary style. They should know what not to read, and what they need not understand at any moment. They should feel secure about modifying a program, retaining the spirit and style of the original author . These skills are by no means unique to computer programming. The techniques we t


key: chroma:document
string_value:
each and draw upon are common to all of engineering design. We control complexity by building abstractions that hide details when appropriate. We control complexity by establishing conventional interfaces that enable us to construct systems by combining standard, well- understood pieces in a “mix and match” way . We control complexity by establishing new languages for describing a design, each of which emphasizes particular aspects of the design and deemphasizes others. Underlying our approach to this subject is our conviction that “computer science” is not a science and that its significance has little to do with computers. The computer revolution is a revolution in the way we think and in the way we express what we think. The essence of this change is the emer gence of what might best be called procedural epistemology  – the study of the structure of knowledge from an imperative point of view , as opposed to the more declarative point of view taken by classical mathematical subjects. Mathematics provides a 


key: chroma:document
string_value:
framework for dealing precisely with notions of “what is.” Computation provides a framework for dealing precisely with notions of “how to.” In teaching our material we use a dialect of the programming language Lisp. We never formally teach the language, because we don't have to. We just use it, and students pick it up in a few days. This is one great advantage of Lisp-like languages: They have very few ways of forming compound expressions, and almost no syntactic structure. All of the formal properties can be covered in an hour , like the rules of chess. After a short time we forget about syntactic details of the language (because there are none) andget on with the real issues – figuring out what we want to compute, how we will decompose problems into manageable parts, and how we will work on the parts. Another advantage of Lisp is that it supports (but does not enforce) more of the lar ge-scale strategies for modular decomposition of programs than any other language we know . We can make procedural and data 


key: chroma:document
string_value:
abstractions, we can use higher -order functions to capture common patterns of usage, we can model local state using assignment and data mutation, we can link parts of a program with streams and delayed evaluation, and we can easily implement embedded languages. All of this is embedded in an interactive environment with excellent support for incremental program design, construction, testing, and debugging. We thank all the generations of Lisp wizards, starting with John McCarthy , who have fashioned a fine tool of unprecedented power and elegance. Scheme, the dialect of Lisp that we use, is an attempt to bring together the power and elegance of Lisp and Algol. From Lisp we take the metalinguistic power that derives from the simple syntax, the uniform representation of programs as data objects, and the garbage-collected heap- allocated data. From Algol we take lexical scoping and block structure, which are gifts from the pioneers of programming-language design who were on the Algol committee. We wish to cite J


key: chroma:document
string_value:
ohn Reynolds and Peter Landin for their insights into the relationship of Church's lambda calculus to the structure of programming languages. We also recognize our debt to the mathematicians who scouted out this territory decades before computers appeared on the scene. These pioneers include Alonzo Church, Barkley Rosser , Stephen Kleene, and Haskell Curry .  Acknowledgments We would like to thank the many people who have helped us develop this book and this curriculum. Our subject is a clear intellectual descendant of “6.231,” a wonderful subject on programming linguistics and the lambda calculus taught at MIT in the late 1960s by Jack W ozencraft and Arthur Evans, Jr . We owe a great debt to Robert Fano, who reor ganized MIT's introductory curriculum in electrical engineering and computer science to emphasize the principles of engineering design. He led us in starting out on this enterprise and wrote the first set of subject notes from which this book evolved. Much of the style and aesthetics of programming


key: chroma:document
string_value:
 that we try to teach were developed in conjunction with Guy Lewis Steele Jr ., who collaborated with Gerald Jay Sussman in the initial development of the Scheme language. In addition, David T urner , Peter Henderson, Dan Friedman, David W ise, and Will Clinger have taught us many of the techniques of the functional programming community that appear in this book. Joel Moses taught us about structuring lar ge systems. His experience with the Macsyma system for symbolic computation provided the insight that one should avoid complexities of control and concentrate on or ganizing the data to reflect the real structure of the world being modeled. Marvin Minsky and Seymour Papert formed many of our attitudes about programming and its place in our intellectual lives. To them we owe the understanding that computation provides a means of expression for exploring ideas that would otherwise be too complex to deal with precisely . They emphasize that a student's ability to write and modify programs provides a powerful me


key: chroma:document
string_value:
dium in which exploring becomes a natural activity .We also strongly agree with Alan Perlis that programming is lots of fun and we had better be careful to support the joy of programming. Part of this joy derives from observing great masters at work. We are fortunate to have been apprentice programmers at the feet of Bill Gosper and Richard Greenblatt. It is dif ficult to identify all the people who have contributed to the development of our curriculum. We thank all the lecturers, recitation instructors, and tutors who have worked with us over the past fifteen years and put in many extra hours on our subject, especially Bill Siebert, Albert Meyer , Joe Stoy , Randy Davis, Louis Braida, Eric Grimson, Rod Brooks, Lynn Stein, and Peter Szolovits. We would like to specially acknowledge the outstanding teaching contributions of Franklyn T urbak, now at Wellesley; his work in under graduate instruction set a standard that we can all aspire to. We are grateful to Jerry Saltzer and Jim Miller for helping us grapple w


key: chroma:document
string_value:
ith the mysteries of concurrency , and to Peter Szolovits and David McAllester for their contributions to the exposition of nondeterministic evaluation in chapter 4. Many people have put in significant ef fort presenting this material at other universities. Some of the people we have worked closely with are Jacob Katzenelson at the T echnion, Hardy Mayer at the University of California at Irvine, Joe Stoy at Oxford, Elisha Sacks at Purdue, and Jan Komorowski at the Norwegian University of Science and Technology . We are exceptionally proud of our colleagues who have received major teaching awards for their adaptations of this subject at other universities, including Kenneth Y ip at Yale, Brian Harvey at the University of California at Berkeley , and Dan Huttenlocher at Cornell. Al Moyé arranged for us to teach this material to engineers at Hewlett- Packard, and for the production of videotapes of these lectures. We would like to thank the talented instructors – in particular Jim Miller , Bill Siebert, and Mik


key: chroma:document
string_value:
e Eisenber g – who have designed continuing education courses incorporating these tapes and taught them at universities and industry all over the world. Many educators in other countries have put in significant work translating the first edition. Michel Briand, Pierre Chamard, and André Pic produced aFrench edition; Susanne Daniels-Herold produced a German edition; and Fumio Motoyoshi produced a Japanese edition. We do not know who produced the Chinese edition, but we consider it an honor to have been selected as the subject of an “unauthorized” translation. It is hard to enumerate all the people who have made technical contributions to the development of the Scheme systems we use for instructional purposes. In addition to Guy Steele, principal wizards have included Chris Hanson, Joe Bowbeer , Jim Miller , Guillermo Rozas, and Stephen Adams. Others who have put in significant time are Richard Stallman, Alan Bawden, Kent Pitman, Jon T aft, Neil Mayle, John Lamping, Gwyn Osnos, T racy Larrabee, Geor ge Carrette


key: chroma:document
string_value:
, Soma Chaudhuri, Bill Chiarchiaro, Steven Kirsch, Leigh Klotz, W ayne Noss, Todd Cass, Patrick O'Donnell, Kevin Theobald, Daniel W eise, Kenneth Sinclair , Anthony Courtemanche, Henry M. W u, Andrew Berlin, and Ruth Shyu. Beyond the MIT implementation, we would like to thank the many people who worked on the IEEE Scheme standard, including W illiam Clinger and Jonathan Rees, who edited the R4RS, and Chris Haynes, David Bartley , Chris Hanson, and Jim Miller , who prepared the IEEE standard. Dan Friedman has been a long-time leader of the Scheme community . The community's broader work goes beyond issues of language design to encompass significant educational innovations, such as the high-school curriculum based on EdScheme by Schemer's Inc., and the wonderful books by Mike Eisenber g and by Brian Harvey and Matthew W right. We appreciate the work of those who contributed to making this a real book, especially T erry Ehling, Larry Cohen, and Paul Bethge at the MIT Press. Ella Mazel found the wonderful cover i


key: chroma:document
string_value:
mage. For the second edition we are particularly grateful to Bernard and Ella Mazel for help with the book design, and to David Jones, T EX wizard extraordinaire. We also are indebted to those readers who made penetrating comments on the new draft: Jacob Katzenelson, Hardy Mayer , Jim Miller , and especially Brian Harvey , who did unto this book as Julie did unto his book Simply Scheme . Finally , we would like to acknowledge the support of the or ganizations that have encouraged this work over the years, including support from Hewlett-Packard, made possible by Ira Goldstein and Joel Birnbaum, and support from DARP A, made possible by Bob Kahn.Chapter 1 Building Abstractions with Procedures The acts of the mind, wherein it exerts its power over simple ideas, are chiefly these three: 1. Combining several simple ideas into one compound one, and thus all complex ideas are made. 2. The second is bringing two ideas, whether simple or complex, together , and setting them by one another so as to take a view of them 


key: chroma:document
string_value:
at once, without uniting them into one, by which it gets all its ideas of relations. 3. The third is separating them from all other ideas that accompany them in their real existence: this is called abstraction, and thus all its general ideas are made. John Locke, An Essay Concerning Human Understanding (1690) We are about to study the idea of a computational pr ocess . Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a program . People create programs to direct processes. In ef fect, we conjure the spirits of the computer with our spells. A computational process is indeed much like a sorcerer's idea of a spirit. It cannot be seen or touched. It is not composed of matter at all. However , it is very real. It can perform intellectual work. It can answer questions. It can affect the world by disbursing money at a bank or by controlling a robot arm in a fac


key: chroma:document
string_value:
tory . The programs we use to conjure processes are like a sorcerer's spells. They are carefully composed from symbolic expressions in arcane and esoteric programming languages  that prescribe the tasks we want our processes to perform. A computational process, in a correctly working computer , executes programs precisely and accurately . Thus, like the sorcerer's apprentice, novice programmers must learn to understand and to anticipate theconsequences of their conjuring. Even small errors (usually called bugs  or glitches ) in programs can have complex and unanticipated consequences. Fortunately , learning to program is considerably less dangerous than learning sorcery , because the spirits we deal with are conveniently contained in a secure way . Real-world programming, however , requires care, expertise, and wisdom. A small bug in a computer -aided design program, for example, can lead to the catastrophic collapse of an airplane or a dam or the self-destruction of an industrial robot. Master software engin


key: chroma:document
string_value:
eers have the ability to or ganize programs so that they can be reasonably sure that the resulting processes will perform the tasks intended. They can visualize the behavior of their systems in advance. They know how to structure programs so that unanticipated problems do not lead to catastrophic consequences, and when problems do arise, they can debug  their programs. Well-designed computational systems, like well- designed automobiles or nuclear reactors, are designed in a modular manner , so that the parts can be constructed, replaced, and debugged separately . Programming in Lisp We need an appropriate language for describing processes, and we will use for this purpose the programming language Lisp. Just as our everyday thoughts are usually expressed in our natural language (such as English, French, or Japanese), and descriptions of quantitative phenomena are expressed with mathematical notations, our procedural thoughts will be expressed in Lisp. Lisp was invented in the late 1950s as a formalism for rea


key: chroma:document
string_value:
soning about the use of certain kinds of logical expressions, called recursion equations , as a model for computation. The language was conceived by John McCarthy and is based on his paper “Recursive Functions of Symbolic Expressions and Their Computation by Machine” (McCarthy 1960). Despite its inception as a mathematical formalism, Lisp is a practical programming language. A Lisp interpr eter is a machine that carries out processes described in the Lisp language. The first Lisp interpreter wasimplemented by McCarthy with the help of colleagues and students in the Artificial Intelligence Group of the MIT Research Laboratory of Electronics and in the MIT Computation Center .1 Lisp, whose name is an acronym for LISt Processing, was designed to provide symbol-manipulating capabilities for attacking programming problems such as the symbolic dif ferentiation and integration of algebraic expressions. It included for this purpose new data objects known as atoms and lists, which most strikingly set it apart from all


key: chroma:document
string_value:
 other languages of the period. Lisp was not the product of a concerted design ef fort. Instead, it evolved informally in an experimental manner in response to users' needs and to pragmatic implementation considerations. Lisp's informal evolution has continued through the years, and the community of Lisp users has traditionally resisted attempts to promulgate any “of ficial” definition of the language. This evolution, together with the flexibility and elegance of the initial conception, has enabled Lisp, which is the second oldest language in widespread use today (only Fortran is older), to continually adapt to encompass the most modern ideas about program design. Thus, Lisp is by now a family of dialects, which, while sharing most of the original features, may dif fer from one another in significant ways. The dialect of Lisp used in this book is called Scheme.2 Because of its experimental character and its emphasis on symbol manipulation, Lisp was at first very inef ficient for numerical computations, at lea


key: chroma:document
string_value:
st in comparison with Fortran. Over the years, however , Lisp compilers have been developed that translate programs into machine code that can perform numerical computations reasonably ef ficiently . And for special applications, Lisp has been used with great ef fectiveness.3 Although Lisp has not yet overcome its old reputation as hopelessly inef ficient, Lisp is now used in many applications where ef ficiency is not the central concern. For example, Lisp has become a language of choice for operating- system shell languages and for extension languages for editors and computer -aided design systems. If Lisp is not a mainstream language, why are we using it as the framework for our discussion of programming? Because the language possesses unique features that make it an excellent medium for studying importantprogramming constructs and data structures and for relating them to the linguistic features that support them. The most significant of these features is the fact that Lisp descriptions of processes, called


key: chroma:document
string_value:
 procedur es, can themselves be represented and manipulated as Lisp data. The importance of this is that there are powerful program-design techniques that rely on the ability to blur the traditional distinction between “passive” data and “active” processes. As we shall discover , Lisp's flexibility in handling procedures as data makes it one of the most convenient languages in existence for exploring these techniques. The ability to represent procedures as data also makes Lisp an excellent language for writing programs that must manipulate other programs as data, such as the interpreters and compilers that support computer languages. Above and beyond these considerations, programming in Lisp is great fun. 1 The Lisp 1 Pr ogrammer's Manual  appeared in 1960, and the Lisp 1.5 Pr ogrammer's Manual (McCarthy 1965) was published in 1962. The early history of Lisp is described in McCarthy 1978. 2 The two dialects in which most major Lisp programs of the 1970s were written are MacLisp (Moon 1978; Pitman 1983), devel


key: chroma:document
string_value:
oped at the MIT Project MAC, and Interlisp (Teitelman 1974), developed at Bolt Beranek and Newman Inc. and the Xerox Palo Alto Research Center . Portable Standard Lisp (Hearn 1969; Griss 1981) was a Lisp dialect designed to be easily portable between dif ferent machines. MacLisp spawned a number of subdialects, such as Franz Lisp, which was developed at the University of California at Berkeley , and Zetalisp (Moon 1981), which was based on a special- purpose processor designed at the MIT Artificial Intelligence Laboratory to run Lisp very ef ficiently . The Lisp dialect used in this book, called Scheme (Steele 1975), was invented in 1975 by Guy Lewis Steele Jr . and Gerald Jay Sussman of the MIT Artificial Intelligence Laboratory and later reimplemented for instructional use at MIT . Scheme became an IEEE standard in 1990 (IEEE 1990). The Common Lisp dialect (Steele 1982, Steele 1990) was developed by the Lisp community to combine features from the earlier Lisp dialects to make an industrial standard for Lisp


key: chroma:document
string_value:
. Common Lisp became an ANSI standard in 1994 (ANSI 1994). 3 One such special application was a breakthrough computation of scientific importance – an integration of the motion of the Solar System that extended previous results by nearly two orders of magnitude, and demonstrated that the dynamics of the Solar System is chaotic. This computation was made possible by new integration algorithms, a special-purpose compiler , and a special-purpose computer all implemented with the aid of software tools written in Lisp (Abelson et al. 1992; Sussman and Wisdom 1992).1.1  The Elements of Programming A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we or ganize our ideas about processes. Thus, when we describe a language, we should pay particular attention to the means that the language provides for combining simple ideas to form more complex ideas. Every powerful language has three mechanisms for accomplishing t


key: chroma:document
string_value:
his: primitive expr essions , which represent the simplest entities the language is concerned with, means of combination , by which compound elements are built from simpler ones, and means of abstraction , by which compound elements can be named and manipulated as units. In programming, we deal with two kinds of elements: procedures and data. (Later we will discover that they are really not so distinct.) Informally , data is “stuf f” that we want to manipulate, and procedures are descriptions of the rules for manipulating the data. Thus, any powerful programming language should be able to describe primitive data and primitive procedures and should have methods for combining and abstracting procedures and data. In this chapter we will deal only with simple numerical data so that we can focus on the rules for building procedures.4 In later chapters we will see that these same rules allow us to build procedures to manipulate compound data as well. 1.1.1  Expr essions One easy way to get started at programming is


key: chroma:document
string_value:
 to examine some typical interactions with an interpreter for the Scheme dialect of Lisp. Imagine that you are sitting at a computer terminal. You type an expression , and theinterpreter responds by displaying the result of its evaluating  that expression. One kind of primitive expression you might type is a number . (More precisely , the expression that you type consists of the numerals that represent the number in base 10.) If you present Lisp with a number 486  the interpreter will respond by printing5 486  Expressions representing numbers may be combined with an expression representing a primitive procedure (such as + or *) to form a compound expression that represents the application of the procedure to those numbers. For example: (+ 137 349)   486  (- 1000 334)   666  (* 5 99)   495  (/ 10 5)   2  (+ 2.7 10)   12.7  Expressions such as these, formed by delimiting a list of expressions within parentheses in order to denote procedure application, are called combinations . The leftmost element in the list 


key: chroma:document
string_value:
is called the operator , and the other elements are called operands . The value of a combination is obtained by applying the procedure specified by the operator to the arguments  that are the values of the operands. The convention of placing the operator to the left of the operands is known as prefix notation , and it may be somewhat confusing at first because itdeparts significantly from the customary mathematical convention. Prefix notation has several advantages, however . One of them is that it can accommodate procedures that may take an arbitrary number of ar guments, as in the following examples: (+ 21 35 12 7)   75    (* 25 4 12)   1200  No ambiguity can arise, because the operator is always the leftmost element and the entire combination is delimited by the parentheses. A second advantage of prefix notation is that it extends in a straightforward way to allow combinations to be nested , that is, to have combinations whose elements are themselves combinations: (+ (* 3 5) (- 10 6))   19  There is no lim


key: chroma:document
string_value:
it (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as (+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))   which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form (+ (* 3        (+ (* 2 4)            (+ 3 5)))      (+ (- 10 7)         6))  following a formatting convention known as pretty-printing , in which each long combination is written so that the operands are aligned vertically . The resulting indentations display clearly the structure of the expression.6 Even with complex expressions, the interpreter always operates in the same basic cycle: It reads an expression from the terminal, evaluates the expression, and prints the result. This mode of operation is often expressed by saying that the interpreter runs in a read-eval-print loop . Observe in particular that it is not necessary to expl


key: chroma:document
string_value:
icitly instruct the interpreter to print the value of the expression.7 1.1.2  Naming and the Envir onment A critical aspect of a programming language is the means it provides for using names to refer to computational objects. We say that the name identifies a variable  whose value  is the object. In the Scheme dialect of Lisp, we name things with define . Typing (define size 2)   causes the interpreter to associate the value 2 with the name size .8 Once the name size  has been associated with the number 2, we can refer to the value 2 by name: size  2  (* 5 size)   10  Here are further examples of the use of define : (define pi 3.14159)   (define radius 10)   (* pi (* radius radius))   314.159  (define circumference (* 2 pi radius))  circumference   62.8318  Define  is our language's simplest means of abstraction, for it allows us to use simple names to refer to the results of compound operations, such as the circumference  computed above. In general, computational objects may have very complex structures, and


key: chroma:document
string_value:
 it would be extremely inconvenient to have to remember and repeat their details each time we want to use them. Indeed, complex programs are constructed by building, step by step, computational objects of increasing complexity . The interpreter makes this step-by-step program construction particularly convenient because name- object associations can be created incrementally in successive interactions. This feature encourages the incremental development and testing of programs and is lar gely responsible for the fact that a Lisp program usually consists of a lar ge number of relatively simple procedures. It should be clear that the possibility of associating values with symbols and later retrieving them means that the interpreter must maintain some sort of memory that keeps track of the name-object pairs. This memory is called the envir onment  (more precisely the global envir onment , since we will see later that a computation may involve a number of dif ferent environments).9 1.1.3  Evaluating Combinations O


key: chroma:document
string_value:
ne of our goals in this chapter is to isolate issues about thinking procedurally . As a case in point, let us consider that, in evaluating combinations, the interpreter is itself following a procedure. To evaluate a combination, do the following: 1.  Evaluate the subexpressions of the combination. 2.  Apply the procedure that is the value of the leftmost subexpression (the operator) to the ar guments that are the values of the other subexpressions (the operands). Even this simple rule illustrates some important points about processes in general. First, observe that the first step dictates that in order to accomplishthe evaluation process for a combination we must first perform the evaluation process on each element of the combination. Thus, the evaluation rule is recursive  in nature; that is, it includes, as one of its steps, the need to invoke the rule itself.10 Notice how succinctly the idea of recursion can be used to express what, in the case of a deeply nested combination, would otherwise be viewed as a


key: chroma:document
string_value:
 rather complicated process. For example, evaluating (* (+ 2 (* 4 6))      (+ 3 5 7))   requires that the evaluation rule be applied to four dif ferent combinations. We can obtain a picture of this process by representing the combination in the form of a tree, as shown in figure 1.1. Each combination is represented by a node with branches corresponding to the operator and the operands of the combination stemming from it. The terminal nodes (that is, nodes with no branches stemming from them) represent either operators or numbers. Viewing evaluation in terms of the tree, we can imagine that the values of the operands percolate upward, starting from the terminal nodes and then combining at higher and higher levels. In general, we shall see that recursion is a very powerful technique for dealing with hierarchical, treelike objects. In fact, the “percolate values upward” form of the evaluation rule is an example of a general kind of process known as tree accumulation . Figur e 1.1:   Tree representation, showing 


key: chroma:document
string_value:
the value of each subcombination.Next, observe that the repeated application of the first step brings us to the point where we need to evaluate, not combinations, but primitive expressions such as numerals, built-in operators, or other names. We take care of the primitive cases by stipulating that the values of numerals are the numbers that they name, the values of built-in operators are the machine instruction sequences that carry out the corresponding operations, and the values of other names are the objects associated with those names in the environment. We may regard the second rule as a special case of the third one by stipulating that symbols such as + and * are also included in the global environment, and are associated with the sequences of machine instructions that are their “values.” The key point to notice is the role of the environment in determining the meaning of the symbols in expressions. In an interactive language such as Lisp, it is meaningless to speak of the value of an expression such as 


key: chroma:document
string_value:
(+ x 1)  without specifying any information about the environment that would provide a meaning for the symbol x (or even for the symbol +). As we shall see in chapter 3, the general notion of the environment as providing a context in which evaluation takes place will play an important role in our understanding of program execution.Notice that the evaluation rule given above does not handle definitions. For instance, evaluating (define x 3)  does not apply define  to two arguments, one of which is the value of the symbol x and the other of which is 3, since the purpose of the define  is precisely to associate x with a value. (That is, (define x 3)  is not a combination.) Such exceptions to the general evaluation rule are called special forms . Define  is the only example of a special form that we have seen so far , but we will meet others shortly . Each special form has its own evaluation rule. The various kinds of expressions (each with its associated evaluation rule) constitute the syntax of the programming 


key: chroma:document
string_value:
language. In comparison with most other programming languages, Lisp has a very simple syntax; that is, the evaluation rule for expressions can be described by a simple general rule together with specialized rules for a small number of special forms.11 1.1.4  Compound Pr ocedur es We have identified in Lisp some of the elements that must appear in any powerful programming language: Numbers and arithmetic operations are primitive data and procedures. Nesting of combinations provides a means of combining operations. Definitions that associate names with values provide a limited means of abstraction. Now we will learn about procedur e definitions , a much more powerful abstraction technique by which a compound operation can be given a name and then referred to as a unit. We begin by examining how to express the idea of “squaring.” We might say, “To square something, multiply it by itself.” This is expressed in our language as (define (square x) (* x x))   We can understand this in the following way:(define (squar


key: chroma:document
string_value:
e  x)        (*         x     x))      ↑        ↑     ↑          ↑         ↑    ↑    To      square something, multiply   it by itself.   We have here a compound pr ocedur e, which has been given the name square . The procedure represents the operation of multiplying something by itself. The thing to be multiplied is given a local name, x, which plays the same role that a pronoun plays in natural language. Evaluating the definition creates this compound procedure and associates it with the name square .12 The general form of a procedure definition is (define (< name> <formal parameters >) <body>)  The < name > is a symbol to be associated with the procedure definition in the environment.13 The <formal parameters > are the names used within the body of the procedure to refer to the corresponding ar guments of the procedure. The <body > is an expression that will yield the value of the procedure application when the formal parameters are replaced by the actual ar guments to which the procedure is applied.14 The


key: chroma:document
string_value:
 < name > and the <formal parameters > are grouped within parentheses, just as they would be in an actual call to the procedure being defined. Having defined square , we can now use it: (square 21)   441    (square (+ 2 5))   49    (square (square 3))   81  We can also use square  as a building block in defining other procedures. For example, x2 + y2 can be expressed as(+ (square x) (square y))   We can easily define a procedure sum-of-squares  that, given any two numbers as ar guments, produces the sum of their squares: (define (sum-of-squares x y)     (+ (square x) (square y)))     (sum-of-squares 3 4)   25  Now we can use sum-of-squares  as a building block in constructing further procedures: (define (f a)     (sum-of-squares (+ a 1) (* a 2)))     (f 5)  136  Compound procedures are used in exactly the same way as primitive procedures. Indeed, one could not tell by looking at the definition of sum- of-squares  given above whether square  was built into the interpreter , like + and *, or defined as a compou


key: chroma:document
string_value:
nd procedure. 1.1.5  The Substitution Model for Pr ocedur e Application To evaluate a combination whose operator names a compound procedure, the interpreter follows much the same process as for combinations whose operators name primitive procedures, which we described in section 1.1.3 . That is, the interpreter evaluates the elements of the combination and applies the procedure (which is the value of the operator of the combination) to the ar guments (which are the values of the operands of the combination). We can assume that the mechanism for applying primitive procedures to arguments is built into the interpreter . For compound procedures, the application process is as follows:To apply a compound procedure to ar guments, evaluate the body of the procedure with each formal parameter replaced by the corresponding argument. To illustrate this process, let's evaluate the combination (f 5)  where f is the procedure defined in section 1.1.4 . We begin by retrieving the body of f: (sum-of-squares (+ a 1) (* a 2))


key: chroma:document
string_value:
   Then we replace the formal parameter a by the ar gument 5: (sum-of-squares (+ 5 1) (* 5 2))   Thus the problem reduces to the evaluation of a combination with two operands and an operator sum-of-squares . Evaluating this combination involves three subproblems. We must evaluate the operator to get the procedure to be applied, and we must evaluate the operands to get the arguments. Now (+ 5 1)  produces 6 and (* 5 2)  produces 10, so we must apply the sum-of-squares  procedure to 6 and 10. These values are substituted for the formal parameters x and y in the body of sum-of- squares , reducing the expression to (+ (square 6) (square 10))   If we use the definition of square , this reduces to (+ (* 6 6) (* 10 10))   which reduces by multiplication to (+ 36 100)   and finally to 136 The process we have just described is called the substitution model  for procedure application. It can be taken as a model that determines the “meaning” of procedure application, insofar as the procedures in this chapter are concern


key: chroma:document
string_value:
ed. However , there are two points that should be stressed: The purpose of the substitution is to help us think about procedure application, not to provide a description of how the interpreter really works. Typical interpreters do not evaluate procedure applications by manipulating the text of a procedure to substitute values for the formal parameters. In practice, the “substitution” is accomplished by using a local environment for the formal parameters. We will discuss this more fully in chapters 3 and 4 when we examine the implementation of an interpreter in detail. Over the course of this book, we will present a sequence of increasingly elaborate models of how interpreters work, culminating with a complete implementation of an interpreter and compiler in chapter 5. The substitution model is only the first of these models – a way to get started thinking formally about the evaluation process. In general, when modeling phenomena in science and engineering, we begin with simplified, incomplete models. As we ex


key: chroma:document
string_value:
amine things in greater detail, these simple models become inadequate and must be replaced by more refined models. The substitution model is no exception. In particular , when we address in chapter 3 the use of procedures with “mutable data,” we will see that the substitution model breaks down and must be replaced by a more complicated model of procedure application.15 Applicative order versus normal order According to the description of evaluation given in section 1.1.3 , the interpreter first evaluates the operator and operands and then applies the resulting procedure to the resulting ar guments. This is not the only way to perform evaluation. An alternative evaluation model would not evaluate the operands until their values were needed. Instead it would first substitute operand expressions for parameters until it obtained an expressioninvolving only primitive operators, and would then perform the evaluation. If we used this method, the evaluation of (f 5)  would proceed according to the sequence of expansi


key: chroma:document
string_value:
ons (sum-of-squares (+ 5 1) (* 5 2))     (+    (square (+ 5 1))      (square (* 5 2))  )     (+    (* (+ 5 1) (+ 5 1))   (* (* 5 2) (* 5 2)))   followed by the reductions (+         (* 6 6)             (* 10 10))     (+           36                   100)                         136   This gives the same answer as our previous evaluation model, but the process is dif ferent. In particular , the evaluations of (+ 5 1)  and (* 5 2) are each performed twice here, corresponding to the reduction of the expression (* x x)  with x replaced respectively by (+ 5 1)  and (* 5 2) . This alternative “fully expand and then reduce” evaluation method is known as normal-or der evaluation , in contrast to the “evaluate the arguments and then apply” method that the interpreter actually uses, which is called applicative-or der evaluation . It can be shown that, for procedure applications that can be modeled using substitution (including all the procedures in the first two chapters of this book) and that yield legitimate values,


key: chroma:document
string_value:
 normal-order and applicative-order evaluation produce the samevalue. (See exercise 1.5 for an instance of an “illegitimate” value where normal-order and applicative-order evaluation do not give the same result.) Lisp uses applicative-order evaluation, partly because of the additional efficiency obtained from avoiding multiple evaluations of expressions such as those illustrated with (+ 5 1)  and (* 5 2)  above and, more significantly , because normal-order evaluation becomes much more complicated to deal with when we leave the realm of procedures that can be modeled by substitution. On the other hand, normal-order evaluation can be an extremely valuable tool, and we will investigate some of its implications in chapters 3 and 4.16 1.1.6  Conditional Expr essions and Pr edicates The expressive power of the class of procedures that we can define at this point is very limited, because we have no way to make tests and to perform different operations depending on the result of a test. For instance, we cannot defin


key: chroma:document
string_value:
e a procedure that computes the absolute value of a number by testing whether the number is positive, negative, or zero and taking different actions in the dif ferent cases according to the rule This construct is called a case analysis , and there is a special form in Lisp for notating such a case analysis. It is called cond  (which stands for “conditional”), and it is used as follows: (define (abs x)     (cond ((> x 0) x)           ((= x 0) 0)           ((< x 0) (- x))))   The general form of a conditional expression is (cond (< p1> <e1>)        (< p2> <e2>)       ⋮        (< pn> <en>))  consisting of the symbol cond  followed by parenthesized pairs of expressions (<p> <e>) called clauses . The first expression in each pair is a predicate  – that is, an expression whose value is interpreted as either true or false.17 Conditional expressions are evaluated as follows. The predicate < p1> is evaluated first. If its value is false, then < p2> is evaluated. If <p2>'s value is also false, then < p3> is evaluated. 


key: chroma:document
string_value:
This process continues until a predicate is found whose value is true, in which case the interpreter returns the value of the corresponding consequent expr ession  <e> of the clause as the value of the conditional expression. If none of the < p>'s is found to be true, the value of the cond  is undefined. The word predicate  is used for procedures that return true or false, as well as for expressions that evaluate to true or false. The absolute-value procedure abs makes use of the primitive predicates >, <, and =.18 These take two numbers as ar guments and test whether the first number is, respectively , greater than, less than, or equal to the second number , returning true or false accordingly . Another way to write the absolute-value procedure is (define (abs x)     (cond ((< x 0) (- x))           (else x)))   which could be expressed in English as “If x is less than zero return - x; otherwise return x.” Else  is a special symbol that can be used in place of the <p> in the final clause of a cond . This caus


key: chroma:document
string_value:
es the cond  to return as its value the value of the corresponding < e> whenever all previous clauses have been bypassed. In fact, any expression that always evaluates to a true value could be used as the < p> here. Here is yet another way to write the absolute-value procedure:(define (abs x)     (if (< x 0)         (- x)         x))   This uses the special form if, a restricted type of conditional that can be used when there are precisely two cases in the case analysis. The general form of an if expression is (if <predicate > <consequent > <alternative >)  To evaluate an if expression, the interpreter starts by evaluating the <predicate > part of the expression. If the < predicate > evaluates to a true value, the interpreter then evaluates the <consequent > and returns its value. Otherwise it evaluates the <alternative > and returns its value.19 In addition to primitive predicates such as <, =, and >, there are logical composition operations, which enable us to construct compound predicates. The three most f


key: chroma:document
string_value:
requently used are these: (and <e1> ... <en>) The interpreter evaluates the expressions < e> one at a time, in left-to- right order . If any < e> evaluates to false, the value of the and expression is false, and the rest of the < e>'s are not evaluated. If all <e>'s evaluate to true values, the value of the and expression is the value of the last one. (or <e1> ... <en>) The interpreter evaluates the expressions < e> one at a time, in left-to- right order . If any < e> evaluates to a true value, that value is returned as the value of the or expression, and the rest of the < e>'s are not evaluated. If all < e>'s evaluate to false, the value of the or expression is false. (not <e>)The value of a not expression is true when the expression < e> evaluates to false, and false otherwise. Notice that and and or are special forms, not procedures, because the subexpressions are not necessarily all evaluated. Not is an ordinary procedure. As an example of how these are used, the condition that a number x be in the range 


key: chroma:document
string_value:
5 < x < 10 may be expressed as (and (> x 5) (< x 10))   As another example, we can define a predicate to test whether one number is greater than or equal to another as (define (>= x y)     (or (> x y) (= x y)))   or alternatively as (define (>= x y)     (not (< x y)))   Exer cise 1.1.   Below is a sequence of expressions. What is the result printed by the interpreter in response to each expression? Assume that the sequence is to be evaluated in the order in which it is presented. 10  (+ 5 3 4)   (- 9 1)  (/ 6 2)  (+ (* 2 4) (- 4 6))   (define a 3)   (define b (+ a 1))   (+ a b (* a b))   (= a b)  (if (and (> b a) (< b (* a b)))       b     a)  (cond ((= a 4) 6)         ((= b 4) (+ 6 7 a))         (else 25))   (+ 2 (if (> b a) b a))   (* (cond ((> a b) a)            ((< a b) b)            (else -1))      (+ a 1))   Exer cise 1.2.   Translate the following expression into prefix form Exer cise 1.3.   Define a procedure that takes three numbers as ar guments and returns the sum of the squares of the two lar ger 


key: chroma:document
string_value:
numbers. Exer cise 1.4.   Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure: (define (a-plus-abs-b a b)     ((if (> b 0) + -) a b))   Exer cise 1.5.   Ben Bitdiddle has invented a test to determine whether the interpreter he is faced with is using applicative-order evaluation or normal- order evaluation. He defines the following two procedures: (define (p) (p))     (define (test x y)     (if (= x 0)         0        y))   Then he evaluates the expression(test 0 (p))   What behavior will Ben observe with an interpreter that uses applicative- order evaluation? What behavior will he observe with an interpreter that uses normal-order evaluation? Explain your answer . (Assume that the evaluation rule for the special form if is the same whether the interpreter is using normal or applicative order: The predicate expression is evaluated first, and the result determines whether to evaluate the 


key: chroma:document
string_value:
consequent or the alternative expression.) 1.1.7  Example: Squar e Roots by Newton's Method Procedures, as introduced above, are much like ordinary mathematical functions. They specify a value that is determined by one or more parameters. But there is an important dif ference between mathematical functions and computer procedures. Procedures must be ef fective. As a case in point, consider the problem of computing square roots. We can define the square-root function as This describes a perfectly legitimate mathematical function. We could use it to recognize whether one number is the square root of another , or to derive facts about square roots in general. On the other hand, the definition does not describe a procedure. Indeed, it tells us almost nothing about how to actually find the square root of a given number . It will not help matters to rephrase this definition in pseudo-Lisp: (define (sqrt x)     (the y (and (>= y 0)                 (= (square y) x))))   This only begs the question. The contrast betwe


key: chroma:document
string_value:
en function and procedure is a reflection of the general distinction between describing properties of things and describing how to do things, or , as it is sometimes referred to, the distinction betweendeclarative knowledge and imperative knowledge. In mathematics we are usually concerned with declarative (what is) descriptions, whereas in computer science we are usually concerned with imperative (how to) descriptions.20 How does one compute square roots? The most common way is to use Newton's method of successive approximations, which says that whenever we have a guess y for the value of the square root of a number x, we can perform a simple manipulation to get a better guess (one closer to the actual square root) by averaging y with x/y.21 For example, we can compute the square root of 2 as follows. Suppose our initial guess is 1: Guess Quotient Average    1 (2/1) = 2 ((2 + 1)/2) = 1.5    1.5 (2/1.5) = 1.3333 ((1.3333 + 1.5)/2) = 1.4167    1.4167 (2/1.4167) = 1.4118((1.4167 + 1.41 18)/2) = 1.4142    1.4142.


key: chroma:document
string_value:
.. ... Continuing this process, we obtain better and better approximations to the square root. Now let's formalize the process in terms of procedures. We start with a value for the radicand (the number whose square root we are trying to compute) and a value for the guess. If the guess is good enough for our purposes, we are done; if not, we must repeat the process with an improved guess. We write this basic strategy as a procedure: (define (sqrt-iter guess x)     (if (good-enough? guess x)         guess         (sqrt-iter (improve guess x)                    x)))  A guess is improved by averaging it with the quotient of the radicand and the old guess: (define (improve guess x)     (average guess (/ x guess)))   where (define (average x y)     (/ (+ x y) 2))   We also have to say what we mean by “good enough.” The following will do for illustration, but it is not really a very good test. (See exercise 1.7.) The idea is to improve the answer until it is close enough so that its square differs from the radicand 


key: chroma:document
string_value:
by less than a predetermined tolerance (here 0.001):22 (define (good-enough? guess x)     (< (abs (- (square guess) x)) 0.001))   Finally , we need a way to get started. For instance, we can always guess that the square root of any number is 1:23 (define (sqrt x)     (sqrt-iter 1.0 x))   If we type these definitions to the interpreter , we can use sqrt  just as we can use any procedure: (sqrt 9)   3.00009155413138   (sqrt (+ 100 37))   11.704699917758145   (sqrt (+ (sqrt 2) (sqrt 3)))   1.7739279023207892   (square (sqrt 1000))   1000.000369924366  The sqrt  program also illustrates that the simple procedural language we have introduced so far is suf ficient for writing any purely numerical program that one could write in, say , C or Pascal. This might seem surprising, since we have not included in our language any iterative (looping) constructs that direct the computer to do something over and over again. Sqrt-iter , on the other hand, demonstrates how iteration can be accomplished using no special construct


key: chroma:document
string_value:
 other than the ordinary ability to call a procedure.24 Exer cise 1.6.   Alyssa P . Hacker doesn't see why if needs to be provided as a special form. “Why can't I just define it as an ordinary procedure in terms of cond ?” she asks. Alyssa's friend Eva Lu Ator claims this can indeed be done, and she defines a new version of if: (define (new-if predicate then-clause else-clause)     (cond (predicate then-clause)           (else else-clause)))   Eva demonstrates the program for Alyssa: (new-if (= 2 3) 0 5)   5    (new-if (= 1 1) 0 5)   0  Delighted, Alyssa uses new-if  to rewrite the square-root program: (define (sqrt-iter guess x)     (new-if (good-enough? guess x)             guess             (sqrt-iter (improve guess x)                        x)))   What happens when Alyssa attempts to use this to compute square roots? Explain.Exer cise 1.7.   The good-enough?  test used in computing square roots will not be very ef fective for finding the square roots of very small numbers. Also, in real computers, arithme


key: chroma:document
string_value:
tic operations are almost always performed with limited precision. This makes our test inadequate for very lar ge numbers. Explain these statements, with examples showing how the test fails for small and lar ge numbers. An alternative strategy for implementing good-enough?  is to watch how guess  changes from one iteration to the next and to stop when the change is a very small fraction of the guess. Design a square-root procedure that uses this kind of end test. Does this work better for small and lar ge numbers? Exer cise 1.8.   Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In section 1.3.4  we will see how to implement Newton's method in general as an abstraction of these square-root and cube- root procedures.) 1.1.8  Pr ocedur es as Black-Box Abstractions Sqrt  is our first example of a process defined by a


key: chroma:document
string_value:
 set of mutually defined procedures. Notice that the definition of sqrt-iter  is recursive ; that is, the procedure is defined in terms of itself. The idea of being able to define a procedure in terms of itself may be disturbing; it may seem unclear how such a “circular” definition could make sense at all, much less specify a well-defined process to be carried out by a computer . This will be addressed more carefully in section 1.2. But first let's consider some other important points illustrated by the sqrt  example. Observe that the problem of computing square roots breaks up naturally into a number of subproblems: how to tell whether a guess is good enough, how to improve a guess, and so on. Each of these tasks is accomplished by a separate procedure. The entire sqrt  program can be viewed as a cluster ofprocedures (shown in figure 1.2) that mirrors the decomposition of the problem into subproblems. Figur e 1.2:   Procedural decomposition of the sqrt  program. The importance of this decomposition strategy 


key: chroma:document
string_value:
is not simply that one is dividing the program into parts. After all, we could take any lar ge program and divide it into parts – the first ten lines, the next ten lines, the next ten lines, and so on. Rather , it is crucial that each procedure accomplishes an identifiable task that can be used as a module in defining other procedures. For example, when we define the good-enough?  procedure in terms of square , we are able to regard the square  procedure as a “black box.” We are not at that moment concerned with how the procedure computes its result, only with the fact that it computes the square. The details of how the square is computed can be suppressed, to be considered at a later time. Indeed, as far as the good-enough?  procedure is concerned, square  is not quite a procedure but rather an abstraction of a procedure, a so-called procedural abstraction . At this level of abstraction, any procedure that computes the square is equally good. Thus, considering only the values they return, the following two p


key: chroma:document
string_value:
rocedures for squaring a number should be indistinguishable. Each takes a numerical argument and produces the square of that number as the value.25 (define (square x) (* x x))    (define (square x)     (exp (double (log x))))     (define (double x) (+ x x))   So a procedure definition should be able to suppress detail. The users of the procedure may not have written the procedure themselves, but may have obtained it from another programmer as a black box. A user should not need to know how the procedure is implemented in order to use it. Local names One detail of a procedure's implementation that should not matter to the user of the procedure is the implementer's choice of names for the procedure's formal parameters. Thus, the following procedures should not be distinguishable: (define (square x) (* x x))     (define (square y) (* y y))   This principle – that the meaning of a procedure should be independent of the parameter names used by its author – seems on the surface to be self- evident, but its conseque


key: chroma:document
string_value:
nces are profound. The simplest consequence is that the parameter names of a procedure must be local to the body of the procedure. For example, we used square  in the definition of good-enough? in our square-root procedure: (define (good-enough? guess x)     (< (abs (- (square guess) x)) 0.001))   The intention of the author of good-enough?  is to determine if the square of the first ar gument is within a given tolerance of the second ar gument. We see that the author of good-enough?  used the name guess  to refer to the first ar gument and x to refer to the second ar gument. The ar gument of square  is guess . If the author of square  used x (as above) to refer to that argument, we see that the x in good-enough?  must be a dif ferent x than the one in square . Running the procedure square  must not af fect the value of xthat is used by good-enough? , because that value of x may be needed by good-enough?  after square  is done computing. If the parameters were not local to the bodies of their respective proce


key: chroma:document
string_value:
dures, then the parameter x in square  could be confused with the parameter x in good-enough? , and the behavior of good-enough?  would depend upon which version of square  we used. Thus, square  would not be the black box we desired. A formal parameter of a procedure has a very special role in the procedure definition, in that it doesn't matter what name the formal parameter has. Such a name is called a bound variable , and we say that the procedure definition binds  its formal parameters. The meaning of a procedure definition is unchanged if a bound variable is consistently renamed throughout the definition.26 If a variable is not bound, we say that it is free. The set of expressions for which a binding defines a name is called the scope  of that name. In a procedure definition, the bound variables declared as the formal parameters of the procedure have the body of the procedure as their scope. In the definition of good-enough?  above, guess  and x are bound variables but <, -, abs, and square  are free. Th


key: chroma:document
string_value:
e meaning of good-enough?  should be independent of the names we choose for guess  and x so long as they are distinct and dif ferent from <, -, abs, and square . (If we renamed guess  to abs we would have introduced a bug by capturing  the variable abs. It would have changed from free to bound.) The meaning of good-enough?  is not independent of the names of its free variables, however . It surely depends upon the fact (external to this definition) that the symbol abs names a procedure for computing the absolute value of a number . Good- enough?  will compute a dif ferent function if we substitute cos for abs in its definition. Internal definitions and block structur e We have one kind of name isolation available to us so far: The formal parameters of a procedure are local to the body of the procedure. The square-root program illustrates another way in which we would like tocontrol the use of names. The existing program consists of separate procedures: (define (sqrt x)     (sqrt-iter 1.0 x))   (define (sqrt-i


key: chroma:document
string_value:
ter guess x)     (if (good-enough? guess x)         guess         (sqrt-iter (improve guess x) x)))   (define (good-enough? guess x)     (< (abs (- (square guess) x)) 0.001))   (define (improve guess x)     (average guess (/ x guess)))   The problem with this program is that the only procedure that is important to users of sqrt  is sqrt . The other procedures ( sqrt-iter , good-enough? , and improve ) only clutter up their minds. They may not define any other procedure called good-enough?  as part of another program to work together with the square-root program, because sqrt  needs it. The problem is especially severe in the construction of lar ge systems by many separate programmers. For example, in the construction of a lar ge library of numerical procedures, many numerical functions are computed as successive approximations and thus might have procedures named good- enough?  and improve  as auxiliary procedures. We would like to localize the subprocedures, hiding them inside sqrt  so that sqrt  could coexi


key: chroma:document
string_value:
st with other successive approximations, each having its own private good-enough? procedure. To make this possible, we allow a procedure to have internal definitions that are local to that procedure. For example, in the square-root problem we can write (define (sqrt x)     (define (good-enough? guess x)       (< (abs (- (square guess) x)) 0.001))     (define (improve guess x)       (average guess (/ x guess)))     (define (sqrt-iter guess x)       (if (good-enough? guess x)          guess           (sqrt-iter (improve guess x) x)))     (sqrt-iter 1.0 x))   Such nesting of definitions, called block structur e, is basically the right solution to the simplest name-packaging problem. But there is a better idea lurking here. In addition to internalizing the definitions of the auxiliary procedures, we can simplify them. Since x is bound in the definition of sqrt , the procedures good-enough? , improve , and sqrt-iter , which are defined internally to sqrt , are in the scope of x. Thus, it is not necessary to pass x


key: chroma:document
string_value:
 explicitly to each of these procedures. Instead, we allow x to be a free variable in the internal definitions, as shown below . Then x gets its value from the ar gument with which the enclosing procedure sqrt  is called. This discipline is called lexical scoping .27 (define (sqrt x)     (define (good-enough? guess)       (< (abs (- (square guess) x)) 0.001))     (define (improve guess)       (average guess (/ x guess)))     (define (sqrt-iter guess)       (if (good-enough? guess)           guess           (sqrt-iter (improve guess))))     (sqrt-iter 1.0))   We will use block structure extensively to help us break up lar ge programs into tractable pieces.28 The idea of block structure originated with the programming language Algol 60. It appears in most advanced programming languages and is an important tool for helping to or ganize the construction of lar ge programs. 4 The characterization of numbers as “simple data” is a barefaced bluf f. In fact, the treatment of numbers is one of the trickiest and most c


key: chroma:document
string_value:
onfusing aspects of any programming language. Some typical issues involved are these: Some computer systems distinguish integers , such as 2, from real numbers , such as 2.71. Is the real number 2.00 dif ferent from the integer 2? Are the arithmetic operations used for integers the same as the operations used for real numbers? Does 6 divided by 2 produce 3, or 3.0? How lar ge a number can we represent? How many decimal places of accuracy canwe represent? Is the range of integers the same as the range of real numbers? Above and beyond these questions, of course, lies a collection of issues concerning roundof f and truncation errors – the entire science of numerical analysis. Since our focus in this book is on lar ge-scale program design rather than on numerical techniques, we are going to ignore these problems. The numerical examples in this chapter will exhibit the usual roundof f behavior that one observes when using arithmetic operations that preserve a limited number of decimal places of accuracy in nonint


key: chroma:document
string_value:
eger operations. 5 Throughout this book, when we wish to emphasize the distinction between the input typed by the user and the response printed by the interpreter , we will show the latter in slanted characters. 6 Lisp systems typically provide features to aid the user in formatting expressions. Two especially useful features are one that automatically indents to the proper pretty-print position whenever a new line is started and one that highlights the matching left parenthesis whenever a right parenthesis is typed. 7 Lisp obeys the convention that every expression has a value. This convention, together with the old reputation of Lisp as an inef ficient language, is the source of the quip by Alan Perlis (paraphrasing Oscar W ilde) that “Lisp programmers know the value of everything but the cost of nothing.” 8 In this book, we do not show the interpreter's response to evaluating definitions, since this is highly implementation-dependent. 9 Chapter 3 will show that this notion of environment is crucial, both f


key: chroma:document
string_value:
or understanding how the interpreter works and for implementing interpreters. 10 It may seem strange that the evaluation rule says, as part of the first step, that we should evaluate the leftmost element of a combination, since at this point that can only be an operator such as + or * representing a built-in primitive procedure such as addition or multiplication. We will see later that it is useful to be able to work with combinations whose operators are themselves compound expressions. 11 Special syntactic forms that are simply convenient alternative surface structures for things that can be written in more uniform ways are sometimes called syntactic sugar , to use a phrase coined by Peter Landin. In comparison with users of other languages, Lisp programmers, as a rule, are less concerned with matters of syntax. (By contrast, examine any Pascal manual and notice how much of it is devoted to descriptions of syntax.) This disdain for syntax is due partly to the flexibility of Lisp, which makes it easy to chang


key: chroma:document
string_value:
e surface syntax, and partly to the observation that many “convenient” syntactic constructs, which make the language less uniform, end up causing more trouble than they are worth when programs become lar ge and complex. In the words of Alan Perlis, “Syntactic sugar causes cancer of the semicolon.” 12 Observe that there are two dif ferent operations being combined here: we are creating the procedure, and we are giving it the name square . It is possible, indeed important, to be able to separate these two notions – to create procedures without naming them, and to give names to procedures that have already been created. We will see how to do this in section 1.3.2 . 13 Throughout this book, we will describe the general syntax of expressions by using italic symbols delimited by angle brackets – e.g., < name > – to denote the “slots” in the expression to be filled in when such an expression is actually used.14 More generally , the body of the procedure can be a sequence of expressions. In this case, the interpreter


key: chroma:document
string_value:
 evaluates each expression in the sequence in turn and returns the value of the final expression as the value of the procedure application. 15 Despite the simplicity of the substitution idea, it turns out to be surprisingly complicated to give a rigorous mathematical definition of the substitution process. The problem arises from the possibility of confusion between the names used for the formal parameters of a procedure and the (possibly identical) names used in the expressions to which the procedure may be applied. Indeed, there is a long history of erroneous definitions of substitution  in the literature of logic and programming semantics. See Stoy 1977 for a careful discussion of substitution. 16 In chapter 3 we will introduce stream pr ocessing , which is a way of handling apparently “infinite” data structures by incorporating a limited form of normal-order evaluation. In section 4.2 we will modify the Scheme interpreter to produce a normal-order variant of Scheme. 17 “Interpreted as either true or false


key: chroma:document
string_value:
” means this: In Scheme, there are two distinguished values that are denoted by the constants #t and #f. When the interpreter checks a predicate's value, it interprets #f as false. Any other value is treated as true. (Thus, providing #t is logically unnecessary , but it is convenient.) In this book we will use names true  and false , which are associated with the values #t and #f respectively . 18 Abs also uses the “minus” operator -, which, when used with a single operand, as in (- x) , indicates negation. 19 A minor dif ference between if and cond  is that the < e> part of each cond  clause may be a sequence of expressions. If the corresponding < p> is found to be true, the expressions < e> are evaluated in sequence and the value of the final expression in the sequence is returned as the value of the cond . In an if expression, however , the < consequent > and < alternative > must be single expressions. 20 Declarative and imperative descriptions are intimately related, as indeed are mathematics and computer


key: chroma:document
string_value:
 science. For instance, to say that the answer produced by a program is “correct” is to make a declarative statement about the program. There is a lar ge amount of research aimed at establishing techniques for proving that programs are correct, and much of the technical dif ficulty of this subject has to do with negotiating the transition between imperative statements (from which programs are constructed) and declarative statements (which can be used to deduce things). In a related vein, an important current area in programming-language design is the exploration of so-called very high- level languages, in which one actually programs in terms of declarative statements. The idea is to make interpreters sophisticated enough so that, given “what is” knowledge specified by the programmer , they can generate “how to” knowledge automatically . This cannot be done in general, but there are important areas where progress has been made. We shall revisit this idea in chapter 4. 21 This square-root algorithm is actually 


key: chroma:document
string_value:
a special case of Newton's method, which is a general technique for finding roots of equations. The square-root algorithm itself was developed by Heron of Alexandria in the first century A.D. We will see how to express the general Newton's method as a Lisp procedure in section 1.3.4 . 22 We will usually give predicates names ending with question marks, to help us remember that they are predicates. This is just a stylistic convention. As far as the interpreter is concerned, the question mark is just an ordinary character .23 Observe that we express our initial guess as 1.0 rather than 1. This would not make any dif ference in many Lisp implementations. MIT Scheme, however , distinguishes between exact integers and decimal values, and dividing two integers produces a rational number rather than a decimal. For example, dividing 10 by 6 yields 5/3, while dividing 10.0 by 6.0 yields 1.6666666666666667. (We will learn how to implement arithmetic on rational numbers in section 2.1.1 .) If we start with an initial gu


key: chroma:document
string_value:
ess of 1 in our square-root program, and x is an exact integer , all subsequent values produced in the square-root computation will be rational numbers rather than decimals. Mixed operations on rational numbers and decimals always yield decimals, so starting with an initial guess of 1.0 forces all subsequent values to be decimals. 24 Readers who are worried about the ef ficiency issues involved in using procedure calls to implement iteration should note the remarks on “tail recursion” in section 1.2.1 . 25 It is not even clear which of these procedures is a more ef ficient implementation. This depends upon the hardware available. There are machines for which the “obvious” implementation is the less efficient one. Consider a machine that has extensive tables of logarithms and antilogarithms stored in a very ef ficient manner . 26 The concept of consistent renaming is actually subtle and dif ficult to define formally . Famous logicians have made embarrassing errors here. 27 Lexical scoping dictates that free va


key: chroma:document
string_value:
riables in a procedure are taken to refer to bindings made by enclosing procedure definitions; that is, they are looked up in the environment in which the procedure was defined. We will see how this works in detail in chapter 3 when we study environments and the detailed behavior of the interpreter . 28 Embedded definitions must come first in a procedure body . The management is not responsible for the consequences of running programs that intertwine definition and use.1.2  Procedures and the Processes They Generate We have now considered the elements of programming: W e have used primitive arithmetic operations, we have combined these operations, and we have abstracted these composite operations by defining them as compound procedures. But that is not enough to enable us to say that we know how to program. Our situation is analogous to that of someone who has learned the rules for how the pieces move in chess but knows nothing of typical openings, tactics, or strategy . Like the novice chess player , we don'


key: chroma:document
string_value:
t yet know the common patterns of usage in the domain. We lack the knowledge of which moves are worth making (which procedures are worth defining). We lack the experience to predict the consequences of making a move (executing a procedure). The ability to visualize the consequences of the actions under consideration is crucial to becoming an expert programmer , just as it is in any synthetic, creative activity . In becoming an expert photographer , for example, one must learn how to look at a scene and know how dark each region will appear on a print for each possible choice of exposure and development conditions. Only then can one reason backward, planning framing, lighting, exposure, and development to obtain the desired ef fects. So it is with programming, where we are planning the course of action to be taken by a process and where we control the process by means of a program. To become experts, we must learn to visualize the processes generated by various types of procedures. Only after we have developed


key: chroma:document
string_value:
 such a skill can we learn to reliably construct programs that exhibit the desired behavior . A procedure is a pattern for the local evolution  of a computational process. It specifies how each stage of the process is built upon the previous stage. We would like to be able to make statements about the overall, or global , behavior of a process whose local evolution has been specified by a procedure. This is very dif ficult to do in general, but we can at least try to describe some typical patterns of process evolution. In this section we will examine some common “shapes” for processes generated by simple procedures. We will also investigate the rates at whichthese processes consume the important computational resources of time and space. The procedures we will consider are very simple. Their role is like that played by test patterns in photography: as oversimplified prototypical patterns, rather than practical examples in their own right. 1.2.1  Linear Recursion and Iteration Figur e 1.3:   A linear recursive


key: chroma:document
string_value:
 process for computing 6!. We begin by considering the factorial function, defined by n! = n · (n - 1) · ( n - 2) ⋯  3 · 2 · 1 There are many ways to compute factorials. One way is to make use of the observation that n! is equal to n times ( n - 1)! for any positive integer n: n! = n · [(n - 1) · ( n - 2) ⋯  3 · 2 · 1] = n · (n - 1)! Thus, we can compute n! by computing ( n - 1)! and multiplying the result by n. If we add the stipulation that 1! is equal to 1, this observation translates directly into a procedure: (define (factorial n)     (if (= n 1)         1        (* n (factorial (- n 1)))))   We can use the substitution model of section 1.1.5  to watch this procedure in action computing 6!, as shown in figure 1.3.Now let's take a dif ferent perspective on computing factorials. We could describe a rule for computing n! by specifying that we first multiply 1 by 2, then multiply the result by 3, then by 4, and so on until we reach n. More formally , we maintain a running product, together with a counter tha


key: chroma:document
string_value:
t counts from 1 up to n. We can describe the computation by saying that the counter and the product simultaneously change from one step to the next according to the rule product ⟵ counter · product counter ⟵ counter + 1 and stipulating that n! is the value of the product when the counter exceeds n. Figur e 1.4:   A linear iterative process for computing 6!. Once again, we can recast our description as a procedure for computing factorials:29 (define (factorial n)     (fact-iter 1 1 n))     (define (fact-iter product counter max-count)     (if (> counter max-count)         product         (fact-iter (* counter product)                    (+ counter 1)                    max-count)))  As before, we can use the substitution model to visualize the process of computing 6!, as shown in figure 1.4. Compare the two processes. From one point of view , they seem hardly different at all. Both compute the same mathematical function on the same domain, and each requires a number of steps proportional to n to compute n!. In


key: chroma:document
string_value:
deed, both processes even carry out the same sequence of multiplications, obtaining the same sequence of partial products. On the other hand, when we consider the “shapes” of the two processes, we find that they evolve quite dif ferently . Consider the first process. The substitution model reveals a shape of expansion followed by contraction, indicated by the arrow in figure 1.3. The expansion occurs as the process builds up a chain of deferr ed operations  (in this case, a chain of multiplications). The contraction occurs as the operations are actually performed. This type of process, characterized by a chain of deferred operations, is called a recursive pr ocess . Carrying out this process requires that the interpreter keep track of the operations to be performed later on. In the computation of n!, the length of the chain of deferred multiplications, and hence the amount of information needed to keep track of it, grows linearly with n (is proportional to n), just like the number of steps. Such a process is 


key: chroma:document
string_value:
called a linear r ecursive pr ocess . By contrast, the second process does not grow and shrink. At each step, all we need to keep track of, for any n, are the current values of the variables product , counter , and max-count . We call this an iterative pr ocess . In general, an iterative process is one whose state can be summarized by a fixed number of state variables , together with a fixed rule that describes how the state variables should be updated as the process moves from state to state and an (optional) end test that specifies conditions under which the process should terminate. In computing n!, the number of steps required grows linearly with n. Such a process is called a linear iterative pr ocess . The contrast between the two processes can be seen in another way . In the iterative case, the program variables provide a complete description of the state of the process at any point. If we stopped the computation between steps, all we would need to do to resume the computation is to supply the interpret


key: chroma:document
string_value:
er with the values of the three program variables. Not so with therecursive process. In this case there is some additional “hidden” information, maintained by the interpreter and not contained in the program variables, which indicates “where the process is” in negotiating the chain of deferred operations. The longer the chain, the more information must be maintained.30 In contrasting iteration and recursion, we must be careful not to confuse the notion of a recursive process  with the notion of a recursive procedur e. When we describe a procedure as recursive, we are referring to the syntactic fact that the procedure definition refers (either directly or indirectly) to the procedure itself. But when we describe a process as following a pattern that is, say , linearly recursive, we are speaking about how the process evolves, not about the syntax of how a procedure is written. It may seem disturbing that we refer to a recursive procedure such as fact-iter  as generating an iterative process. However , the proce


key: chroma:document
string_value:
ss really is iterative: Its state is captured completely by its three state variables, and an interpreter need keep track of only three variables in order to execute the process. One reason that the distinction between process and procedure may be confusing is that most implementations of common languages (including Ada, Pascal, and C) are designed in such a way that the interpretation of any recursive procedure consumes an amount of memory that grows with the number of procedure calls, even when the process described is, in principle, iterative. As a consequence, these languages can describe iterative processes only by resorting to special-purpose “looping constructs” such as do, repeat , until , for, and while . The implementation of Scheme we shall consider in chapter 5 does not share this defect. It will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-r ecursive . With a tail-recursive 


key: chroma:document
string_value:
implementation, iteration can be expressed using the ordinary procedure call mechanism, so that special iteration constructs are useful only as syntactic sugar .31 Exer cise 1.9.   Each of the following two procedures defines a method for adding two positive integers in terms of the procedures inc, which increments its ar gument by 1, and dec, which decrements its ar gument by 1.(define (+ a b)     (if (= a 0)         b        (inc (+ (dec a) b))))     (define (+ a b)     (if (= a 0)         b        (+ (dec a) (inc b))))   Using the substitution model, illustrate the process generated by each procedure in evaluating (+ 4 5) . Are these processes iterative or recursive? Exer cise 1.10.   The following procedure computes a mathematical function called Ackermann's function. (define (A x y)     (cond ((= y 0) 0)           ((= x 0) (* 2 y))           ((= y 1) 2)           (else (A (- x 1)                    (A x (- y 1))))))   What are the values of the following expressions? (A 1 10)     (A 2 4)    (A 3 3)  Cons


key: chroma:document
string_value:
ider the following procedures, where A is the procedure defined above: (define (f n) (A 0 n))     (define (g n) (A 1 n))     (define (h n) (A 2 n))    (define (k n) (* 5 n n))   Give concise mathematical definitions for the functions computed by the procedures f, g, and h for positive integer values of n. For example, (k n) computes 5 n2. 1.2.2  Tree Recursion Another common pattern of computation is called tree recursion . As an example, consider computing the sequence of Fibonacci numbers, in which each number is the sum of the preceding two: 0, 1, 1, 2, 3, 5, 8, 13, 21, … In general, the Fibonacci numbers can be defined by the rule We can immediately translate this definition into a recursive procedure for computing Fibonacci numbers: (define (fib n)     (cond ((= n 0) 0)           ((= n 1) 1)           (else (+ (fib (- n 1))                    (fib (- n 2))))))   Figur e 1.5:   The tree-recursive process generated in computing (fib 5) .Consider the pattern of this computation. To compute (fib 5) , we comp


key: chroma:document
string_value:
ute (fib 4)  and (fib 3) . To compute (fib 4) , we compute (fib 3)  and (fib 2). In general, the evolved process looks like a tree, as shown in figure 1.5. Notice that the branches split into two at each level (except at the bottom); this reflects the fact that the fib procedure calls itself twice each time it is invoked. This procedure is instructive as a prototypical tree recursion, but it is a terrible way to compute Fibonacci numbers because it does so much redundant computation. Notice in figure 1.5 that the entire computation of (fib 3)  – almost half the work – is duplicated. In fact, it is not hard to show that the number of times the procedure will compute (fib 1)  or (fib 0) (the number of leaves in the above tree, in general) is precisely Fib(n + 1). To get an idea of how bad this is, one can show that the value of Fib(n) grows exponentially with n. More precisely (see exercise 1.13), Fib(n) is the closest integer to φn /√5, where φ = (1 + √5)/2 ≈ 1.6180 is the golden ratio , which satisfies the eq


key: chroma:document
string_value:
uationφ2 = φ + 1 Thus, the process uses a number of steps that grows exponentially with the input. On the other hand, the space required grows only linearly with the input, because we need keep track only of which nodes are above us in the tree at any point in the computation. In general, the number of steps required by a tree-recursive process will be proportional to the number of nodes in the tree, while the space required will be proportional to the maximum depth of the tree. We can also formulate an iterative process for computing the Fibonacci numbers. The idea is to use a pair of integers a and b, initialized to Fib(1) = 1 and Fib(0) = 0, and to repeatedly apply the simultaneous transformations a ⟵ a + b  b ⟵ a It is not hard to show that, after applying this transformation n times, a and b will be equal, respectively , to Fib(n + 1) and Fib(n). Thus, we can compute Fibonacci numbers iteratively using the procedure (define (fib n)     (fib-iter 1 0 n))     (define (fib-iter a b count)     (if (= count 0


key: chroma:document
string_value:
)         b        (fib-iter (+ a b) a (- count 1))))   This second method for computing Fib(n) is a linear iteration. The difference in number of steps required by the two methods – one linear in n, one growing as fast as Fib(n) itself – is enormous, even for small inputs. One should not conclude from this that tree-recursive processes are useless. When we consider processes that operate on hierarchically structured data rather than numbers, we will find that tree recursion is a natural and powerful tool.32 But even in numerical operations, tree-recursive processes can be useful in helping us to understand and design programs. Forinstance, although the first fib procedure is much less ef ficient than the second one, it is more straightforward, being little more than a translation into Lisp of the definition of the Fibonacci sequence. To formulate the iterative algorithm required noticing that the computation could be recast as an iteration with three state variables. Example: Counting change It takes only a 


key: chroma:document
string_value:
bit of cleverness to come up with the iterative Fibonacci algorithm. In contrast, consider the following problem: How many dif ferent ways can we make change of $ 1.00, given half-dollars, quarters, dimes, nickels, and pennies? More generally , can we write a procedure to compute the number of ways to change any given amount of money? This problem has a simple solution as a recursive procedure. Suppose we think of the types of coins available as arranged in some order . Then the following relation holds: The number of ways to change amount a using n kinds of coins equals the number of ways to change amount a using all but the first kind of coin, plus the number of ways to change amount a - d using all n kinds of coins, where d is the denomination of the first kind of coin. To see why this is true, observe that the ways to make change can be divided into two groups: those that do not use any of the first kind of coin, and those that do. Therefore, the total number of ways to make change for some amount is equa


key: chroma:document
string_value:
l to the number of ways to make change for the amount without using any of the first kind of coin, plus the number of ways to make change assuming that we do use the first kind of coin. But the latter number is equal to the number of ways to make change for the amount that remains after using a coin of the first kind. Thus, we can recursively reduce the problem of changing a given amount to the problem of changing smaller amounts using fewer kinds of coins. Consider this reduction rule carefully , and convince yourself that we canuse it to describe an algorithm if we specify the following degenerate cases:33 If a is exactly 0, we should count that as 1 way to make change. If a is less than 0, we should count that as 0 ways to make change. If n is 0, we should count that as 0 ways to make change. We can easily translate this description into a recursive procedure: (define (count-change amount)     (cc amount 5))   (define (cc amount kinds-of-coins)     (cond ((= amount 0) 1)           ((or (< amount 0) (= kind


key: chroma:document
string_value:
s-of-coins 0)) 0)           (else (+ (cc amount                        (- kinds-of-coins 1))                    (cc (- amount                           (first-denomination kinds-of-coins))                        kinds-of-coins)))))   (define (first-denomination kinds-of-coins)     (cond ((= kinds-of-coins 1) 1)           ((= kinds-of-coins 2) 5)           ((= kinds-of-coins 3) 10)           ((= kinds-of-coins 4) 25)           ((= kinds-of-coins 5) 50)))   (The first-denomination  procedure takes as input the number of kinds of coins available and returns the denomination of the first kind. Here we are thinking of the coins as arranged in order from lar gest to smallest, but any order would do as well.) We can now answer our original question about changing a dollar: (count-change 100)   292 Count-change  generates a tree-recursive process with redundancies similar to those in our first implementation of fib. (It will take quite a while for that 292 to be computed.) On the other hand, it is not obvious how to 


key: chroma:document
string_value:
design a better algorithm for computing the result, and we leave this problem as a challenge. The observation that a tree-recursive process may be highly inefficient but often easy to specify and understand has led people to propose that one could get the best of both worlds by designing a “smart compiler” that could transform tree-recursive procedures into more ef ficient procedures that compute the same result.34 Exer cise 1.1 1.  A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2 f(n - 2) + 3 f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process. Exer cise 1.12.   The following pattern of numbers is called Pascal's triangle . The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it.35 Write a procedure that computes elements of Pascal's triangle by means of a recursive process. Exer cise 1.13.   Prove that Fib(n)


key: chroma:document
string_value:
 is the closest integer to φn/√5, where φ = (1 + √5)/2. Hint: Let ψ = (1 - √5)/2. Use induction and the definition of the Fibonacci numbers (see section 1.2.2 ) to prove that Fib(n) = (φn - ψn)/√5. 1.2.3  Orders of Gr owth The previous examples illustrate that processes can dif fer considerably in the rates at which they consume computational resources. One convenient way to describe this dif ference is to use the notion of order of gr owth  toobtain a gross measure of the resources required by a process as the inputs become lar ger. Let n be a parameter that measures the size of the problem, and let R(n) be the amount of resources the process requires for a problem of size n. In our previous examples we took n to be the number for which a given function is to be computed, but there are other possibilities. For instance, if our goal is to compute an approximation to the square root of a number , we might take n to be the number of digits accuracy required. For matrix multiplication we might take n to be the n


key: chroma:document
string_value:
umber of rows in the matrices. In general there are a number of properties of the problem with respect to which it will be desirable to analyze a given process. Similarly , R(n) might measure the number of internal storage registers used, the number of elementary machine operations performed, and so on. In computers that do only a fixed number of operations at a time, the time required will be proportional to the number of elementary machine operations performed. We say that R(n) has order of growth θ( f(n)), written R(n) = θ( f(n)) (pronounced “theta of f(n)”), if there are positive constants k1 and k2 independent of n such that k1f(n) ≤ R(n) ≤ k2f(n) for any suf ficiently lar ge value of n. (In other words, for lar ge n, the value R(n) is sandwiched between k1f(n) and k2f(n).) For instance, with the linear recursive process for computing factorial described in section 1.2.1  the number of steps grows proportionally to the input n. Thus, the steps required for this process grows as θ( n). We also saw that th


key: chroma:document
string_value:
e space required grows as θ( n). For the iterative factorial, the number of steps is still θ( n) but the space is θ(1) – that is, constant.36 The tree- recursive Fibonacci computation requires θ( φn) steps and space θ( n), where φ is the golden ratio described in section 1.2.2 . Orders of growth provide only a crude description of the behavior of a process. For example, a process requiring n2 steps and a process requiring 1000 n2 steps and a process requiring 3 n2 + 10 n + 17 steps all have θ( n2)order of growth. On the other hand, order of growth provides a useful indication of how we may expect the behavior of the process to change as we change the size of the problem. For a θ(n) (linear) process, doubling the size will roughly double the amount of resources used. For an exponential process, each increment in problem size will multiply the resource utilization by a constant factor . In the remainder of section 1.2 we will examine two algorithms whose order of growth is logarithmic, so that doubling the prob


key: chroma:document
string_value:
lem size increases the resource requirement by a constant amount. Exer cise 1.14.   Draw the tree illustrating the process generated by the count-change  procedure of section 1.2.2  in making change for 1 1 cents. What are the orders of growth of the space and number of steps used by this process as the amount to be changed increases? Exer cise 1.15.   The sine of an angle (specified in radians) can be computed by making use of the approximation sin x ≈ x if x is suf ficiently small, and the trigonometric identity to reduce the size of the ar gument of sin. (For purposes of this exercise an angle is considered “suf ficiently small” if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures: (define (cube x) (* x x x))   (define (p x) (- (* 3 x) (* 4 (cube x))))   (define (sine angle)      (if (not (> (abs angle) 0.1))          angle          (p (sine (/ angle 3.0)))))   a.  How many times is the procedure p applied when (sine 12.15)  is evaluated? b.  What is t


key: chroma:document
string_value:
he order of growth in space and number of steps (as a function of a) used by the process generated by the sine  procedure when (sine a) is evaluated?1.2.4  Exponentiation Consider the problem of computing the exponential of a given number . We would like a procedure that takes as ar guments a base b and a positive integer exponent n and computes bn. One way to do this is via the recursive definition bn = b · bn-1  b0 = 1 which translates readily into the procedure (define (expt b n)     (if (= n 0)         1        (* b (expt b (- n 1)))))   This is a linear recursive process, which requires θ( n) steps and θ( n) space. Just as with factorial, we can readily formulate an equivalent linear iteration: (define (expt b n)     (expt-iter b n 1))     (define (expt-iter b counter product)     (if (= counter 0)         product         (expt-iter b                   (- counter 1)                   (* b product))))   This version requires θ( n) steps and θ(1) space. We can compute exponentials in fewer steps by using s


key: chroma:document
string_value:
uccessive squaring. For instance, rather than computing b8 as b · (b · (b · (b · (b · (b · (b · b))))))we can compute it using three multiplications: b2 = b · b  b4 = b2 · b2  b8 = b4 · b4 This method works fine for exponents that are powers of 2. We can also take advantage of successive squaring in computing exponentials in general if we use the rule bn = (bn/2)2          if n is even   bn = b · bn-1         if n is odd We can express this method as a procedure: (define (fast-expt b n)     (cond ((= n 0) 1)           ((even? n) (square (fast-expt b (/ n 2))))           (else (* b (fast-expt b (- n 1))))))   where the predicate to test whether an integer is even is defined in terms of the primitive procedure remainder  by (define (even? n)     (= (remainder n 2) 0))   The process evolved by fast-expt  grows logarithmically with n in both space and number of steps. To see this, observe that computing b2n using fast-expt  requires only one more multiplication than computing bn. The size of the exponent we can c


key: chroma:document
string_value:
ompute therefore doubles (approximately) with every new multiplication we are allowed. Thus, the number of multiplications required for an exponent of n grows about as fast as the logarithm of n to the base 2. The process has θ( log n) growth.37 The dif ference between θ( log n) growth and θ( n) growth becomes striking as n becomes lar ge. For example, fast-expt  for n = 1000 requires only 14 multiplications.38 It is also possible to use the idea of successive squaring todevise an iterative algorithm that computes exponentials with a logarithmic number of steps (see exercise 1.16), although, as is often the case with iterative algorithms, this is not written down so straightforwardly as the recursive algorithm.39 Exer cise 1.16.   Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt . (Hint: Using the observation that ( bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state var


key: chroma:document
string_value:
iable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity  that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.) Exer cise 1.17.   The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt  procedure: (define (* a b)     (if (= b 0)         0        (+ a (* a (- b 1)))))   This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double , which doubles an integer , and halve , 


key: chroma:document
string_value:
which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt  that uses a logarithmic number of steps. Exer cise 1.18.   Using the results of exercises 1.16 and 1.17, devise a procedure that generates an iterative process for multiplying two integers in terms of adding, doubling, and halving and uses a logarithmic number of steps.40Exer cise 1.19.    There is a clever algorithm for computing the Fibonacci numbers in a logarithmic number of steps. Recall the transformation of the state variables a and b in the fib-iter  process of section 1.2.2 : a ⟵ a + b and b ⟵ a. Call this transformation T, and observe that applying T over and over again n times, starting with 1 and 0, produces the pair Fib(n + 1) and Fib(n). In other words, the Fibonacci numbers are produced by applying Tn, the nth power of the transformation T, starting with the pair (1,0). Now consider T to be the special case of p = 0 and q = 1 in a family of transformations Tpq, where Tpq transforms the p


key: chroma:document
string_value:
air ( a,b) according to a ⟵ bq + aq + ap and b ⟵ bp + aq. Show that if we apply such a transformation Tpq twice, the ef fect is the same as using a single transformation Tp'q' of the same form, and compute p' and q' in terms of p and q. This gives us an explicit way to square these transformations, and thus we can compute Tn using successive squaring, as in the fast-expt procedure. Put this all together to complete the following procedure, which runs in a logarithmic number of steps:41 (define (fib n)     (fib-iter 1 0 0 1 n))   (define (fib-iter a b p q count)     (cond ((= count 0) b)           ((even? count)            (fib-iter a                      b                      < ??>      ; compute p'                     < ??>      ; compute q'                     (/ count 2)))           (else (fib-iter (+ (* b q) (* a q) (* a p))                           (+ (* b p) (* a q))                           p                           q                           (- count 1)))))   1.2.5  Gr eatest Common DivisorsThe 


key: chroma:document
string_value:
greatest common divisor (GCD) of two integers a and b is defined to be the lar gest integer that divides both a and b with no remainder . For example, the GCD of 16 and 28 is 4. In chapter 2, when we investigate how to implement rational-number arithmetic, we will need to be able to compute GCDs in order to reduce rational numbers to lowest terms. (To reduce a rational number to lowest terms, we must divide both the numerator and the denominator by their GCD. For example, 16/28 reduces to 4/7.) One way to find the GCD of two integers is to factor them and search for common factors, but there is a famous algorithm that is much more ef ficient. The idea of the algorithm is based on the observation that, if r is the remainder when a is divided by b, then the common divisors of a and b are precisely the same as the common divisors of b and r. Thus, we can use the equation GCD(a, b) = GCD( b, r) to successively reduce the problem of computing a GCD to the problem of computing the GCD of smaller and smaller pairs o


key: chroma:document
string_value:
f integers. For example,   GCD(206, 40) = GCD(40, 6)                = GCD(6, 4)                = GCD(4, 2)                = GCD(2, 0)                = 2   reduces GCD(206,40) to GCD(2,0), which is 2. It is possible to show that starting with any two positive integers and performing repeated reductions will always eventually produce a pair where the second number is 0. Then the GCD is the other number in the pair . This method for computing the GCD is known as Euclid's Algorithm .42 It is easy to express Euclid's Algorithm as a procedure: (define (gcd a b)     (if (= b 0)        a        (gcd b (remainder a b))))   This generates an iterative process, whose number of steps grows as the logarithm of the numbers involved. The fact that the number of steps required by Euclid's Algorithm has logarithmic growth bears an interesting relation to the Fibonacci numbers: Lamé's Theor em: If Euclid's Algorithm requires k steps to compute the GCD of some pair , then the smaller number in the pair must be greater than or e


key: chroma:document
string_value:
qual to the kth Fibonacci number .43 We can use this theorem to get an order -of-growth estimate for Euclid's Algorithm. Let n be the smaller of the two inputs to the procedure. If the process takes k steps, then we must have n> Fib (k) ≈ φk/√5. Therefore the number of steps k grows as the logarithm (to the base φ) of n. Hence, the order of growth is θ( log n). Exer cise 1.20.   The process that a procedure generates is of course dependent on the rules used by the interpreter . As an example, consider the iterative gcd procedure given above. Suppose we were to interpret this procedure using normal-order evaluation, as discussed in section 1.1.5 . (The normal-order -evaluation rule for if is described in exercise 1.5.) Using the substitution method (for normal order), illustrate the process generated in evaluating (gcd 206 40)  and indicate the remainder  operations that are actually performed. How many remainder  operations are actually performed in the normal-order evaluation of (gcd 206 40) ? In the applica


key: chroma:document
string_value:
tive-order evaluation? 1.2.6  Example: T esting for Primality This section describes two methods for checking the primality of an integer n, one with order of growth θ(√ n), and a “probabilistic” algorithm with order of growth θ( log n). The exercises at the end of this section suggest programming projects based on these algorithms. Sear ching for divisorsSince ancient times, mathematicians have been fascinated by problems concerning prime numbers, and many people have worked on the problem of determining ways to test if numbers are prime. One way to test if a number is prime is to find the number's divisors. The following program finds the smallest integral divisor (greater than 1) of a given number n. It does this in a straightforward way , by testing n for divisibility by successive integers starting with 2. (define (smallest-divisor n)     (find-divisor n 2))   (define (find-divisor n test-divisor)     (cond ((> (square test-divisor) n) n)           ((divides? test-divisor n) test-divisor)           (else


key: chroma:document
string_value:
 (find-divisor n (+ test-divisor 1)))))   (define (divides? a b)     (= (remainder b a) 0))   We can test whether a number is prime as follows: n is prime if and only if n is its own smallest divisor . (define (prime? n)     (= n (smallest-divisor n)))   The end test for find-divisor  is based on the fact that if n is not prime it must have a divisor less than or equal to √ n.44 This means that the algorithm need only test divisors between 1 and √ n. Consequently , the number of steps required to identify n as prime will have order of growth θ(√ n). The Fermat test The θ(log n) primality test is based on a result from number theory known as Fermat's Little Theorem.45 Fermat's Little Theor em: If n is a prime number and a is any positive integer less than n, then a raised to the nth power is congruent to a modulo n.(Two numbers are said to be congruent modulo  n if they both have the same remainder when divided by n. The remainder of a number a when divided by n is also referred to as the remainder of  a modul


key: chroma:document
string_value:
o  n, or simply as a modulo  n.) If n is not prime, then, in general, most of the numbers a< n will not satisfy the above relation. This leads to the following algorithm for testing primality: Given a number n, pick a random number a < n and compute the remainder of an modulo n. If the result is not equal to a, then n is certainly not prime. If it is a, then chances are good that n is prime. Now pick another random number a and test it with the same method. If it also satisfies the equation, then we can be even more confident that n is prime. By trying more and more values of a, we can increase our confidence in the result. This algorithm is known as the Fermat test. To implement the Fermat test, we need a procedure that computes the exponential of a number modulo another number: (define (expmod base exp m)     (cond ((= exp 0) 1)           ((even? exp)            (remainder (square (expmod base (/ exp 2) m))                       m))           (else            (remainder (* base (expmod base (- exp 1) m))   


key: chroma:document
string_value:
                    m))))          This is very similar to the fast-expt  procedure of section 1.2.4 . It uses successive squaring, so that the number of steps grows logarithmically with the exponent.46 The Fermat test is performed by choosing at random a number a between 1 and n - 1 inclusive and checking whether the remainder modulo n of the nth power of a is equal to a. The random number a is chosen using the procedure random , which we assume is included as a primitive in Scheme. Random  returns a nonnegative integer less than its integer input. Hence, to obtain a random number between 1 and n - 1, we call random  with an input of n - 1 and add 1 to the result:(define (fermat-test n)     (define (try-it a)       (= (expmod a n n) a))     (try-it (+ 1 (random (- n 1)))))   The following procedure runs the test a given number of times, as specified by a parameter . Its value is true if the test succeeds every time, and false otherwise. (define (fast-prime? n times)     (cond ((= times 0) true)           ((f


key: chroma:document
string_value:
ermat-test n) (fast-prime? n (- times 1)))           (else false)))   Probabilistic methods The Fermat test dif fers in character from most familiar algorithms, in which one computes an answer that is guaranteed to be correct. Here, the answer obtained is only probably correct. More precisely , if n ever fails the Fermat test, we can be certain that n is not prime. But the fact that n passes the test, while an extremely strong indication, is still not a guarantee that n is prime. What we would like to say is that for any number n, if we perform the test enough times and find that n always passes the test, then the probability of error in our primality test can be made as small as we like. Unfortunately , this assertion is not quite correct. There do exist numbers that fool the Fermat test: numbers n that are not prime and yet have the property that an is congruent to a modulo n for all integers a < n. Such numbers are extremely rare, so the Fermat test is quite reliable in practice.47 There are variations of 


key: chroma:document
string_value:
the Fermat test that cannot be fooled. In these tests, as with the Fermat method, one tests the primality of an integer n by choosing a random integer a<n and checking some condition that depends upon n and a. (See exercise 1.28 for an example of such a test.) On the other hand, in contrast to the Fermat test, one can prove that, for any n, the condition does not hold for most of the integers a<n unless n is prime. Thus, if n passes the test for some random choice of a, the chances are better than even that n is prime. If n passes the test for two random choicesof a, the chances are better than 3 out of 4 that n is prime. By running the test with more and more randomly chosen values of a we can make the probability of error as small as we like. The existence of tests for which one can prove that the chance of error becomes arbitrarily small has sparked interest in algorithms of this type, which have come to be known as probabilistic algorithms . There is a great deal of research activity in this area, and pro


key: chroma:document
string_value:
babilistic algorithms have been fruitfully applied to many fields.48 Exer cise 1.21.   Use the smallest-divisor  procedure to find the smallest divisor of each of the following numbers: 199, 1999, 19999. Exer cise 1.22.   Most Lisp implementations include a primitive called runtime  that returns an integer that specifies the amount of time the system has been running (measured, for example, in microseconds). The following timed-prime-test  procedure, when called with an integer n, prints n and checks to see if n is prime. If n is prime, the procedure prints three asterisks followed by the amount of time used in performing the test. (define (timed-prime-test n)     (newline)     (display n)     (start-prime-test n (runtime)))   (define (start-prime-test n start-time)     (if (prime? n)         (report-prime (- (runtime) start-time))))   (define (report-prime elapsed-time)     (display " *** ")     (display elapsed-time))   Using this procedure, write a procedure search-for-primes  that checks the primality of 


key: chroma:document
string_value:
consecutive odd integers in a specified range. Use your procedure to find the three smallest primes lar ger than 1000; lar ger than 10,000; lar ger than 100,000; lar ger than 1,000,000. Note the time needed to test each prime. Since the testing algorithm has order of growth of θ(√ n), you should expect that testing for primes around 10,000 should take about √10 times as long as testing for primes around 1000. Do your timing databear this out? How well do the data for 100,000 and 1,000,000 support the √n prediction? Is your result compatible with the notion that programs on your machine run in time proportional to the number of steps required for the computation? Exer cise 1.23.   The smallest-divisor  procedure shown at the start of this section does lots of needless testing: After it checks to see if the number is divisible by 2 there is no point in checking to see if it is divisible by any larger even numbers. This suggests that the values used for test-divisor should not be 2, 3, 4, 5, 6, ..., but rather 2


key: chroma:document
string_value:
, 3, 5, 7, 9, .... To implement this change, define a procedure next  that returns 3 if its input is equal to 2 and otherwise returns its input plus 2. Modify the smallest-divisor procedure to use (next test-divisor)  instead of (+ test-divisor 1) . With timed-prime-test  incorporating this modified version of smallest- divisor , run the test for each of the 12 primes found in exercise 1.22. Since this modification halves the number of test steps, you should expect it to run about twice as fast. Is this expectation confirmed? If not, what is the observed ratio of the speeds of the two algorithms, and how do you explain the fact that it is dif ferent from 2? Exer cise 1.24.   Modify the timed-prime-test  procedure of exercise 1.22 to use fast-prime?  (the Fermat method), and test each of the 12 primes you found in that exercise. Since the Fermat test has θ( log n) growth, how would you expect the time to test primes near 1,000,000 to compare with the time needed to test primes near 1000? Do your data bear this


key: chroma:document
string_value:
 out? Can you explain any discrepancy you find? Exer cise 1.25.   Alyssa P . Hacker complains that we went to a lot of extra work in writing expmod . After all, she says, since we already know how to compute exponentials, we could have simply written (define (expmod base exp m)     (remainder (fast-expt base exp) m))   Is she correct? Would this procedure serve as well for our fast prime tester? Explain.Exer cise 1.26.   Louis Reasoner is having great dif ficulty doing exercise 1.24. His fast-prime?  test seems to run more slowly than his prime?  test. Louis calls his friend Eva Lu Ator over to help. When they examine Louis's code, they find that he has rewritten the expmod  procedure to use an explicit multiplication, rather than calling square : (define (expmod base exp m)     (cond ((= exp 0) 1)           ((even? exp)            (remainder (* (expmod base (/ exp 2) m)                          (expmod base (/ exp 2) m))                       m))           (else            (remainder (* base (expmod base (- 


