# embeddings_queue

created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6465920s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "sit  or withdraw  procedure, which is then applied to the specified amount . As was the case with make- withdraw , another call to make-account (define acc2 (make-account 100))  will produce a completely separate account object, which maintains its own local balance . Exer cise 3.1.   An accumulator  is a procedure that is called repeatedly with a single numeric ar gument and accumulates its ar guments into a sum. Each time it is called, it returns the currently accumulated sum. Write a procedure make-accumulator  that generates accumulators, each maintaining an independent sum. The input to make-accumulator  should specify the initial value of the sum; for example (define A (make-accumulator 5))   (A 10)  15  (A 10)  25  Exer cise 3.2.   In software-testing applications, it is useful to be able to count the number of times a given procedure is called during the course of a computation. Write a procedure make-monitored  that takes as input a procedure, f, that itself takes one input. The result returned by ma"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6466944k
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ke- monitored  is a third procedure, say mf, that keeps track of the number of times it has been called by maintaining an internal counter . If the input to mf is the special symbol how-many-calls? , then mf returns the value of the counter . If the input is the special symbol reset-count , then mf resets the counter to zero. For any other input, mf returns the result of calling f on that input and increments the counter . For instance, we could make a monitored version of the sqrt  procedure: (define s (make-monitored sqrt))     (s 100)  10    (s 'how-many-calls?)   1  Exer cise 3.3.   Modify the make-account  procedure so that it creates password-protected accounts. That is, make-account  should take a symbolas an additional ar gument, as in (define acc (make-account 100 'secret-password))   The resulting account object should process a request only if it is accompanied by the password with which the account was created, and should otherwise return a complaint: ((acc 'secret-password 'withdraw) 40)   60    "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6467968(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "((acc 'some-other-password 'deposit) 50)   \"Incorrect password\"   Exer cise 3.4.   Modify the make-account  procedure of exercise 3.3 by adding another local state variable so that, if an account is accessed more than seven consecutive times with an incorrect password, it invokes the procedure call-the-cops . 3.1.2  The Benefits of Intr oducing Assignment As we shall see, introducing assignment into our programming language leads us into a thicket of dif ficult conceptual issues. Nevertheless, viewing systems as collections of objects with local state is a powerful technique for maintaining a modular design. As a simple example, consider the design of a procedure rand  that, whenever it is called, returns an integer chosen at random. It is not at all clear what is meant by \u201cchosen at random.\u201d What we presumably want is for successive calls to rand  to produce a sequence of numbers that has statistical properties of uniform distribution. We will not discuss methods for generating suitable sequences here. Rathe"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6468992r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "r , let us assume that we have a procedure rand-update  that has the property that if we start with a given number x1 and form x2 = (rand-update x1)  x3 = (rand-update x2) then the sequence of values x1, x2, x3, ..., will have the desired statistical properties.6 We can implement rand  as a procedure with a local state variable x that is initialized to some fixed value random-init . Each call to rand  computes rand-update  of the current value of x, returns this as the random number , and also stores this as the new value of x. (define rand     (let ((x random-init))       (lambda ()         (set! x (rand-update x))         x)))   Of course, we could generate the same sequence of random numbers without using assignment by simply calling rand-update  directly . However , this would mean that any part of our program that used random numbers would have to explicitly remember the current value of x to be passed as an ar gument to rand-update . To realize what an annoyance this would be, consider using random numb"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6470016e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ers to implement a technique called Monte Carlo simulation . The Monte Carlo method consists of choosing sample experiments at random from a lar ge set and then making deductions on the basis of the probabilities estimated from tabulating the results of those experiments. For example, we can approximate \u03c0 using the fact that 6/\u03c02 is the probability that two integers chosen at random will have no factors in common; that is, that their greatest common divisor will be 1.7 To obtain the approximation to \u03c0, we perform a lar ge number of experiments. In each experiment we choose two integers at random and perform a test to see if their GCD is 1. The fraction of times that the test is passed gives us our estimate of 6/\u03c02, and from this we obtain our approximation to \u03c0. The heart of our program is a procedure monte-carlo , which takes as arguments the number of times to try an experiment, together with the experiment, represented as a no-ar gument procedure that will return either true or false each time it is run. M"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6471040o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "onte-carlo  runs the experiment for thedesignated number of trials and returns a number telling the fraction of the trials in which the experiment was found to be true. (define (estimate-pi trials)     (sqrt (/ 6 (monte-carlo trials cesaro-test))))   (define (cesaro-test)      (= (gcd (rand) (rand)) 1))   (define (monte-carlo trials experiment)     (define (iter trials-remaining trials-passed)       (cond ((= trials-remaining 0)              (/ trials-passed trials))             ((experiment)              (iter (- trials-remaining 1) (+ trials-passed 1)))             (else              (iter (- trials-remaining 1) trials-passed))))     (iter trials 0))   Now let us try the same computation using rand-update  directly rather than rand , the way we would be forced to proceed if we did not use assignment to model local state: (define (estimate-pi trials)     (sqrt (/ 6 (random-gcd-test trials random-init))))   (define (random-gcd-test trials initial-x)     (define (iter trials-remaining trials-passed x)       (l"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6472064e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "et ((x1 (rand-update x)))         (let ((x2 (rand-update x1)))           (cond ((= trials-remaining 0)                    (/ trials-passed trials))                 ((= (gcd x1 x2) 1)                  (iter (- trials-remaining 1)                        (+ trials-passed 1)                        x2))                 (else                  (iter (- trials-remaining 1)                        trials-passed                       x2))))))     (iter trials 0 initial-x))   While the program is still simple, it betrays some painful breaches of modularity . In our first version of the program, using rand , we can express the Monte Carlo method directly as a general monte-carlo  procedure that takes as an ar gument an arbitrary experiment  procedure. In our second version of the program, with no local state for the random-number generator , random-gcd-test  must explicitly manipulate the random numbers x1 and x2 and recycle x2 through the iterative loop as the new input to rand-update . This explicit handling of the rand"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6473088o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "om numbers intertwines the structure of accumulating test results with the fact that our particular experiment uses two random numbers, whereas other Monte Carlo experiments might use one random number or three. Even the top- level procedure estimate-pi  has to be concerned with supplying an initial random number . The fact that the random-number generator's insides are leaking out into other parts of the program makes it dif ficult for us to isolate the Monte Carlo idea so that it can be applied to other tasks. In the first version of the program, assignment encapsulates the state of the random- number generator within the rand  procedure, so that the details of random- number generation remain independent of the rest of the program. The general phenomenon illustrated by the Monte Carlo example is this: From the point of view of one part of a complex process, the other parts appear to change with time. They have hidden time-varying local state. If we wish to write computer programs whose structure reflects t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6474112h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "his decomposition, we make computational objects (such as bank accounts and random-number generators) whose behavior changes with time. We model state with local state variables, and we model the changes of state with assignments to those variables. It is tempting to conclude this discussion by saying that, by introducing assignment and the technique of hiding state in local variables, we are able to structure systems in a more modular fashion than if all state had to be manipulated explicitly , by passing additional parameters. Unfortunately , as we shall see, the story is not so simple.Exer cise 3.5.   Monte Carlo integration  is a method of estimating definite integrals by means of Monte Carlo simulation. Consider computing the area of a region of space described by a predicate P(x, y) that is true for points (x, y) in the region and false for points not in the region. For example, the region contained within a circle of radius 3 centered at (5, 7) is described by the predicate that tests whether ( x - 5)2"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6475136
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " + (y - 7)2< 32. To estimate the area of the region described by such a predicate, begin by choosing a rectangle that contains the region. For example, a rectangle with diagonally opposite corners at (2, 4) and (8, 10) contains the circle above. The desired integral is the area of that portion of the rectangle that lies in the region. We can estimate the integral by picking, at random, points ( x,y) that lie in the rectangle, and testing P(x, y) for each point to determine whether the point lies in the region. If we try this with many points, then the fraction of points that fall in the region should give an estimate of the proportion of the rectangle that lies in the region. Hence, multiplying this fraction by the area of the entire rectangle should produce an estimate of the integral. Implement Monte Carlo integration as a procedure estimate-integral  that takes as ar guments a predicate P, upper and lower bounds x1, x2, y1, and y2 for the rectangle, and the number of trials to perform in order to produce t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6476160h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "he estimate. Your procedure should use the same monte-carlo  procedure that was used above to estimate \u03c0. Use your estimate-integral  to produce an estimate of \u03c0 by measuring the area of a unit circle. You will find it useful to have a procedure that returns a number chosen at random from a given range. The following random-in-range  procedure implements this in terms of the random  procedure used in section 1.2.6 , which returns a nonnegative number less than its input.8 (define (random-in-range low high)     (let ((range (- high low)))       (+ low (random range))))   Exer cise 3.6.   It is useful to be able to reset a random-number generator to produce a sequence starting from a given value. Design a new rand procedure that is called with an ar gument that is either the symbol generate or the symbol reset  and behaves as follows: (rand 'generate)  produces anew random number; ((rand 'reset) < new-value >) resets the internal state variable to the designated < new-value >. Thus, by resetting the state, one "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6477184c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "can generate repeatable sequences. These are very handy to have when testing and debugging programs that use random numbers. 3.1.3  The Costs of Intr oducing Assignment As we have seen, the set!  operation enables us to model objects that have local state. However , this advantage comes at a price. Our programming language can no longer be interpreted in terms of the substitution model of procedure application that we introduced in section 1.1.5 . Moreover , no simple model with \u201cnice\u201d mathematical properties can be an adequate framework for dealing with objects and assignment in programming languages. So long as we do not use assignments, two evaluations of the same procedure with the same ar guments will produce the same result, so that procedures can be viewed as computing mathematical functions. Programming without any use of assignments, as we did throughout the first two chapters of this book, is accordingly known as functional programming . To understand how assignment complicates matters, consider a s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6478208i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "implified version of the make-withdraw  procedure of section 3.1.1  that does not bother to check for an insuf ficient amount: (define (make-simplified-withdraw balance)     (lambda (amount)       (set! balance (- balance amount))       balance))   (define W (make-simplified-withdraw 25))   (W 20)  5  (W 10)  - 5  Compare this procedure with the following make-decrementer  procedure, which does not use set! :(define (make-decrementer balance)     (lambda (amount)       (- balance amount)))   Make-decrementer  returns a procedure that subtracts its input from a designated amount balance , but there is no accumulated ef fect over successive calls, as with make-simplified-withdraw : (define D (make-decrementer 25))   (D 20)  5  (D 10)  15  We can use the substitution model to explain how make-decrementer works. For instance, let us analyze the evaluation of the expression ((make-decrementer 25) 20)   We first simplify the operator of the combination by substituting 25 for balance  in the body of make-decrementer"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6479232
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " . This reduces the expression to ((lambda (amount) (- 25 amount)) 20)   Now we apply the operator by substituting 20 for amount  in the body of the lambda  expression: (- 25 20)   The final answer is 5. Observe, however , what happens if we attempt a similar substitution analysis with make-simplified-withdraw : ((make-simplified-withdraw 25) 20)   We first simplify the operator by substituting 25 for balance  in the body of make-simplified-withdraw . This reduces the expression to9((lambda (amount) (set! balance (- 25 amount)) 25) 20)   Now we apply the operator by substituting 20 for amount  in the body of the lambda  expression: (set! balance (- 25 20)) 25   If we adhered to the substitution model, we would have to say that the meaning of the procedure application is to first set balance  to 5 and then return 25 as the value of the expression. This gets the wrong answer . In order to get the correct answer , we would have to somehow distinguish the first occurrence of balance  (before the ef fect of the se"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6480256t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "t! ) from the second occurrence of balance  (after the ef fect of the set! ), and the substitution model cannot do this. The trouble here is that substitution is based ultimately on the notion that the symbols in our language are essentially names for values. But as soon as we introduce set!  and the idea that the value of a variable can change, a variable can no longer be simply a name. Now a variable somehow refers to a place where a value can be stored, and the value stored at this place can change. In section 3.2 we will see how environments play this role of \u201cplace\u201d in our computational model. Sameness and change The issue surfacing here is more profound than the mere breakdown of a particular model of computation. As soon as we introduce change into our computational models, many notions that were previously straightforward become problematical. Consider the concept of two things being \u201cthe same.\u201d Suppose we call make-decrementer  twice with the same ar gument to create two procedures: (define D1 (make-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6481280d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "decrementer 25))   (define D2 (make-decrementer 25))  Are D1 and D2 the same? An acceptable answer is yes, because D1 and D2 have the same computational behavior \u2013 each is a procedure that subtracts its input from 25. In fact, D1 could be substituted for D2 in any computation without changing the result. Contrast this with making two calls to make-simplified-withdraw : (define W1 (make-simplified-withdraw 25))   (define W2 (make-simplified-withdraw 25))   Are W1 and W2 the same? Surely not, because calls to W1 and W2 have distinct effects, as shown by the following sequence of interactions: (W1 20)  5  (W1 20)  - 15  (W2 20)  5  Even though W1 and W2 are \u201cequal\u201d in the sense that they are both created by evaluating the same expression, (make-simplified-withdraw 25) , it is not true that W1 could be substituted for W2 in any expression without changing the result of evaluating the expression. A language that supports the concept that \u201cequals can be substituted for equals\u201d in an expresssion without changing the"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6482304
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " value of the expression is said to be referentially transpar ent. Referential transparency is violated when we include set!  in our computer language. This makes it tricky to determine when we can simplify expressions by substituting equivalent expressions. Consequently , reasoning about programs that use assignment becomes drastically more dif ficult. Once we for go referential transparency , the notion of what it means for computational objects to be \u201cthe same\u201d becomes dif ficult to capture in a formal way . Indeed, the meaning of \u201csame\u201d in the real world that our programs model is hardly clear in itself. In general, we can determine that two apparently identical objects are indeed \u201cthe same one\u201d only bymodifying one object and then observing whether the other object has changed in the same way . But how can we tell if an object has \u201cchanged\u201d other than by observing the \u201csame\u201d object twice and seeing whether some property of the object dif fers from one observation to the next? Thus, we cannot determine \u201cc"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6483328h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "hange\u201d without some a priori  notion of \u201csameness,\u201d and we cannot determine sameness without observing the ef fects of change. As an example of how this issue arises in programming, consider the situation where Peter and Paul have a bank account with $100 in it. There is a substantial dif ference between modeling this as (define peter-acc (make-account 100))   (define paul-acc (make-account 100))   and modeling it as (define peter-acc (make-account 100))   (define paul-acc peter-acc)   In the first situation, the two bank accounts are distinct. Transactions made by Peter will not af fect Paul's account, and vice versa. In the second situation, however , we have defined paul-acc  to be the same thing  as peter-acc . In effect, Peter and Paul now have a joint bank account, and if Peter makes a withdrawal from peter-acc  Paul will observe less money in paul-acc . These two similar but distinct situations can cause confusion in building computational models. With the shared account, in particular , it can be espe"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6484352c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cially confusing that there is one object (the bank account) that has two dif ferent names ( peter-acc  and paul-acc ); if we are searching for all the places in our program where paul-acc  can be changed, we must remember to look also at things that change peter-acc .10 With reference to the above remarks on \u201csameness\u201d and \u201cchange,\u201d observe that if Peter and Paul could only examine their bank balances, and could not perform operations that changed the balance, then the issue of whether the two accounts are distinct would be moot. In general, so long as we never modify data objects, we can regard a compound data object to be precisely the totality of its pieces. For example, a rational number is determined by giving its numerator and its denominator . But this view is no longer valid inthe presence of change, where a compound data object has an \u201cidentity\u201d that is something dif ferent from the pieces of which it is composed. A bank account is still \u201cthe same\u201d bank account even if we change the balance by makin"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6485376g
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "g a withdrawal; conversely , we could have two dif ferent bank accounts with the same state information. This complication is a consequence, not of our programming language, but of our perception of a bank account as an object. We do not, for example, ordinarily regard a rational number as a changeable object with identity , such that we could change the numerator and still have \u201cthe same\u201d rational number . Pitfalls of imperative pr ogramming In contrast to functional programming, programming that makes extensive use of assignment is known as imperative pr ogramming . In addition to raising complications about computational models, programs written in imperative style are susceptible to bugs that cannot occur in functional programs. For example, recall the iterative factorial program from section 1.2.1 : (define (factorial n)     (define (iter product counter)       (if (> counter n)           product           (iter (* counter product)                 (+ counter 1))))     (iter 1 1))   Instead of passing ar "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6486400g
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "guments in the internal iterative loop, we could adopt a more imperative style by using explicit assignment to update the values of the variables product  and counter : (define (factorial n)     (let ((product 1)           (counter 1))       (define (iter)         (if (> counter n)             product            (begin (set! product (* counter product))                    (set! counter (+ counter 1))                    (iter))))       (iter)))   This does not change the results produced by the program, but it does introduce a subtle trap. How do we decide the order of the assignments? As it happens, the program is correct as written. But writing the assignments in the opposite order (set! counter (+ counter 1))   (set! product (* counter product))   would have produced a dif ferent, incorrect result. In general, programming with assignment forces us to carefully consider the relative orders of the assignments to make sure that each statement is using the correct version of the variables that have been changed"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6487424.
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ". This issue simply does not arise in functional programs.11 The complexity of imperative programs becomes even worse if we consider applications in which several processes execute concurrently . We will return to this in section 3.4. First, however , we will address the issue of providing a computational model for expressions that involve assignment, and explore the uses of objects with local state in designing simulations. Exer cise 3.7.   Consider the bank account objects created by make-account , with the password modification described in exercise 3.3. Suppose that our banking system requires the ability to make joint accounts. Define a procedure make-joint  that accomplishes this. Make-joint  should take three arguments. The first is a password-protected account. The second ar gument must match the password with which the account was defined in order for the make-joint  operation to proceed. The third ar gument is a new password. Make-joint  is to create an additional access to the original account usin"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6488448g
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "g the new password. For example, if peter-acc  is a bank account with password open-sesame , then (define paul-acc     (make-joint peter-acc 'open-sesame 'rosebud))  will allow one to make transactions on peter-acc  using the name paul-acc and the password rosebud . You may wish to modify your solution to exercise 3.3 to accommodate this new feature. Exer cise 3.8.   When we defined the evaluation model in section 1.1.3 , we said that the first step in evaluating an expression is to evaluate its subexpressions. But we never specified the order in which the subexpressions should be evaluated (e.g., left to right or right to left). When we introduce assignment, the order in which the ar guments to a procedure are evaluated can make a dif ference to the result. Define a simple procedure f such that evaluating (+ (f 0) (f 1))  will return 0 if the ar guments to + are evaluated from left to right but will return 1 if the ar guments are evaluated from right to left. 1 Actually , this is not quite true. One exceptio"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6489472n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "n was the random-number generator in section 1.2.6 . Another exception involved the operation/type tables we introduced in section 2.4.3 , where the values of two calls to get with the same ar guments depended on intervening calls to put. On the other hand, until we introduce assignment, we have no way to create such procedures ourselves. 2 The value of a set!  expression is implementation-dependent. Set!  should be used only for its effect, not for its value. The name set!  reflects a naming convention used in Scheme: Operations that change the values of variables (or that change data structures, as we will see in section 3.3) are given names that end with an exclamation point. This is similar to the convention of designating predicates by names that end with a question mark. 3 We have already used begin  implicitly in our programs, because in Scheme the body of a procedure can be a sequence of expressions. Also, the < consequent > part of each clause in a cond  expression can be a sequence of expressions ra"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6490496t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ther than a single expression. 4 In programming-language jar gon, the variable balance  is said to be encapsulated  within the new- withdraw  procedure. Encapsulation reflects the general system-design principle known as the hiding principle : One can make a system more modular and robust by protecting parts of the system from each other; that is, by providing information access only to those parts of the system that have a \u201cneed to know .\u201d 5 In contrast with new-withdraw  above, we do not have to use let to make balance  a local variable, since formal parameters are already local. This will be clearer after the discussion of the environment model of evaluation in section 3.2. (See also exercise 3.10.) 6 One common way to implement rand-update  is to use the rule that x is updated to ax + b modulo m, where a, b, and m are appropriately chosen integers. Chapter 3 of Knuth 1981 includes an extensive discussion of techniques for generating sequences of random numbers and establishingtheir statistical properties."}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6491520
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " Notice that the rand-update  procedure computes a mathematical function: Given the same input twice, it produces the same output. Therefore, the number sequence produced by rand-update  certainly is not \u201crandom,\u201d if by \u201crandom\u201d we insist that each number in the sequence is unrelated to the preceding number . The relation between \u201creal randomness\u201d and so-called pseudo-random  sequences, which are produced by well-determined computations and yet have suitable statistical properties, is a complex question involving dif ficult issues in mathematics and philosophy . Kolmogorov , Solomonof f, and Chaitin have made great progress in clarifying these issues; a discussion can be found in Chaitin 1975. 7 This theorem is due to E. Ces\u00e0ro. See section 4.5.2 of Knuth 1981 for a discussion and a proof. 8 MIT Scheme provides such a procedure. If random  is given an exact integer (as in section 1.2.6 ) it returns an exact integer , but if it is given a decimal value (as in this exercise) it returns a decimal value. 9 We don"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6492544'
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "'t substitute for the occurrence of balance  in the set!  expression because the < name > in a set!  is not evaluated. If we did substitute for it, we would get (set! 25 (- 25 amount)) , which makes no sense. 10 The phenomenon of a single computational object being accessed by more than one name is known as aliasing . The joint bank account situation illustrates a very simple example of an alias. In section 3.3 we will see much more complex examples, such as \u201cdistinct\u201d compound data structures that share parts. Bugs can occur in our programs if we for get that a change to an object may also, as a \u201cside ef fect,\u201d change a \u201cdif ferent\u201d object because the two \u201cdif ferent\u201d objects are actually a single object appearing under dif ferent aliases. These so-called side-effect bugs  are so dif ficult to locate and to analyze that some people have proposed that programming languages be designed in such a way as to not allow side ef fects or aliasing (Lampson et al. 1981; Morris, Schmidt, and W adler 1980). 11 In view o"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6493568f
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "f this, it is ironic that introductory programming is most often taught in a highly imperative style. This may be a vestige of a belief, common throughout the 1960s and 1970s, that programs that call procedures must inherently be less ef ficient than programs that perform assignments. (Steele (1977) debunks this ar gument.) Alternatively it may reflect a view that step-by- step assignment is easier for beginners to visualize than procedure call. Whatever the reason, it often saddles beginning programmers with \u201cshould I set this variable before or after that one\u201d concerns that can complicate programming and obscure the important ideas.3.2  The Environment Model of Evaluation When we introduced compound procedures in chapter 1, we used the substitution model of evaluation (section 1.1.5 ) to define what is meant by applying a procedure to ar guments: To apply a compound procedure to ar guments, evaluate the body of the procedure with each formal parameter replaced by the corresponding argument. Once we admit as"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6494592s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "signment into our programming language, such a definition is no longer adequate. In particular , section 3.1.3  argued that, in the presence of assignment, a variable can no longer be considered to be merely a name for a value. Rather , a variable must somehow designate a \u201cplace\u201d in which values can be stored. In our new model of evaluation, these places will be maintained in structures called envir onments . An environment is a sequence of frames . Each frame is a table (possibly empty) of bindings , which associate variable names with their corresponding values. (A single frame may contain at most one binding for any variable.) Each frame also has a pointer to its enclosing envir onment , unless, for the purposes of discussion, the frame is considered to be global . The value of a variable  with respect to an environment is the value given by the binding of the variable in the first frame in the environment that contains a binding for that variable. If no frame in the sequence specifies a binding for the va"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6495616r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "riable, then the variable is said to be unbound  in the environment. Figur e 3.1:   A simple environment structure.Figure 3.1 shows a simple environment structure consisting of three frames, labeled I, II, and III. In the diagram, A, B, C, and D are pointers to environments. C and D point to the same environment. The variables z and x are bound in frame II, while y and x are bound in frame I. The value of x in environment D is 3. The value of x with respect to environment B is also 3. This is determined as follows: W e examine the first frame in the sequence (frame III) and do not find a binding for x, so we proceed to the enclosing environment D and find the binding in frame I. On the other hand, the value of x in environment A is 7, because the first frame in the sequence (frame II) contains a binding of x to 7. With respect to environment A, the binding of x to 7 in frame II is said to shadow  the binding of x to 3 in frame I. The environment is crucial to the evaluation process, because it determines the "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6496640c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "context in which an expression should be evaluated. Indeed, one could say that expressions in a programming language do not, in themselves, have any meaning. Rather , an expression acquires a meaning only with respect to some environment in which it is evaluated. Even the interpretation of an expression as straightforward as (+ 1 1)  depends on an understanding that one is operating in a context in which + is the symbol for addition. Thus, in our model of evaluation we will always speak of evaluating an expression with respect to some environment. To describe interactions with the interpreter , we will suppose that there is a global environment, consisting of a single frame (with no enclosing environment) that includes values for the symbols associated with the primitive procedures. For example, the idea that + is the symbol for addition is captured by saying that the symbol + is bound in the global environment to the primitive addition procedure. 3.2.1  The Rules for Evaluation The overall specification of h"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6497664o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ow the interpreter evaluates a combination remains the same as when we first introduced it in section 1.1.3 : To evaluate a combination: 1.  Evaluate the subexpressions of the combination.122.  Apply the value of the operator subexpression to the values of the operand subexpressions. The environment model of evaluation replaces the substitution model in specifying what it means to apply a compound procedure to ar guments. In the environment model of evaluation, a procedure is always a pair consisting of some code and a pointer to an environment. Procedures are created in one way only: by evaluating a lambda  expression. This produces a procedure whose code is obtained from the text of the lambda  expression and whose environment is the environment in which the lambda  expression was evaluated to produce the procedure. For example, consider the procedure definition (define (square x)     (* x x))   evaluated in the global environment. The procedure definition syntax is just syntactic sugar for an underlying im"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6498688p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "plicit lambda  expression. It would have been equivalent to have used (define square     (lambda (x) (* x x)))   which evaluates (lambda (x) (* x x))  and binds square  to the resulting value, all in the global environment. Figure 3.2 shows the result of evaluating this define  expression. The procedure object is a pair whose code specifies that the procedure has one formal parameter , namely x, and a procedure body (* x x) . The environment part of the procedure is a pointer to the global environment, since that is the environment in which the lambda  expression was evaluated to produce the procedure. A new binding, which associates the procedure object with the symbol square , has been added to the global frame. In general, define  creates definitions by adding bindings to frames. Figur e 3.2:   Environment structure produced by evaluating (define (square x) (* x x))  in the global environment.Now that we have seen how procedures are created, we can describe how procedures are applied. The environment model"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6499712
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " specifies: T o apply a procedure to ar guments, create a new environment containing a frame that binds the parameters to the values of the ar guments. The enclosing environment of this frame is the environment specified by the procedure. Now , within this new environment, evaluate the procedure body . To show how this rule is followed, figure 3.3 illustrates the environment structure created by evaluating the expression (square 5)  in the global environment, where square  is the procedure generated in figure 3.2. Applying the procedure results in the creation of a new environment, labeled E1 in the figure, that begins with a frame in which x, the formal parameter for the procedure, is bound to the ar gument 5. The pointer leading upward from this frame shows that the frame's enclosing environment is the global environment. The global environment is chosen here, because this is the environment that is indicated as part of the square procedure object. Within E1, we evaluate the body of the procedure, (* x x). "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6500736S
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "Since the value of x in E1 is 5, the result is (* 5 5) , or 25. Figur e 3.3:   Environment created by evaluating (square 5)  in the global environment.The environment model of procedure application can be summarized by two rules: A procedure object is applied to a set of ar guments by constructing a frame, binding the formal parameters of the procedure to the arguments of the call, and then evaluating the body of the procedure in the context of the new environment constructed. The new frame has as its enclosing environment the environment part of the procedure object being applied. A procedure is created by evaluating a lambda  expression relative to a given environment. The resulting procedure object is a pair consisting of the text of the lambda  expression and a pointer to the environment in which the procedure was created. We also specify that defining a symbol using define  creates a binding in the current environment frame and assigns to the symbol the indicated value.13 Finally , we specify the behavio"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6501760r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "r of set! , the operation that forced us to introduce the environment model in the first place. Evaluating the expression (set! <variable > <value>) in some environment locates the binding of the variable in the environment and changes that binding to indicate the new value. That is, one finds the first frame in the environment that contains a binding for the variable and modifies that frame. If the variable is unbound in the environment, then set!  signals an error . These evaluation rules, though considerably more complex than the substitution model, are still reasonably straightforward. Moreover , the evaluation model, though abstract, provides a correct description of how the interpreter evaluates expressions. In chapter 4 we shall see how this model can serve as a blueprint for implementing a working interpreter . The following sections elaborate the details of the model by analyzing some illustrative programs. 3.2.2  Applying Simple Pr ocedur es When we introduced the substitution model in section 1.1.5"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6502784
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "  we showed how the combination (f 5)  evaluates to 136, given the following proceduredefinitions: (define (square x)     (* x x))   (define (sum-of-squares x y)     (+ (square x) (square y)))   (define (f a)     (sum-of-squares (+ a 1) (* a 2)))   We can analyze the same example using the environment model. Figure 3.4 shows the three procedure objects created by evaluating the definitions of f, square , and sum-of-squares  in the global environment. Each procedure object consists of some code, together with a pointer to the global environment. Figur e 3.4:   Procedure objects in the global frame. In figure 3.5 we see the environment structure created by evaluating the expression (f 5) . The call to f creates a new environment E1 beginning with a frame in which a, the formal parameter of f, is bound to the argument 5. In E1, we evaluate the body of f: (sum-of-squares (+ a 1) (* a 2))   Figur e 3.5:   Environments created by evaluating (f 5)  using the procedures in figure 3.4.To evaluate this combination, we "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6503808f
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "first evaluate the subexpressions. The first subexpression, sum-of-squares , has a value that is a procedure object. (Notice how this value is found: W e first look in the first frame of E1, which contains no binding for sum-of-squares . Then we proceed to the enclosing environment, i.e. the global environment, and find the binding shown in figure 3.4.) The other two subexpressions are evaluated by applying the primitive operations + and * to evaluate the two combinations (+ a 1)  and (* a 2)  to obtain 6 and 10, respectively . Now we apply the procedure object sum-of-squares  to the ar guments 6 and 10. This results in a new environment E2 in which the formal parameters x and y are bound to the ar guments. Within E2 we evaluate the combination (+ (square x) (square y)) . This leads us to evaluate (square x) , where square  is found in the global frame and x is 6. Once again, we set up a new environment, E3, in which x is bound to 6, and within this we evaluate the body of square , which is (* x x) . Also as "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6504832p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "part of applying sum-of-squares , we must evaluate the subexpression (square y), where y is 10. This second call to square  creates another environment, E4, in which x, the formal parameter of square , is bound to 10. And within E4 we must evaluate (* x x) . The important point to observe is that each call to square  creates a new environment containing a binding for x. We can see here how the dif ferent frames serve to keep separate the dif ferent local variables all named x. Notice that each frame created by square  points to the global environment, since this is the environment indicated by the square  procedure object.After the subexpressions are evaluated, the results are returned. The values generated by the two calls to square  are added by sum-of-squares , and this result is returned by f. Since our focus here is on the environment structures, we will not dwell on how these returned values are passed from call to call; however , this is also an important aspect of the evaluation process, and we will r"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6505856e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eturn to it in detail in chapter 5. Exer cise 3.9.   In section 1.2.1  we used the substitution model to analyze two procedures for computing factorials, a recursive version (define (factorial n)     (if (= n 1)         1        (* n (factorial (- n 1)))))   and an iterative version (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)))   Show the environment structures created by evaluating (factorial 6) using each version of the factorial  procedure.14 3.2.3  Frames as the Repository of Local State We can turn to the environment model to see how procedures and assignment can be used to represent objects with local state. As an example, consider the \u201cwithdrawal processor\u201d from section 3.1.1  created by calling the procedure (define (make-withdraw balance)     (lambda (amount)      (if (>= balance amount)           (begin (s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6506880e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "et! balance (- balance amount))                  balance)           \"Insufficient funds\")))   Let us describe the evaluation of (define W1 (make-withdraw 100))   followed by (W1 50)  50  Figure 3.6 shows the result of defining the make-withdraw  procedure in the global environment. This produces a procedure object that contains a pointer to the global environment. So far , this is no dif ferent from the examples we have already seen, except that the body of the procedure is itself a lambda  expression. Figur e 3.6:   Result of defining make-withdraw  in the global environment. The interesting part of the computation happens when we apply the procedure make-withdraw  to an ar gument: (define W1 (make-withdraw 100))  We begin, as usual, by setting up an environment E1 in which the formal parameter balance  is bound to the ar gument 100. Within this environment, we evaluate the body of make-withdraw , namely the lambda  expression. This constructs a new procedure object, whose code is as specified by the lambda "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6507904
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " and whose environment is E1, the environment in which the lambda was evaluated to produce the procedure. The resulting procedure object is the value returned by the call to make-withdraw . This is bound to W1 in the global environment, since the define  itself is being evaluated in the global environment. Figure 3.7 shows the resulting environment structure. Figur e 3.7:   Result of evaluating (define W1 (make-withdraw 100)) . Now we can analyze what happens when W1 is applied to an ar gument: (W1 50)  50  We begin by constructing a frame in which amount , the formal parameter of W1, is bound to the ar gument 50. The crucial point to observe is that this frame has as its enclosing environment not the global environment, but rather the environment E1, because this is the environment that is specified by the W1 procedure object. Within this new environment, we evaluate the body of the procedure: (if (>= balance amount)       (begin (set! balance (- balance amount))             balance)       \"Insufficient fund"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6508928s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s\")   The resulting environment structure is shown in figure 3.8. The expression being evaluated references both amount  and balance . Amount  will be found in the first frame in the environment, while balance  will be found by following the enclosing-environment pointer to E1. Figur e 3.8:   Environments created by applying the procedure object W1. When the set!  is executed, the binding of balance  in E1 is changed. At the completion of the call to W1, balance  is 50, and the frame that contains balance  is still pointed to by the procedure object W1. The frame that binds amount  (in which we executed the code that changed balance ) is no longer relevant, since the procedure call that constructed it has terminated, and there are no pointers to that frame from other parts of the environment. The next time W1 is called, this will build a new frame that binds amount  and whose enclosing environment is E1. We see that E1 serves as the \u201cplace\u201d that holds the local state variable for the procedure object W1. Figu"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6509952r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "re 3.9 shows the situation after the call to W1. Figur e 3.9:   Environments after the call to W1.Observe what happens when we create a second \u201cwithdraw\u201d object by making another call to make-withdraw : (define W2 (make-withdraw 100))   This produces the environment structure of figure 3.10, which shows that W2 is a procedure object, that is, a pair with some code and an environment. The environment E2 for W2 was created by the call to make-withdraw . It contains a frame with its own local binding for balance . On the other hand, W1 and W2 have the same code: the code specified by the lambda  expression in the body of make-withdraw .15 We see here why W1 and W2 behave as independent objects. Calls to W1 reference the state variable balance  stored in E1, whereas calls to W2 reference the balance  stored in E2. Thus, changes to the local state of one object do not af fect the other object. Figur e 3.10:   Using (define W2 (make-withdraw 100))  to create a second object.Exer cise 3.10.   In the make-withdraw  p"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6510976r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "rocedure, the local variable balance is created as a parameter of make-withdraw . We could also create the local state variable explicitly , using let, as follows: (define (make-withdraw initial-amount)     (let ((balance initial-amount))       (lambda (amount)         (if (>= balance amount)             (begin (set! balance (- balance amount))                    balance)             \"Insufficient funds\"))))   Recall from section 1.3.2  that let is simply syntactic sugar for a procedure call: (let ((< var> <exp>)) <body>)  is interpreted as an alternate syntax for ((lambda (< var>) <body>) <exp>)  Use the environment model to analyze this alternate version of make- withdraw , drawing figures like the ones above to illustrate the interactions (define W1 (make-withdraw 100))     (W1 50)    (define W2 (make-withdraw 100))   Show that the two versions of make-withdraw  create objects with the same behavior . How do the environment structures dif fer for the two versions? 3.2.4  Internal Definitions Section 1.1.8 "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6512000
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " introduced the idea that procedures can have internal definitions, thus leading to a block structure as in the following procedure to compute square roots:(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))   Now we can use the environment model to see why these internal definitions behave as desired. Figure 3.11 shows the point in the evaluation of the expression (sqrt 2)  where the internal procedure good-enough?  has been called for the first time with guess  equal to 1. Figur e 3.1 1:  Sqrt  procedure with internal definitions. Observe the structure of the environment. Sqrt  is a symbol in the global environment that is bound to a procedure object whose associated environment is the global environment. When sqrt  was called, a new environment E1 was formed, subordin"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6513024a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ate to the global environment, in which the parameter x is bound to 2. The body of sqrt  was then evaluated in E1. Since the first expression in the body of sqrt  is(define (good-enough? guess)     (< (abs (- (square guess) x)) 0.001))   evaluating this expression defined the procedure good-enough?  in the environment E1. To be more precise, the symbol good-enough?  was added to the first frame of E1, bound to a procedure object whose associated environment is E1. Similarly , improve  and sqrt-iter  were defined as procedures in E1. For conciseness, figure 3.11 shows only the procedure object for good-enough? . After the local procedures were defined, the expression (sqrt-iter 1.0) was evaluated, still in environment E1. So the procedure object bound to sqrt-iter  in E1 was called with 1 as an ar gument. This created an environment E2 in which guess , the parameter of sqrt-iter , is bound to 1. Sqrt-iter  in turn called good-enough?  with the value of guess  (from E2) as the ar gument for good-enough? . This "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6514048s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "set up another environment, E3, in which guess  (the parameter of good-enough? ) is bound to 1. Although sqrt-iter  and good-enough?  both have a parameter named guess , these are two distinct local variables located in dif ferent frames. Also, E2 and E3 both have E1 as their enclosing environment, because the sqrt-iter  and good-enough?  procedures both have E1 as their environment part. One consequence of this is that the symbol x that appears in the body of good- enough?  will reference the binding of x that appears in E1, namely the value of x with which the original sqrt  procedure was called. The environment model thus explains the two key properties that make local procedure definitions a useful technique for modularizing programs: The names of the local procedures do not interfere with names external to the enclosing procedure, because the local procedure names will be bound in the frame that the procedure creates when it is run, rather than being bound in the global environment. The local procedures "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6515072c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "can access the ar guments of the enclosing procedure, simply by using parameter names as free variables. This is because the body of the local procedure is evaluated in an environment that is subordinate to the evaluation environment for the enclosing procedure.Exer cise 3.1 1.  In section 3.2.3  we saw how the environment model described the behavior of procedures with local state. Now we have seen how internal definitions work. A typical message-passing procedure contains both of these aspects. Consider the bank account procedure of section 3.1.1 : (define (make-account balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))                  balance)           \"Insufficient funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     (define (dispatch m)       (cond ((eq? m 'withdraw) withdraw)             ((eq? m 'deposit) deposit)             (else (error \"Unknown request -- MAKE-ACCOUNT\"                   "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6516096
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "       m))))     dispatch)   Show the environment structure generated by the sequence of interactions (define acc (make-account 50))     ((acc 'deposit) 40)   90    ((acc 'withdraw) 60)   30  Where is the local state for acc kept? Suppose we define another account (define acc2 (make-account 100))   How are the local states for the two accounts kept distinct? Which parts of the environment structure are shared between acc and acc2 ?12 Assignment introduces a subtlety into step 1 of the evaluation rule. As shown in exercise 3.8, the presence of assignment allows us to write expressions that will produce dif ferent values depending on the order in which the subexpressions in a combination are evaluated. Thus, to be precise, we should specify an evaluation order in step 1 (e.g., left to right or right to left). However , this order should always be considered to be an implementation detail, and one should never write programs that depend on some particular order . For instance, a sophisticated compiler might opti"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6517120m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "mize a program by varying the order in which subexpressions are evaluated. 13 If there is already a binding for the variable in the current frame, then the binding is changed. This is convenient because it allows redefinition of symbols; however , it also means that define  can be used to change values, and this brings up the issues of assignment without explicitly using set! . Because of this, some people prefer redefinitions of existing symbols to signal errors or warnings. 14 The environment model will not clarify our claim in section 1.2.1  that the interpreter can execute a procedure such as fact-iter  in a constant amount of space using tail recursion. We will discuss tail recursion when we deal with the control structure of the interpreter in section 5.4. 15 Whether W1 and W2 share the same physical code stored in the computer , or whether they each keep a copy of the code, is a detail of the implementation. For the interpreter we implement in chapter 4, the code is in fact shared.3.3  Modeling with Mu"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6518144t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "table Data Chapter 2 dealt with compound data as a means for constructing computational objects that have several parts, in order to model real-world objects that have several aspects. In that chapter we introduced the discipline of data abstraction, according to which data structures are specified in terms of constructors, which create data objects, and selectors, which access the parts of compound data objects. But we now know that there is another aspect of data that chapter 2 did not address. The desire to model systems composed of objects that have changing state leads us to the need to modify compound data objects, as well as to construct and select from them. In order to model compound objects with changing state, we will design data abstractions to include, in addition to selectors and constructors, operations called mutators , which modify data objects. For instance, modeling a banking system requires us to change account balances. Thus, a data structure for representing bank accounts might admit an "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6519168o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "operation (set-balance! < account> <new-value >)  that changes the balance of the designated account to the designated new value. Data objects for which mutators are defined are known as mutable data objects . Chapter 2 introduced pairs as a general-purpose \u201cglue\u201d for synthesizing compound data. We begin this section by defining basic mutators for pairs, so that pairs can serve as building blocks for constructing mutable data objects. These mutators greatly enhance the representational power of pairs, enabling us to build data structures other than the sequences and trees that we worked with in section 2.2. We also present some examples of simulations in which complex systems are modeled as collections of objects with local state. 3.3.1  Mutable List Structur eThe basic operations on pairs \u2013 cons , car, and cdr \u2013 can be used to construct list structure and to select parts from list structure, but they are incapable of modifying list structure. The same is true of the list operations we have used so far , such"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6520192
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " as append  and list , since these can be defined in terms of cons , car, and cdr. To modify list structures we need new operations. Figur e 3.12:   Lists x: ((a b) c d)  and y: (e f) . Figur e 3.13:   Effect of (set-car! x y)  on the lists in figure 3.12. Figur e 3.14:   Effect of (define z (cons y (cdr x)))  on the lists in figure 3.12.Figur e 3.15:   Effect of (set-cdr! x y)  on the lists in figure 3.12. The primitive mutators for pairs are set-car!  and set-cdr! . Set-car! takes two ar guments, the first of which must be a pair . It modifies this pair , replacing the car pointer by a pointer to the second ar gument of set-car! .16 As an example, suppose that x is bound to the list ((a b) c d)  and y to the list (e f)  as illustrated in figure 3.12. Evaluating the expression (set-car! x y)  modifies the pair to which x is bound, replacing its car by the value of y. The result of the operation is shown in figure 3.13. The structure x has been modified and would now be printed as ((e f) c d) . The pairs repr"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6521216e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "esenting the list (a b) , identified by the pointer that was replaced, are now detached from the original structure.17 Compare figure 3.13 with figure 3.14, which illustrates the result of executing (define z (cons y (cdr x)))  with x and y bound to the original lists of figure 3.12. The variable z is now bound to a new pair created by the cons  operation; the list to which x is bound is unchanged.The set-cdr!  operation is similar to set-car! . The only dif ference is that the cdr pointer of the pair , rather than the car pointer , is replaced. The effect of executing (set-cdr! x y)  on the lists of figure 3.12 is shown in figure 3.15. Here the cdr pointer of x has been replaced by the pointer to (e f). Also, the list (c d) , which used to be the cdr of x, is now detached from the structure. Cons  builds new list structure by creating new pairs, while set-car!  and set-cdr!  modify existing pairs. Indeed, we could implement cons  in terms of the two mutators, together with a procedure get-new-pair , which re"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6522240t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "turns a new pair that is not part of any existing list structure. We obtain the new pair, set its car and cdr pointers to the designated objects, and return the new pair as the result of the cons .18 (define (cons x y)     (let ((new (get-new-pair)))       (set-car! new x)       (set-cdr! new y)       new))   Exer cise 3.12.   The following procedure for appending lists was introduced in section 2.2.1 : (define (append x y)     (if (null? x)         y        (cons (car x) (append (cdr x) y))))   Append  forms a new list by successively cons ing the elements of x onto y. The procedure append!  is similar to append , but it is a mutator rather than a constructor . It appends the lists by splicing them together , modifying the final pair of x so that its cdr is now y. (It is an error to call append!  with an empty x.) (define (append! x y)     (set-cdr! (last-pair x) y)     x) Here last-pair  is a procedure that returns the last pair in its ar gument: (define (last-pair x)     (if (null? (cdr x))         x      "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6523264
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "  (last-pair (cdr x))))   Consider the interaction (define x (list 'a 'b))   (define y (list 'c 'd))   (define z (append x y))   z  (a b c d)   (cdr x)  <response >  (define w (append! x y))   w  (a b c d)   (cdr x)  <response >  What are the missing < response >s? Draw box-and-pointer diagrams to explain your answer . Exer cise 3.13.   Consider the following make-cycle  procedure, which uses the last-pair  procedure defined in exercise 3.12: (define (make-cycle x)     (set-cdr! (last-pair x) x)     x)  Draw a box-and-pointer diagram that shows the structure z created by (define z (make-cycle (list 'a 'b 'c)))   What happens if we try to compute (last-pair z) ?Exer cise 3.14.   The following procedure is quite useful, although obscure: (define (mystery x)     (define (loop x y)       (if (null? x)           y           (let ((temp (cdr x)))             (set-cdr! x y)             (loop temp x))))     (loop x '()))   Loop  uses the \u201ctemporary\u201d variable temp  to hold the old value of the cdr of x, since the set-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6524288c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cdr!  on the next line destroys the cdr. Explain what mystery  does in general. Suppose v is defined by (define v (list 'a 'b 'c 'd)) . Draw the box-and-pointer diagram that represents the list to which v is bound. Suppose that we now evaluate (define w (mystery v)) . Draw box-and-pointer diagrams that show the structures v and w after evaluating this expression. What would be printed as the values of v and w ? Sharing and identity We mentioned in section 3.1.3  the theoretical issues of \u201csameness\u201d and \u201cchange\u201d raised by the introduction of assignment. These issues arise in practice when individual pairs are shared among dif ferent data objects. For example, consider the structure formed by (define x (list 'a 'b))   (define z1 (cons x x))   As shown in figure 3.16, z1 is a pair whose car and cdr both point to the same pair x. This sharing of x by the car and cdr of z1 is a consequence of the straightforward way in which cons  is implemented. In general, using cons  to construct lists will result in an interli"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6525312n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "nked structure of pairs in which many individual pairs are shared by many dif ferent structures. Figur e 3.16:   The list z1 formed by (cons x x) .Figur e 3.17:   The list z2 formed by (cons (list 'a 'b) (list 'a 'b)) . In contrast to figure 3.16, figure 3.17 shows the structure created by (define z2 (cons (list 'a 'b) (list 'a 'b)))   In this structure, the pairs in the two (a b)  lists are distinct, although the actual symbols are shared.19 When thought of as a list, z1 and z2 both represent \u201cthe same\u201d list, ((a b) a b) . In general, sharing is completely undetectable if we operate on lists using only cons , car, and cdr. However , if we allow mutators on list structure, sharing becomes significant. As an example of the dif ference that sharing can make, consider the following procedure, which modifies the car of the structure to which it is applied: (define (set-to-wow! x)     (set-car! (car x) 'wow)     x)  Even though z1 and z2 are \u201cthe same\u201d structure, applying set-to-wow!  to them yields dif ferent res"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6526336u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ults. With z1, altering the car also changes the cdr, because in z1 the car and the cdr are the same pair . With z2, the car and cdr are distinct, so set-to-wow!  modifies only the car: z1  ((a b) a b)    (set-to-wow! z1)   ((wow b) wow b)     z2  ((a b) a b)     (set-to-wow! z2)   ((wow b) a b)   One way to detect sharing in list structures is to use the predicate eq?, which we introduced in section 2.3.1  as a way to test whether two symbols are equal. More generally , (eq? x y)  tests whether x and y are the same object (that is, whether x and y are equal as pointers). Thus, with z1 and z2 as defined in figures 3.16 and 3.17, (eq? (car z1) (cdr z1))  is true and (eq? (car z2) (cdr z2))  is false. As will be seen in the following sections, we can exploit sharing to greatly extend the repertoire of data structures that can be represented by pairs. On the other hand, sharing can also be dangerous, since modifications made to structures will also af fect other structures that happen to share the modified parts"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6527360.
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ". The mutation operations set-car!  and set-cdr!  should be used with care; unless we have a good understanding of how our data objects are shared, mutation can have unanticipated results.20 Exer cise 3.15.   Draw box-and-pointer diagrams to explain the ef fect of set-to-wow!  on the structures z1 and z2 above. Exer cise 3.16.   Ben Bitdiddle decides to write a procedure to count the number of pairs in any list structure. \u201cIt's easy ,\u201d he reasons. \u201cThe number of pairs in any structure is the number in the car plus the number in the cdr plus one more to count the current pair .\u201d So Ben writes the following procedure: (define (count-pairs x)     (if (not (pair? x))         0        (+ (count-pairs (car x))           (count-pairs (cdr x))            1)))   Show that this procedure is not correct. In particular , draw box-and-pointer diagrams representing list structures made up of exactly three pairs for which Ben's procedure would return 3; return 4; return 7; never return at all. Exer cise 3.17.   Devise a cor"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6528384r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "rect version of the count-pairs  procedure of exercise 3.16 that returns the number of distinct pairs in any structure. (Hint: T raverse the structure, maintaining an auxiliary data structure that is used to keep track of which pairs have already been counted.) Exer cise 3.18.   Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists. Exer cise 3.19.   Redo exercise 3.18 using an algorithm that takes only a constant amount of space. (This requires a very clever idea.) Mutation is just assignment When we introduced compound data, we observed in section 2.1.3  that pairs can be represented purely in terms of procedures: (define (cons x y)     (define (dispatch m)       (cond ((eq? m 'car) x)             ((eq? m 'cdr) y)             (else (error \"Undefined operation -- CONS\" m))))     dispatch)   (define (car z) (z 'car))   (de"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6529408f
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "fine (cdr z) (z 'cdr))   The same observation is true for mutable data. We can implement mutable data objects as procedures using assignment and local state. For instance, we can extend the above pair implementation to handle set-car!  and set-cdr!  in a manner analogous to the way we implemented bank accounts using make-account  in section 3.1.1 : (define (cons x y)     (define (set-x! v) (set! x v))     (define (set-y! v) (set! y v))     (define (dispatch m)       (cond ((eq? m 'car) x)             ((eq? m 'cdr) y)             ((eq? m 'set-car!) set-x!)             ((eq? m 'set-cdr!) set-y!)             (else (error \"Undefined operation -- CONS\" m))))     dispatch)   (define (car z) (z 'car))   (define (cdr z) (z 'cdr))   (define (set-car! z new-value)     ((z 'set-car!) new-value)     z)  (define (set-cdr! z new-value)     ((z 'set-cdr!) new-value)     z)  Assignment is all that is needed, theoretically , to account for the behavior of mutable data. As soon as we admit set!  to our language, we raise all t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6530432h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "he issues, not only of assignment, but of mutable data in general.21 Exer cise 3.20.   Draw environment diagrams to illustrate the evaluation of the sequence of expressions (define x (cons 1 2))   (define z (cons x x))   (set-car! (cdr z) 17)   (car x)  17  using the procedural implementation of pairs given above. (Compare exercise 3.11.)3.3.2  Repr esenting Queues The mutators set-car!  and set-cdr!  enable us to use pairs to construct data structures that cannot be built with cons , car, and cdr alone. This section shows how to use pairs to represent a data structure called a queue. Section 3.3.3  will show how to represent data structures called tables. A queue  is a sequence in which items are inserted at one end (called the rear of the queue) and deleted from the other end (the front). Figure 3.18 shows an initially empty queue in which the items a and b are inserted. Then a is removed, c and d are inserted, and b is removed. Because items are always removed in the order in which they are inserted, a que"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6531456u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ue is sometimes called a FIFO  (first in, first out) buf fer. Operation Resulting Queue (define q (make-queue)) (insert-queue! q 'a) a (insert-queue! q 'b) a b (delete-queue! q) b (insert-queue! q 'c) b c (insert-queue! q 'd) b c d (delete-queue! q) c dFigur e 3.18:   Queue operations. In terms of data abstraction, we can regard a queue as defined by the following set of operations: a constructor:   (make-queue)   returns an empty queue (a queue containing no items). two selectors:   (empty-queue? < queue>)  tests if the queue is empty .  (front-queue < queue>) returns the object at the front of the queue, signaling an error if the queue is empty; it does not modify the queue. two mutators:   (insert-queue! < queue> <item>)  inserts the item at the rear of the queue and returns the modified queue as its value.   (delete-queue! < queue>)  removes the item at the front of the queue and returns the modified queue as its value, signaling an error if the queue is empty before the deletion. Because a queue is a seq"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6532480u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "uence of items, we could certainly represent it as an ordinary list; the front of the queue would be the car of the list, inserting an item in the queue would amount to appending a new element at the end of the list, and deleting an item from the queue would just be taking the cdr of the list. However , this representation is inef ficient, because in order to insert an item we must scan the list until we reach the end. Since the only method we have for scanning a list is by successive cdr operations, this scanning requires \u03b8( n) steps for a list of n items. A simple modification to the list representation overcomes this disadvantage by allowing the queue operations to be implemented so that they require \u03b8(1) steps; that is, so that the number of steps needed is independent of the length of the queue. The dif ficulty with the list representation arises from the need to scan to find the end of the list. The reason we need to scan is that, although the standard way of representing a list as a chain of pairs read"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6533504i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ily provides us with a pointer to the beginning of the list, it gives us no easily accessible pointer to the end. The modification that avoids the drawback is to represent the queue as a list, together with an additional pointer that indicates the final pair in the list. That way , when we go to insert an item, we can consult the rear pointer and so avoid scanning the list. A queue is represented, then, as a pair of pointers, front-ptr  and rear- ptr, which indicate, respectively , the first and last pairs in an ordinary list. Since we would like the queue to be an identifiable object, we can use cons to combine the two pointers. Thus, the queue itself will be the cons  of the two pointers. Figure 3.19 illustrates this representation.Figur e 3.19:   Implementation of a queue as a list with front and rear pointers. To define the queue operations we use the following procedures, which enable us to select and to modify the front and rear pointers of a queue: (define (front-ptr queue) (car queue))   (define (rear"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6534528-
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "-ptr queue) (cdr queue))   (define (set-front-ptr! queue item) (set-car! queue item))   (define (set-rear-ptr! queue item) (set-cdr! queue item))   Now we can implement the actual queue operations. We will consider a queue to be empty if its front pointer is the empty list: (define (empty-queue? queue) (null? (front-ptr queue)))   The make-queue  constructor returns, as an initially empty queue, a pair whose car and cdr are both the empty list: (define (make-queue) (cons '() '()))   To select the item at the front of the queue, we return the car of the pair indicated by the front pointer: (define (front-queue queue)     (if (empty-queue? queue)         (error \"FRONT called with an empty queue\" queue)         (car (front-ptr queue))))   To insert an item in a queue, we follow the method whose result is indicated in figure 3.20. We first create a new pair whose car is the item to be inserted and whose cdr is the empty list. If the queue was initially empty ,we set the front and rear pointers of the queue to thi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6535552s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s new pair . Otherwise, we modify the final pair in the queue to point to the new pair , and also set the rear pointer to the new pair . Figur e 3.20:   Result of using (insert-queue! q 'd)  on the queue of figure 3.19. (define (insert-queue! queue item)     (let ((new-pair (cons item '())))       (cond ((empty-queue? queue)              (set-front-ptr! queue new-pair)              (set-rear-ptr! queue new-pair)              queue)             (else              (set-cdr! (rear-ptr queue) new-pair)              (set-rear-ptr! queue new-pair)              queue))))   To delete the item at the front of the queue, we merely modify the front pointer so that it now points at the second item in the queue, which can be found by following the cdr pointer of the first item (see figure 3.21):22 Figur e 3.21:   Result of using (delete-queue! q)  on the queue of figure 3.20.(define (delete-queue! queue)     (cond ((empty-queue? queue)            (error \"DELETE! called with an empty queue\" queue))           (else         "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6536576
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "   (set-front-ptr! queue (cdr (front-ptr queue)))            queue)))   Exer cise 3.21.   Ben Bitdiddle decides to test the queue implementation described above. He types in the procedures to the Lisp interpreter and proceeds to try them out: (define q1 (make-queue))   (insert-queue! q1 'a)   ((a) a)  (insert-queue! q1 'b)   ((a b) b)   (delete-queue! q1)   ((b) b)  (delete-queue! q1)   (() b)  \u201cIt's all wrong!\u201d he complains. \u201cThe interpreter's response shows that the last item is inserted into the queue twice. And when I delete both items, the second b is still there, so the queue isn't empty , even though it's supposed to be.\u201d Eva Lu Ator suggests that Ben has misunderstood what is happening. \u201cIt's not that the items are going into the queue twice,\u201d she explains. \u201cIt's just that the standard Lisp printer doesn't know how to make sense of the queue representation. If you want to see the queue printed correctly , you'll have to define your own print procedure for queues.\u201d Explain what Eva Lu is talking about."}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6537600
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " In particular , show why Ben's examples produce the printed results that they do. Define a procedure print-queue  that takes a queue as input and prints the sequence of items in the queue. Exer cise 3.22.   Instead of representing a queue as a pair of pointers, we can build a queue as a procedure with local state. The local state will consist of pointers to the beginning and the end of an ordinary list. Thus, the make- queue  procedure will have the form(define (make-queue)     (let ((front-ptr ...)          (rear-ptr ...))      <definitions of internal procedures >      (define (dispatch m) ...)      dispatch))   Complete the definition of make-queue  and provide implementations of the queue operations using this representation. Exer cise 3.23.   A deque  (\u201cdouble-ended queue\u201d) is a sequence in which items can be inserted and deleted at either the front or the rear . Operations on deques are the constructor make-deque , the predicate empty-deque? , selectors front-deque  and rear-deque , and mutators front-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6538624i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "insert- deque! , rear-insert-deque! , front-delete-deque! , and rear-delete- deque! . Show how to represent deques using pairs, and give implementations of the operations.23 All operations should be accomplished in \u03b8(1) steps. 3.3.3  Repr esenting T ables When we studied various ways of representing sets in chapter 2, we mentioned in section 2.3.3  the task of maintaining a table of records indexed by identifying keys. In the implementation of data-directed programming in section 2.4.3 , we made extensive use of two-dimensional tables, in which information is stored and retrieved using two keys. Here we see how to build tables as mutable list structures. We first consider a one-dimensional table, in which each value is stored under a single key . We implement the table as a list of records, each of which is implemented as a pair consisting of a key and the associated value. The records are glued together to form a list by pairs whose cars point to successive records. These gluing pairs are called the backbone"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6539648
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "  of the table. In order to have a place that we can change when we add a new record to the table, we build the table as a headed list . A headed list has a special backbone pair at the beginning, which holds a dummy \u201crecord\u201d \u2013 in thiscase the arbitrarily chosen symbol *table* . Figure 3.22 shows the box-and- pointer diagram for the table a:  1  b:  2  c:  3  Figur e 3.22:   A table represented as a headed list. To extract information from a table we use the lookup  procedure, which takes a key as ar gument and returns the associated value (or false if there is no value stored under that key). Lookup  is defined in terms of the assoc operation, which expects a key and a list of records as ar guments. Note that assoc  never sees the dummy record. Assoc  returns the record that has the given key as its car.24 Lookup  then checks to see that the resulting record returned by assoc  is not false, and returns the value (the cdr) of the record. (define (lookup key table)     (let ((record (assoc key (cdr table))))  "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6540672
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "     (if record           (cdr record)           false)))   (define (assoc key records)     (cond ((null? records) false)           ((equal? key (caar records)) (car records))           (else (assoc key (cdr records)))))   To insert a value in a table under a specified key , we first use assoc  to see if there is already a record in the table with this key . If not, we form a new record by cons ing the key with the value, and insert this at the head of thetable's list of records, after the dummy record. If there already is a record with this key , we set the cdr of this record to the designated new value. The header of the table provides us with a fixed location to modify in order to insert the new record.25 (define (insert! key value table)     (let ((record (assoc key (cdr table))))       (if record           (set-cdr! record value)           (set-cdr! table                     (cons (cons key value) (cdr table)))))     'ok)  To construct a new table, we simply create a list containing the symbol *table* : "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6541696(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "(define (make-table)     (list '*table*))   Two-dimensional tables In a two-dimensional table, each value is indexed by two keys. We can construct such a table as a one-dimensional table in which each key identifies a subtable. Figure 3.23 shows the box-and-pointer diagram for the table math:      +:  43       -:  45       *:  42   letters:       a:  97       b:  98   which has two subtables. (The subtables don't need a special header symbol, since the key that identifies the subtable serves this purpose.) Figur e 3.23:   A two-dimensional table.When we look up an item, we use the first key to identify the correct subtable. Then we use the second key to identify the record within the subtable. (define (lookup key-1 key-2 table)     (let ((subtable (assoc key-1 (cdr table))))       (if subtable           (let ((record (assoc key-2 (cdr subtable))))             (if record                 (cdr record)                 false))           false)))   To insert a new item under a pair of keys, we use assoc  to see if "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6542720t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "there is a subtable stored under the first key . If not, we build a new subtable containing the single record ( key-2 , value ) and insert it into the table under the first key . If a subtable already exists for the first key , we insert the new record into this subtable, using the insertion method for one-dimensional tables described above:(define (insert! key-1 key-2 value table)     (let ((subtable (assoc key-1 (cdr table))))       (if subtable           (let ((record (assoc key-2 (cdr subtable))))             (if record                 (set-cdr! record value)                 (set-cdr! subtable                           (cons (cons key-2 value)                                 (cdr subtable)))))           (set-cdr! table                     (cons (list key-1                                 (cons key-2 value))                           (cdr table)))))     'ok)  Creating local tables The lookup  and insert!  operations defined above take the table as an argument. This enables us to use programs that access mo"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6543744r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "re than one table. Another way to deal with multiple tables is to have separate lookup  and insert!  procedures for each table. We can do this by representing a table procedurally , as an object that maintains an internal table as part of its local state. When sent an appropriate message, this \u201ctable object\u201d supplies the procedure with which to operate on the internal table. Here is a generator for two-dimensional tables represented in this fashion: (define (make-table)     (let ((local-table (list '*table*)))       (define (lookup key-1 key-2)         (let ((subtable (assoc key-1 (cdr local-table))))           (if subtable               (let ((record (assoc key-2 (cdr subtable))))                 (if record                     (cdr record)                     false))               false)))       (define (insert! key-1 key-2 value)        (let ((subtable (assoc key-1 (cdr local-table))))           (if subtable               (let ((record (assoc key-2 (cdr subtable))))                 (if record               "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6544768
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "      (set-cdr! record value)                     (set-cdr! subtable                               (cons (cons key-2 value)                                     (cdr subtable)))))               (set-cdr! local-table                         (cons (list key-1                                     (cons key-2 value))                               (cdr local-table)))))         'ok)          (define (dispatch m)         (cond ((eq? m 'lookup-proc) lookup)               ((eq? m 'insert-proc!) insert!)               (else (error \"Unknown operation -- TABLE\" m))))       dispatch))   Using make-table , we could implement the get and put operations used in section 2.4.3  for data-directed programming, as follows: (define operation-table (make-table))   (define get (operation-table 'lookup-proc))   (define put (operation-table 'insert-proc!))   Get takes as ar guments two keys, and put takes as ar guments two keys and a value. Both operations access the same local table, which is encapsulated within the object created by t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6545792h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "he call to make-table . Exer cise 3.24.   In the table implementations above, the keys are tested for equality using equal?  (called by assoc ). This is not always the appropriate test. For instance, we might have a table with numeric keys in which we don't need an exact match to the number we're looking up, but only a number within some tolerance of it. Design a table constructor make-table that takes as an ar gument a same-key?  procedure that will be used to test \u201cequality\u201d of keys. Make-table  should return a dispatch  procedure thatcan be used to access appropriate lookup  and insert!  procedures for a local table. Exer cise 3.25.   Generalizing one- and two-dimensional tables, show how to implement a table in which values are stored under an arbitrary number of keys and dif ferent values may be stored under dif ferent numbers of keys. The lookup  and insert!  procedures should take as input a list of keys used to access the table. Exer cise 3.26.   To search a table as implemented above, one needs to sc"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6546816a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "an through the list of records. This is basically the unordered list representation of section 2.3.3 . For lar ge tables, it may be more ef ficient to structure the table in a dif ferent manner . Describe a table implementation where the (key , value) records are or ganized using a binary tree, assuming that keys can be ordered in some way (e.g., numerically or alphabetically). (Compare exercise 2.66 of chapter 2.) Exer cise 3.27.   Memoization  (also called tabulation ) is a technique that enables a procedure to record, in a local table, values that have previously been computed. This technique can make a vast dif ference in the performance of a program. A memoized procedure maintains a table in which values of previous calls are stored using as keys the ar guments that produced the values. When the memoized procedure is asked to compute a value, it first checks the table to see if the value is already there and, if so, just returns that value. Otherwise, it computes the new value in the ordinary way and sto"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6547840r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "res this in the table. As an example of memoization, recall from section 1.2.2  the exponential process for computing Fibonacci numbers: (define (fib n)     (cond ((= n 0) 0)           ((= n 1) 1)           (else (+ (fib (- n 1))                    (fib (- n 2))))))   The memoized version of the same procedure is (define memo-fib     (memoize (lambda (n)               (cond ((= n 0) 0)                      ((= n 1) 1)                      (else (+ (memo-fib (- n 1))                               (memo-fib (- n 2))))))))   where the memoizer is defined as (define (memoize f)     (let ((table (make-table)))       (lambda (x)         (let ((previously-computed-result (lookup x table)))           (or previously-computed-result               (let ((result (f x)))                 (insert! x result table)                 result))))))   Draw an environment diagram to analyze the computation of (memo-fib 3). Explain why memo-fib  computes the nth Fibonacci number in a number of steps proportional to n. Would the schem"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6548864e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e still work if we had simply defined memo-fib  to be (memoize fib) ? 3.3.4  A Simulator for Digital Cir cuits Designing complex digital systems, such as computers, is an important engineering activity . Digital systems are constructed by interconnecting simple elements. Although the behavior of these individual elements is simple, networks of them can have very complex behavior . Computer simulation of proposed circuit designs is an important tool used by digital systems engineers. In this section we design a system for performing digital logic simulations. This system typifies a kind of program called an event- driven simulation , in which actions (\u201cevents\u201d) trigger further events that happen at a later time, which in turn trigger more events, and so so. Our computational model of a circuit will be composed of objects that correspond to the elementary components from which the circuit is constructed. There are wires, which carry digital signals . A digital signal may at any moment have only one of two possi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6549888b
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ble values, 0 and 1. There are also various types of digital function boxes , which connect wirescarrying input signals to other output wires. Such boxes produce output signals computed from their input signals. The output signal is delayed by a time that depends on the type of the function box. For example, an inverter is a primitive function box that inverts its input. If the input signal to an inverter changes to 0, then one inverter -delay later the inverter will change its output signal to 1. If the input signal to an inverter changes to 1, then one inverter -delay later the inverter will change its output signal to 0. We draw an inverter symbolically as in figure 3.24. An and-gate , also shown in figure 3.24, is a primitive function box with two inputs and one output. It drives its output signal to a value that is the logical and  of the inputs. That is, if both of its input signals become 1, then one and-gate-delay time later the and-gate will force its output signal to be 1; otherwise the output will "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6550912b
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "be 0. An or-gate  is a similar two-input primitive function box that drives its output signal to a value that is the logical or  of the inputs. That is, the output will become 1 if at least one of the input signals is 1; otherwise the output will become 0. Figur e 3.24:   Primitive functions in the digital logic simulator . We can connect primitive functions together to construct more complex functions. To accomplish this we wire the outputs of some function boxes to the inputs of other function boxes. For example, the half-adder  circuit shown in figure 3.25 consists of an or -gate, two and-gates, and an inverter . It takes two input signals, A and B, and has two output signals, S and C. S will become 1 whenever precisely one of A and B is 1, and C will become 1 whenever A  and B are both 1. We can see from the figure that, because of the delays involved, the outputs may be generated at dif ferent times. Many of the dif ficulties in the design of digital circuits arise from this fact. Figur e 3.25:   A half-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6551936a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "adder circuit.We will now build a program for modeling the digital logic circuits we wish to study . The program will construct computational objects modeling the wires, which will \u201chold\u201d the signals. Function boxes will be modeled by procedures that enforce the correct relationships among the signals. One basic element of our simulation will be a procedure make-wire , which constructs wires. For example, we can construct six wires as follows: (define a (make-wire))   (define b (make-wire))   (define c (make-wire))     (define d (make-wire))   (define e (make-wire))   (define s (make-wire))   We attach a function box to a set of wires by calling a procedure that constructs that kind of box. The ar guments to the constructor procedure are the wires to be attached to the box. For example, given that we can construct and-gates, or -gates, and inverters, we can wire together the half- adder shown in figure 3.25: (or-gate a b d)   ok    (and-gate a b c)   ok    (inverter c e)   ok    (and-gate d e s)   ok  Better "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6552960y
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "yet, we can explicitly name this operation by defining a procedure half-adder  that constructs this circuit, given the four external wires to be attached to the half-adder:(define (half-adder a b s c)     (let ((d (make-wire)) (e (make-wire)))       (or-gate a b d)       (and-gate a b c)       (inverter c e)       (and-gate d e s)       'ok))   The advantage of making this definition is that we can use half-adder itself as a building block in creating more complex circuits. Figure 3.26, for example, shows a full-adder  composed of two half-adders and an or -gate.26 We can construct a full-adder as follows: (define (full-adder a b c-in sum c-out)     (let ((s (make-wire))           (c1 (make-wire))           (c2 (make-wire)))       (half-adder b c-in s c1)       (half-adder a s sum c2)       (or-gate c1 c2 c-out)       'ok))   Having defined full-adder  as a procedure, we can now use it as a building block for creating still more complex circuits. (For example, see exercise 3.30.) Figur e 3.26:   A full-adder "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6553984c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "circuit. In essence, our simulator provides us with the tools to construct a language of circuits. If we adopt the general perspective on languages with which we approached the study of Lisp in section 1.1, we can say that the primitive function boxes form the primitive elements of the language, that wiringboxes together provides a means of combination, and that specifying wiring patterns as procedures serves as a means of abstraction. Primitive function boxes The primitive function boxes implement the \u201cforces\u201d by which a change in the signal on one wire influences the signals on other wires. To build function boxes, we use the following operations on wires: (get-signal < wire>)  returns the current value of the signal on the wire. (set-signal! < wire> <new value >)  changes the value of the signal on the wire to the new value. (add-action! < wire> <procedure of no arguments >)  asserts that the designated procedure should be run whenever the signal on the wire changes value. Such procedures are the vehicles "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6555008b
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "by which changes in the signal value on the wire are communicated to other wires. In addition, we will make use of a procedure after-delay  that takes a time delay and a procedure to be run and executes the given procedure after the given delay . Using these procedures, we can define the primitive digital logic functions. To connect an input to an output through an inverter , we use add-action! to associate with the input wire a procedure that will be run whenever the signal on the input wire changes value. The procedure computes the logical-not  of the input signal, and then, after one inverter-delay , sets the output signal to be this new value: (define (inverter input output)     (define (invert-input)       (let ((new-value (logical-not (get-signal input))))         (after-delay inverter-delay                      (lambda ()                        (set-signal! output new-value)))))    (add-action! input invert-input)     'ok)  (define (logical-not s)     (cond ((= s 0) 1)           ((= s 1) 0)           ("}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6556032e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "else (error \"Invalid signal\" s))))   An and-gate is a little more complex. The action procedure must be run if either of the inputs to the gate changes. It computes the logical-and  (using a procedure analogous to logical-not ) of the values of the signals on the input wires and sets up a change to the new value to occur on the output wire after one and-gate-delay . (define (and-gate a1 a2 output)     (define (and-action-procedure)       (let ((new-value              (logical-and (get-signal a1) (get-signal a2))))         (after-delay and-gate-delay                      (lambda ()                        (set-signal! output new-value)))))     (add-action! a1 and-action-procedure)     (add-action! a2 and-action-procedure)     'ok)  Exer cise 3.28.   Define an or -gate as a primitive function box. Your or-gate constructor should be similar to and-gate . Exer cise 3.29.   Another way to construct an or -gate is as a compound digital logic device, built from and-gates and inverters. Define a procedure or-gate  tha"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6557056t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "t accomplishes this. What is the delay time of the or -gate in terms of and-gate-delay  and inverter-delay ? Exer cise 3.30.   Figure 3.27 shows a ripple-carry adder  formed by stringing together n full-adders. This is the simplest form of parallel adder for adding two n-bit binary numbers. The inputs A1, A2, A3, ..., An and B1, B2, B3, ..., Bn are the two binary numbers to be added (each Ak and Bk is a 0 or a 1). The circuit generates S1, S2, S3, ..., Sn, the n bits of the sum, and C, thecarry from the addition. Write a procedure ripple-carry-adder  that generates this circuit. The procedure should take as ar guments three lists of n wires each \u2013 the Ak, the Bk, and the Sk \u2013 and also another wire C. The major drawback of the ripple-carry adder is the need to wait for the carry signals to propagate. What is the delay needed to obtain the complete output from an n-bit ripple-carry adder , expressed in terms of the delays for and- gates, or -gates, and inverters? Figur e 3.27:   A ripple-carry adder for n-bit n"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6558080u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "umbers. Repr esenting wir es A wire in our simulation will be a computational object with two local state variables: a signal-value  (initially taken to be 0) and a collection of action-procedures  to be run when the signal changes value. We implement the wire, using message-passing style, as a collection of local procedures together with a dispatch  procedure that selects the appropriate local operation, just as we did with the simple bank-account object in section  3.1.1 : (define (make-wire)     (let ((signal-value 0) (action-procedures '()))       (define (set-my-signal! new-value)         (if (not (= signal-value new-value))             (begin (set! signal-value new-value)                    (call-each action-procedures))             'done))       (define (accept-action-procedure! proc)         (set! action-procedures (cons proc action-procedures))         (proc))      (define (dispatch m)         (cond ((eq? m 'get-signal) signal-value)               ((eq? m 'set-signal!) set-my-signal!)               ("}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6559104(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "(eq? m 'add-action!) accept-action-procedure!)               (else (error \"Unknown operation -- WIRE\" m))))       dispatch))   The local procedure set-my-signal!  tests whether the new signal value changes the signal on the wire. If so, it runs each of the action procedures, using the following procedure call-each , which calls each of the items in a list of no-ar gument procedures: (define (call-each procedures)     (if (null? procedures)         'done         (begin           ((car procedures))           (call-each (cdr procedures)))))   The local procedure accept-action-procedure!  adds the given procedure to the list of procedures to be run, and then runs the new procedure once. (See exercise 3.31.) With the local dispatch  procedure set up as specified, we can provide the following procedures to access the local operations on wires:27 (define (get-signal wire)     (wire 'get-signal))   (define (set-signal! wire new-value)     ((wire 'set-signal!) new-value))   (define (add-action! wire action-procedure) "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6560128
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "    ((wire 'add-action!) action-procedure))   Wires, which have time-varying signals and may be incrementally attached to devices, are typical of mutable objects. We have modeled them as procedures with local state variables that are modified by assignment. When a new wire is created, a new set of state variables is allocated (by the letexpression in make-wire ) and a new dispatch  procedure is constructed and returned, capturing the environment with the new state variables. The wires are shared among the various devices that have been connected to them. Thus, a change made by an interaction with one device will af fect all the other devices attached to the wire. The wire communicates the change to its neighbors by calling the action procedures provided to it when the connections were established. The agenda The only thing needed to complete the simulator is after-delay . The idea here is that we maintain a data structure, called an agenda , that contains a schedule of things to do. The following operations a"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6561152r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "re defined for agendas: (make-agenda)   returns a new empty agenda. (empty-agenda? < agenda>)  is true if the specified agenda is empty . (first-agenda-item < agenda>)  returns the first item on the agenda. (remove-first-agenda-item! < agenda>)  modifies the agenda by removing the first item. (add-to-agenda! < time> <action> <agenda>)  modifies the agenda by adding the given action procedure to be run at the specified time. (current-time < agenda>)  returns the current simulation time. The particular agenda that we use is denoted by the-agenda . The procedure after-delay  adds new elements to the-agenda :(define (after-delay delay action)     (add-to-agenda! (+ delay (current-time the-agenda))                     action                     the-agenda))   The simulation is driven by the procedure propagate , which operates on the-agenda , executing each procedure on the agenda in sequence. In general, as the simulation runs, new items will be added to the agenda, and propagate  will continue the simulation as "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6562176l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "long as there are items on the agenda: (define (propagate)     (if (empty-agenda? the-agenda)         'done         (let ((first-item (first-agenda-item the-agenda)))           (first-item)           (remove-first-agenda-item! the-agenda)           (propagate))))   A sample simulation The following procedure, which places a \u201cprobe\u201d on a wire, shows the simulator in action. The probe tells the wire that, whenever its signal changes value, it should print the new signal value, together with the current time and a name that identifies the wire: (define (probe name wire)     (add-action! wire                  (lambda ()                           (newline)                    (display name)                    (display \" \")                    (display (current-time the-agenda))                    (display \"  New-value = \")                    (display (get-signal wire)))))   We begin by initializing the agenda and specifying delays for the primitive function boxes:(define the-agenda (make-agenda))   (define inverter-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6563200d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "delay 2)   (define and-gate-delay 3)   (define or-gate-delay 5)   Now we define four wires, placing probes on two of them: (define input-1 (make-wire))   (define input-2 (make-wire))   (define sum (make-wire))   (define carry (make-wire))   (probe 'sum sum)   sum 0  New-value = 0   (probe 'carry carry)   carry 0  New-value = 0   Next we connect the wires in a half-adder circuit (as in figure 3.25), set the signal on input-1  to 1, and run the simulation: (half-adder input-1 input-2 sum carry)   ok  (set-signal! input-1 1)   done  (propagate)   sum 8  New-value = 1   done  The sum signal changes to 1 at time 8. We are now eight time units from the beginning of the simulation. At this point, we can set the signal on input-2 to 1 and allow the values to propagate: (set-signal! input-2 1)   done  (propagate)   carry 11  New-value = 1   sum 16  New-value = 0   done The carry  changes to 1 at time 1 1 and the sum changes to 0 at time 16. Exer cise 3.31.    The internal procedure accept-action-procedure! defined in "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6564224m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "make-wire  specifies that when a new action procedure is added to a wire, the procedure is immediately run. Explain why this initialization is necessary . In particular , trace through the half-adder example in the paragraphs above and say how the system's response would dif fer if we had defined accept-action-procedure!  as (define (accept-action-procedure! proc)     (set! action-procedures (cons proc action-procedures)))   Implementing the agenda Finally , we give details of the agenda data structure, which holds the procedures that are scheduled for future execution. The agenda is made up of time segments . Each time segment is a pair consisting of a number (the time) and a queue (see exercise 3.32) that holds the procedures that are scheduled to be run during that time segment. (define (make-time-segment time queue)     (cons time queue))   (define (segment-time s) (car s))   (define (segment-queue s) (cdr s))   We will operate on the time-segment queues using the queue operations described in section 3.3"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6565248.
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ".2 . The agenda itself is a one-dimensional table of time segments. It dif fers from the tables described in section 3.3.3  in that the segments will be sorted in order of increasing time. In addition, we store the current time  (i.e., the time of the last action that was processed) at the head of the agenda. A newly constructed agenda has no time segments and has a current time of 0:28 (define (make-agenda) (list 0))   (define (current-time agenda) (car agenda))  (define (set-current-time! agenda time)     (set-car! agenda time))   (define (segments agenda) (cdr agenda))   (define (set-segments! agenda segments)     (set-cdr! agenda segments))   (define (first-segment agenda) (car (segments agenda)))   (define (rest-segments agenda) (cdr (segments agenda)))   An agenda is empty if it has no time segments: (define (empty-agenda? agenda)     (null? (segments agenda)))   To add an action to an agenda, we first check if the agenda is empty . If so, we create a time segment for the action and install this in the "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6566272a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "agenda. Otherwise, we scan the agenda, examining the time of each segment. If we find a segment for our appointed time, we add the action to the associated queue. If we reach a time later than the one to which we are appointed, we insert a new time segment into the agenda just before it. If we reach the end of the agenda, we must create a new time segment at the end. (define (add-to-agenda! time action agenda)     (define (belongs-before? segments)       (or (null? segments)           (< time (segment-time (car segments)))))     (define (make-new-time-segment time action)       (let ((q (make-queue)))         (insert-queue! q action)         (make-time-segment time q)))     (define (add-to-segments! segments)       (if (= (segment-time (car segments)) time)           (insert-queue! (segment-queue (car segments))                          action)           (let ((rest (cdr segments)))             (if (belongs-before? rest)                 (set-cdr!                  segments                  (cons (make-new-time"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6567296-
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "-segment time action)                       (cdr segments)))                 (add-to-segments! rest)))))     (let ((segments (segments agenda)))       (if (belongs-before? segments)           (set-segments!            agenda            (cons (make-new-time-segment time action)                  segments))           (add-to-segments! segments))))   The procedure that removes the first item from the agenda deletes the item at the front of the queue in the first time segment. If this deletion makes the time segment empty , we remove it from the list of segments:29 (define (remove-first-agenda-item! agenda)     (let ((q (segment-queue (first-segment agenda))))       (delete-queue! q)       (if (empty-queue? q)           (set-segments! agenda (rest-segments agenda)))))   The first agenda item is found at the head of the queue in the first time segment. Whenever we extract an item, we also update the current time:30 (define (first-agenda-item agenda)     (if (empty-agenda? agenda)         (error \"Agenda is empty -- "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6568320F
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "FIRST-AGENDA-ITEM\")         (let ((first-seg (first-segment agenda)))           (set-current-time! agenda (segment-time first-seg))           (front-queue (segment-queue first-seg)))))   Exer cise 3.32.   The procedures to be run during each time segment of the agenda are kept in a queue. Thus, the procedures for each segment are called in the order in which they were added to the agenda (first in, first out). Explain why this order must be used. In particular , trace the behavior of an and-gate whose inputs change from 0,1 to 1,0 in the same segment and say how the behavior would dif fer if we stored a segment's procedures in an ordinary list, adding and removing procedures only at the front (last in, first out).3.3.5  Pr opagation of Constraints Computer programs are traditionally or ganized as one-directional computations, which perform operations on prespecified ar guments to produce desired outputs. On the other hand, we often model systems in terms of relations among quantities. For example, a mathemati"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6569344c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cal model of a mechanical structure might include the information that the deflection d of a metal rod is related to the force F on the rod, the length L of the rod, the cross-sectional area A, and the elastic modulus E via the equation Such an equation is not one-directional. Given any four of the quantities, we can use it to compute the fifth. Yet translating the equation into a traditional computer language would force us to choose one of the quantities to be computed in terms of the other four . Thus, a procedure for computing the area A could not be used to compute the deflection d, even though the computations of A and d arise from the same equation.31 In this section, we sketch the design of a language that enables us to work in terms of relations themselves. The primitive elements of the language are primitive constraints , which state that certain relations hold between quantities. For example, (adder a b c)  specifies that the quantities a, b, and c must be related by the equation a + b = c, (multip"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6570368l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "lier x y z) expresses the constraint xy = z, and (constant 3.14 x)  says that the value of x must be 3.14. Our language provides a means of combining primitive constraints in order to express more complex relations. We combine constraints by constructing constraint networks , in which constraints are joined by connectors . A connector is an object that \u201cholds\u201d a value that may participate in one or more constraints. For example, we know that the relationship between Fahrenheit and Celsius temperatures is Such a constraint can be thought of as a network consisting of primitive adder , multiplier , and constant constraints (figure 3.28). In the figure, wesee on the left a multiplier box with three terminals, labeled m1, m2, and p. These connect the multiplier to the rest of the network as follows: The m1 terminal is linked to a connector C, which will hold the Celsius temperature. The m2 terminal is linked to a connector w, which is also linked to a constant box that holds 9. The p terminal, which the multiplie"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6571392r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "r box constrains to be the product of m1 and m2, is linked to the p terminal of another multiplier box, whose m2 is connected to a constant 5 and whose m1 is connected to one of the terms in a sum. Figur e 3.28:   The relation 9 C = 5(F - 32) expressed as a constraint network. Computation by such a network proceeds as follows: When a connector is given a value (by the user or by a constraint box to which it is linked), it awakens all of its associated constraints (except for the constraint that just awakened it) to inform them that it has a value. Each awakened constraint box then polls its connectors to see if there is enough information to determine a value for a connector . If so, the box sets that connector , which then awakens all of its associated constraints, and so on. For instance, in conversion between Celsius and Fahrenheit, w, x, and y are immediately set by the constant boxes to 9, 5, and 32, respectively . The connectors awaken the multipliers and the adder , which determine that there is not en"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6572416o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ough information to proceed. If the user (or some other part of the network) sets C to a value (say 25), the leftmost multiplier will be awakened, and it will set u to 25 \u00b7 9 = 225. Then u awakens the second multiplier , which sets v to 45, and v awakens the adder , which sets F to 77. Using the constraint system To use the constraint system to carry out the temperature computation outlined above, we first create two connectors, C and F, by calling the constructor make-connector , and link C and F in an appropriate network:(define C (make-connector))   (define F (make-connector))   (celsius-fahrenheit-converter C F)   ok  The procedure that creates the network is defined as follows: (define (celsius-fahrenheit-converter c f)     (let ((u (make-connector))           (v (make-connector))           (w (make-connector))           (x (make-connector))           (y (make-connector)))       (multiplier c w u)       (multiplier v x u)       (adder v y f)       (constant 9 w)       (constant 5 x)       (constant 32 y)"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6573440
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "       'ok))   This procedure creates the internal connectors u, v, w, x, and y, and links them as shown in figure 3.28 using the primitive constraint constructors adder , multiplier , and constant . Just as with the digital-circuit simulator of section 3.3.4 , expressing these combinations of primitive elements in terms of procedures automatically provides our language with a means of abstraction for compound objects. To watch the network in action, we can place probes on the connectors C and F, using a probe  procedure similar to the one we used to monitor wires in section 3.3.4 . Placing a probe on a connector will cause a message to be printed whenever the connector is given a value: (probe \"Celsius temp\" C)   (probe \"Fahrenheit temp\" F)   Next we set the value of C to 25. (The third ar gument to set-value!  tells C that this directive comes from the user .)(set-value! C 25 'user)   Probe: Celsius temp = 25   Probe: Fahrenheit temp = 77   done  The probe on C awakens and reports the value. C also propagat"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6574464e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "es its value through the network as described above. This sets F to 77, which is reported by the probe on F. Now we can try to set F to a new value, say 212: (set-value! F 212 'user)   Error! Contradiction (77 212)   The connector complains that it has sensed a contradiction: Its value is 77, and someone is trying to set it to 212. If we really want to reuse the network with new values, we can tell C to for get its old value: (forget-value! C 'user)   Probe: Celsius temp = ?   Probe: Fahrenheit temp = ?   done  C finds that the user , who set its value originally , is now retracting that value, so C agrees to lose its value, as shown by the probe, and informs the rest of the network of this fact. This information eventually propagates to F, which now finds that it has no reason for continuing to believe that its own value is 77. Thus, F also gives up its value, as shown by the probe. Now that F has no value, we are free to set it to 212: (set-value! F 212 'user)   Probe: Fahrenheit temp = 212   Probe: Celsius"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6575488
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " temp = 100   done  This new value, when propagated through the network, forces C to have a value of 100, and this is registered by the probe on C. Notice that the verysame network is being used to compute C given F and to compute F given C. This nondirectionality of computation is the distinguishing feature of constraint-based systems. Implementing the constraint system The constraint system is implemented via procedural objects with local state, in a manner very similar to the digital-circuit simulator of section 3.3.4 . Although the primitive objects of the constraint system are somewhat more complex, the overall system is simpler , since there is no concern about agendas and logic delays. The basic operations on connectors are the following: (has-value? < connector >)  tells whether the connector has a value. (get-value < connector >)  returns the connector's current value. (set-value! < connector > <new-value > <informant >)  indicates that the informant is requesting the connector to set its value to th"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6576512e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e new value. (forget-value! < connector > <retractor >)  tells the connector that the retractor is requesting it to for get its value. (connect < connector > <new-constraint >)  tells the connector to participate in the new constraint. The connectors communicate with the constraints by means of the procedures inform-about-value , which tells the given constraint that the connector has a value, and inform-about-no-value , which tells the constraint that the connector has lost its value. Adder  constructs an adder constraint among summand connectors a1 and a2 and a sum connector . An adder is implemented as a procedure with local state (the procedure me below):(define (adder a1 a2 sum)     (define (process-new-value)       (cond ((and (has-value? a1) (has-value? a2))              (set-value! sum                          (+ (get-value a1) (get-value a2))                          me))             ((and (has-value? a1) (has-value? sum))              (set-value! a2                          (- (get-value sum) (get-v"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6577536a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "alue a1))                          me))             ((and (has-value? a2) (has-value? sum))              (set-value! a1                          (- (get-value sum) (get-value a2))                          me))))     (define (process-forget-value)       (forget-value! sum me)       (forget-value! a1 me)       (forget-value! a2 me)       (process-new-value))     (define (me request)       (cond ((eq? request 'I-have-a-value)               (process-new-value))             ((eq? request 'I-lost-my-value)              (process-forget-value))             (else              (error \"Unknown request -- ADDER\" request))))     (connect a1 me)     (connect a2 me)     (connect sum me)     me)  Adder  connects the new adder to the designated connectors and returns it as its value. The procedure me, which represents the adder , acts as a dispatch to the local procedures. The following \u201csyntax interfaces\u201d (see footnote 27 in section 3.3.4 ) are used in conjunction with the dispatch:(define (inform-about-value constraint)    "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6578560
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " (constraint 'I-have-a-value))   (define (inform-about-no-value constraint)     (constraint 'I-lost-my-value))   The adder's local procedure process-new-value  is called when the adder is informed that one of its connectors has a value. The adder first checks to see if both a1 and a2 have values. If so, it tells sum to set its value to the sum of the two addends. The informant  argument to set-value!  is me, which is the adder object itself. If a1 and a2 do not both have values, then the adder checks to see if perhaps a1 and sum have values. If so, it sets a2 to the dif ference of these two. Finally , if a2 and sum have values, this gives the adder enough information to set a1. If the adder is told that one of its connectors has lost a value, it requests that all of its connectors now lose their values. (Only those values that were set by this adder are actually lost.) Then it runs process-new-value . The reason for this last step is that one or more connectors may still have a value (that is, a connector may"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6579584
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " have had a value that was not originally set by the adder), and these values may need to be propagated back through the adder . A multiplier is very similar to an adder . It will set its product  to 0 if either of the factors is 0, even if the other factor is not known. (define (multiplier m1 m2 product)     (define (process-new-value)       (cond ((or (and (has-value? m1) (= (get-value m1) 0))                  (and (has-value? m2) (= (get-value m2) 0)))              (set-value! product 0 me))             ((and (has-value? m1) (has-value? m2))              (set-value! product                          (* (get-value m1) (get-value m2))                          me))             ((and (has-value? product) (has-value? m1))              (set-value! m2                          (/ (get-value product) (get-value m1))                          me))             ((and (has-value? product) (has-value? m2))             (set-value! m1                          (/ (get-value product) (get-value m2))                          m"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6580608e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e))))     (define (process-forget-value)       (forget-value! product me)       (forget-value! m1 me)       (forget-value! m2 me)       (process-new-value))     (define (me request)       (cond ((eq? request 'I-have-a-value)              (process-new-value))             ((eq? request 'I-lost-my-value)              (process-forget-value))             (else              (error \"Unknown request -- MULTIPLIER\" request))))     (connect m1 me)     (connect m2 me)     (connect product me)     me)  A constant  constructor simply sets the value of the designated connector . Any I-have-a-value  or I-lost-my-value  message sent to the constant box will produce an error . (define (constant value connector)     (define (me request)       (error \"Unknown request -- CONSTANT\" request))     (connect connector me)     (set-value! connector value me)     me)  Finally , a probe prints a message about the setting or unsetting of the designated connector: (define (probe name connector)     (define (print-probe value)       (newli"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6581632n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ne)       (display \"Probe: \")      (display name)       (display \" = \")       (display value))     (define (process-new-value)       (print-probe (get-value connector)))     (define (process-forget-value)       (print-probe \"?\"))     (define (me request)       (cond ((eq? request 'I-have-a-value)              (process-new-value))             ((eq? request 'I-lost-my-value)              (process-forget-value))             (else              (error \"Unknown request -- PROBE\" request))))     (connect connector me)     me)  Repr esenting connectors A connector is represented as a procedural object with local state variables value , the current value of the connector; informant , the object that set the connector's value; and constraints , a list of the constraints in which the connector participates. (define (make-connector)     (let ((value false) (informant false) (constraints '()))       (define (set-my-value newval setter)         (cond ((not (has-value? me))                (set! value newval)                "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6582656(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "(set! informant setter)                (for-each-except setter                                 inform-about-value                                 constraints))               ((not (= value newval))                (error \"Contradiction\" (list value newval)))               (else 'ignored)))       (define (forget-my-value retractor)        (if (eq? retractor informant)             (begin (set! informant false)                    (for-each-except retractor                                     inform-about-no-value                                     constraints))             'ignored))       (define (connect new-constraint)         (if (not (memq new-constraint constraints))             (set! constraints                   (cons new-constraint constraints)))         (if (has-value? me)             (inform-about-value new-constraint))         'done)       (define (me request)         (cond ((eq? request 'has-value?)                (if informant true false))               ((eq? request 'value) value)               (("}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6583680e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eq? request 'set-value!) set-my-value)               ((eq? request 'forget) forget-my-value)               ((eq? request 'connect) connect)               (else (error \"Unknown operation -- CONNECTOR\"                            request))))       me))   The connector's local procedure set-my-value  is called when there is a request to set the connector's value. If the connector does not currently have a value, it will set its value and remember as informant  the constraint that requested the value to be set.32 Then the connector will notify all of its participating constraints except the constraint that requested the value to be set. This is accomplished using the following iterator , which applies a designated procedure to all items in a list except a given one: (define (for-each-except exception procedure list)     (define (loop items)       (cond ((null? items) 'done)             ((eq? (car items) exception) (loop (cdr items)))             (else (procedure (car items))                  (loop (cdr items))))) "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6584704
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "    (loop list))   If a connector is asked to for get its value, it runs the local procedure forget-my-value , which first checks to make sure that the request is coming from the same object that set the value originally . If so, the connector informs its associated constraints about the loss of the value. The local procedure connect  adds the designated new constraint to the list of constraints if it is not already in that list. Then, if the connector has a value, it informs the new constraint of this fact. The connector's procedure me serves as a dispatch to the other internal procedures and also represents the connector as an object. The following procedures provide a syntax interface for the dispatch: (define (has-value? connector)     (connector 'has-value?))   (define (get-value connector)     (connector 'value))   (define (set-value! connector new-value informant)     ((connector 'set-value!) new-value informant))   (define (forget-value! connector retractor)     ((connector 'forget) retractor))   (def"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6585728i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ine (connect connector new-constraint)     ((connector 'connect) new-constraint))   Exer cise 3.33.   Using primitive multiplier , adder , and constant constraints, define a procedure averager  that takes three connectors a, b, and c as inputs and establishes the constraint that the value of c is the average of the values of a and b. Exer cise 3.34.   Louis Reasoner wants to build a squarer , a constraint device with two terminals such that the value of connector b on the second terminal will always be the square of the value a on the first terminal. He proposes the following simple device made from a multiplier:(define (squarer a b)     (multiplier a a b))   There is a serious flaw in this idea. Explain. Exer cise 3.35.   Ben Bitdiddle tells Louis that one way to avoid the trouble in exercise 3.34 is to define a squarer as a new primitive constraint. Fill in the missing portions in Ben's outline for a procedure to implement such a constraint: (define (squarer a b)     (define (process-new-value)       (if (h"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6586752a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "as-value? b)           (if (< (get-value b) 0)               (error \"square less than 0 -- SQUARER\" (get- value b))               < alternative1 >)          < alternative2 >))    (define (process-forget-value) < body1>)    (define (me request) < body2>)    <rest of definition >    me)  Exer cise 3.36.   Suppose we evaluate the following sequence of expressions in the global environment: (define a (make-connector))   (define b (make-connector))   (set-value! a 10 'user)   At some time during evaluation of the set-value! , the following expression from the connector's local procedure is evaluated: (for-each-except setter inform-about-value constraints)   Draw an environment diagram showing the environment in which the above expression is evaluated.Exer cise 3.37.   The celsius-fahrenheit-converter  procedure is cumbersome when compared with a more expression-oriented style of definition, such as (define (celsius-fahrenheit-converter x)     (c+ (c* (c/ (cv 9) (cv 5))             x)         (cv 32)))   (define C "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6587776(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "(make-connector))   (define F (celsius-fahrenheit-converter C))   Here c+, c*, etc. are the \u201cconstraint\u201d versions of the arithmetic operations. For example, c+ takes two connectors as ar guments and returns a connector that is related to these by an adder constraint: (define (c+ x y)     (let ((z (make-connector)))       (adder x y z)       z))  Define analogous procedures c-, c*, c/, and cv (constant value) that enable us to define compound constraints as in the converter example above.33 16 Set-car!  and set-cdr!  return implementation-dependent values. Like set! , they should be used only for their ef fect. 17 We see from this that mutation operations on lists can create \u201cgarbage\u201d that is not part of any accessible structure. We will see in section 5.3.2  that Lisp memory-management systems include a garbage collector , which identifies and recycles the memory space used by unneeded pairs. 18 Get-new-pair  is one of the operations that must be implemented as part of the memory management required by a Lisp"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6588800
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " implementation. We will discuss this in section 5.3.1 . 19 The two pairs are distinct because each call to cons  returns a new pair . The symbols are shared; in Scheme there is a unique symbol with any given name. Since Scheme provides no way to mutate a symbol, this sharing is undetectable. Note also that the sharing is what enables us to compare symbols using eq?, which simply checks equality of pointers. 20 The subtleties of dealing with sharing of mutable data objects reflect the underlying issues of \u201csameness\u201d and \u201cchange\u201d that were raised in section 3.1.3 . We mentioned there that admitting change to our language requires that a compound object must have an \u201cidentity\u201d that is something dif ferentfrom the pieces from which it is composed. In Lisp, we consider this \u201cidentity\u201d to be the quality that is tested by eq?, i.e., by equality of pointers. Since in most Lisp implementations a pointer is essentially a memory address, we are \u201csolving the problem\u201d of defining the identity of objects by stipulating th"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6589824a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "at a data object \u201citself\u201d is the information stored in some particular set of memory locations in the computer . This suf fices for simple Lisp programs, but is hardly a general way to resolve the issue of \u201csameness\u201d in computational models. 21 On the other hand, from the viewpoint of implementation, assignment requires us to modify the environment, which is itself a mutable data structure. Thus, assignment and mutation are equipotent: Each can be implemented in terms of the other . 22 If the first item is the final item in the queue, the front pointer will be the empty list after the deletion, which will mark the queue as empty; we needn't worry about updating the rear pointer , which will still point to the deleted item, because empty-queue?  looks only at the front pointer . 23 Be careful not to make the interpreter try to print a structure that contains cycles. (See exercise 3.13.) 24 Because assoc  uses equal? , it can recognize keys that are symbols, numbers, or list structure. 25 Thus, the first backbo"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6590848n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ne pair is the object that represents the table \u201citself\u201d; that is, a pointer to the table is a pointer to this pair . This same backbone pair always starts the table. If we did not arrange things in this way , insert!  would have to return a new value for the start of the table when it added a new record. 26 A full-adder is a basic circuit element used in adding two binary numbers. Here A and B are the bits at corresponding positions in the two numbers to be added, and Cin is the carry bit from the addition one place to the right. The circuit generates SUM, which is the sum bit in the corresponding position, and Cout, which is the carry bit to be propagated to the left. 27 These procedures are simply syntactic sugar that allow us to use ordinary procedural syntax to access the local procedures of objects. It is striking that we can interchange the role of \u201cprocedures\u201d and \u201cdata\u201d in such a simple way . For example, if we write (wire 'get-signal)  we think of wire  as a procedure that is called with the message"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6591872
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " get-signal  as input. Alternatively , writing (get-signal wire)  encourages us to think of wire  as a data object that is the input to a procedure get-signal . The truth of the matter is that, in a language in which we can deal with procedures as objects, there is no fundamental dif ference between \u201cprocedures\u201d and \u201cdata,\u201d and we can choose our syntactic sugar to allow us to program in whatever style we choose. 28 The agenda is a headed list, like the tables in section 3.3.3 , but since the list is headed by the time, we do not need an additional dummy header (such as the *table*  symbol used with tables). 29 Observe that the if expression in this procedure has no < alternative > expression. Such a \u201cone- armed if statement\u201d is used to decide whether to do something, rather than to select between two expressions. An if expression returns an unspecified value if the predicate is false and there is no <alternative >. 30 In this way , the current time will always be the time of the action most recently processed"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6592896.
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ". Storing this time at the head of the agenda ensures that it will still be available even if the associated timesegment has been deleted. 31 Constraint propagation first appeared in the incredibly forward-looking SKETCHP AD system of Ivan Sutherland (1963). A beautiful constraint-propagation system based on the Smalltalk language was developed by Alan Borning (1977) at Xerox Palo Alto Research Center . Sussman, Stallman, and Steele applied constraint propagation to electrical circuit analysis (Sussman and Stallman 1975; Sussman and Steele 1980). TK!Solver (Konopasek and Jayaraman 1984) is an extensive modeling environment based on constraints. 32 The setter  might not be a constraint. In our temperature example, we used user  as the setter . 33 The expression-oriented format is convenient because it avoids the need to name the intermediate expressions in a computation. Our original formulation of the constraint language is cumbersome in the same way that many languages are cumbersome when dealing with operat"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6593920i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ions on compound data. For example, if we wanted to compute the product ( a + b) \u00b7 (c + d), where the variables represent vectors, we could work in \u201cimperative style,\u201d using procedures that set the values of designated vector ar guments but do not themselves return vectors as values: (v-sum a b temp1)   (v-sum c d temp2)   (v-prod temp1 temp2 answer)   Alternatively , we could deal with expressions, using procedures that return vectors as values, and thus avoid explicitly mentioning temp1  and temp2 : (define answer (v-prod (v-sum a b) (v-sum c d)))   Since Lisp allows us to return compound objects as values of procedures, we can transform our imperative-style constraint language into an expression-oriented style as shown in this exercise. In languages that are impoverished in handling compound objects, such as Algol, Basic, and Pascal (unless one explicitly uses Pascal pointer variables), one is usually stuck with the imperative style when manipulating compound objects. Given the advantage of the expression-"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6594944o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "oriented format, one might ask if there is any reason to have implemented the system in imperative style, as we did in this section. One reason is that the non-expression-oriented constraint language provides a handle on constraint objects (e.g., the value of the adder  procedure) as well as on connector objects. This is useful if we wish to extend the system with new operations that communicate with constraints directly rather than only indirectly via operations on connectors. Although it is easy to implement the expression-oriented style in terms of the imperative implementation, it is very dif ficult to do the converse.3.4  Concurrency: Time Is of the Essence We've seen the power of computational objects with local state as tools for modeling. Yet, as section 3.1.3  warned, this power extracts a price: the loss of referential transparency , giving rise to a thicket of questions about sameness and change, and the need to abandon the substitution model of evaluation in favor of the more intricate environment"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6595968
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " model. The central issue lurking beneath the complexity of state, sameness, and change is that by introducing assignment we are forced to admit time into our computational models. Before we introduced assignment, all our programs were timeless, in the sense that any expression that has a value always has the same value. In contrast, recall the example of modeling withdrawals from a bank account and returning the resulting balance, introduced at the beginning of section 3.1.1 : (withdraw 25)   75  (withdraw 25)   50  Here successive evaluations of the same expression yield dif ferent values. This behavior arises from the fact that the execution of assignment statements (in this case, assignments to the variable balance ) delineates moments in time  when values change. The result of evaluating an expression depends not only on the expression itself, but also on whether the evaluation occurs before or after these moments. Building models in terms of computational objects with local state forces us to confront t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6596992i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ime as an essential concept in programming. We can go further in structuring computational models to match our perception of the physical world. Objects in the world do not change one at a time in sequence. Rather we perceive them as acting concurr ently  \u2013 all at once. So it is often natural to model systems as collections of computational processes that execute concurrently . Just as we can make our programs modular by or ganizing models in terms of objects with separate local state,it is often appropriate to divide computational models into parts that evolve separately and concurrently . Even if the programs are to be executed on a sequential computer , the practice of writing programs as if they were to be executed concurrently forces the programmer to avoid inessential timing constraints and thus makes programs more modular . In addition to making programs more modular , concurrent computation can provide a speed advantage over sequential computation. Sequential computers execute only one operation at a "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6598016t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "time, so the amount of time it takes to perform a task is proportional to the total number of operations performed.34 However , if it is possible to decompose a problem into pieces that are relatively independent and need to communicate only rarely , it may be possible to allocate pieces to separate computing processors, producing a speed advantage proportional to the number of processors available. Unfortunately , the complexities introduced by assignment become even more problematic in the presence of concurrency . The fact of concurrent execution, either because the world operates in parallel or because our computers do, entails additional complexity in our understanding of time. 3.4.1  The Natur e of T ime in Concurr ent Systems On the surface, time seems straightforward. It is an ordering imposed on events.35 For any events A and B, either A occurs before B, A and B are simultaneous, or A occurs after B. For instance, returning to the bank account example, suppose that Peter withdraws $10 and Paul withdr"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6599040a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "aws $25 from a joint account that initially contains $100, leaving $65 in the account. Depending on the order of the two withdrawals, the sequence of balances in the account is either $100 \u27f6  $90 \u27f6  $65 or $100 \u27f6  $75 \u27f6 $65. In a computer implementation of the banking system, this changing sequence of balances could be modeled by successive assignments to a variable balance . In complex situations, however , such a view can be problematic. Suppose that Peter and Paul, and other people besides, are accessing the same bank account through a network of banking machines distributed all over the world. The actual sequence of balances in the account will depend criticallyon the detailed timing of the accesses and the details of the communication among the machines. This indeterminacy in the order of events can pose serious problems in the design of concurrent systems. For instance, suppose that the withdrawals made by Peter and Paul are implemented as two separate processes sharing a common variable balance , each "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6600064p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "process specified by the procedure given in section 3.1.1 : (define (withdraw amount)     (if (>= balance amount)         (begin (set! balance (- balance amount))                balance)         \"Insufficient funds\"))   If the two processes operate independently , then Peter might test the balance and attempt to withdraw a legitimate amount. However , Paul might withdraw some funds in between the time that Peter checks the balance and the time Peter completes the withdrawal, thus invalidating Peter's test. Things can be worse still. Consider the expression (set! balance (- balance amount))   executed as part of each withdrawal process. This consists of three steps: (1) accessing the value of the balance  variable; (2) computing the new balance; (3) setting balance  to this new value. If Peter and Paul's withdrawals execute this statement concurrently , then the two withdrawals might interleave the order in which they access balance  and set it to the new value. The timing diagram in figure 3.29 depicts an ord"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6601088e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "er of events where balance starts at 100, Peter withdraws 10, Paul withdraws 25, and yet the final value of balance  is 75. As shown in the diagram, the reason for this anomaly is that Paul's assignment of 75 to balance  is made under the assumption that the value of balance  to be decremented is 100. That assumption, however , became invalid when Peter changed balance  to 90. This is a catastrophic failure for the banking system, because the total amount of money in thesystem is not conserved. Before the transactions, the total amount of money was $100. Afterwards, Peter has $10, Paul has $25, and the bank has $75.36 The general phenomenon illustrated here is that several processes may share a common state variable. What makes this complicated is that more than one process may be trying to manipulate the shared state at the same time. For the bank account example, during each transaction, each customer should be able to act as if the other customers did not exist. When a customer changes the balance in a way"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6602112
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " that depends on the balance, he must be able to assume that, just before the moment of change, the balance is still what he thought it was. Corr ect behavior of concurr ent pr ograms The above example typifies the subtle bugs that can creep into concurrent programs. The root of this complexity lies in the assignments to variables that are shared among the dif ferent processes. We already know that we must be careful in writing programs that use set! , because the results of a computation depend on the order in which the assignments occur .37 With concurrent processes we must be especially careful about assignments, because we may not be able to control the order of the assignments made by the dif ferent processes. If several such changes might be made concurrently (as with two depositors accessing a joint account) we need some way to ensure that our system behaves correctly . For example, in the case of withdrawals from a joint bank account, we must ensure that money is conserved. To make concurrent programs"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6603136
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " behave correctly , we may have to place some restrictions on concurrent execution. Figur e 3.29:   Timing diagram showing how interleaving the order of events in two banking withdrawals can lead to an incorrect final balance.One possible restriction on concurrency would stipulate that no two operations that change any shared state variables can occur at the same time. This is an extremely stringent requirement. For distributed banking, it would require the system designer to ensure that only one transaction could proceed at a time. This would be both inef ficient and overly conservative. Figure 3.30 shows Peter and Paul sharing a bank account, where Paul has a private account as well. The diagram illustrates two withdrawals from the shared account (one by Peter and one by Paul) and a deposit to Paul's private account.38 The two withdrawals from the shared account must not be concurrent (since both access and update the same account), and Paul's deposit and withdrawal must not be concurrent (since both access"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6604160
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " and update the amount in Paul's wallet). But there should be no problem permitting Paul's deposit to his private account to proceed concurrently with Peter's withdrawal from the shared account. Figur e 3.30:   Concurrent deposits and withdrawals from a joint account in Bank1 and a private account in Bank2.A less stringent restriction on concurrency would ensure that a concurrent system produces the same result as if the processes had run sequentially in some order . There are two important aspects to this requirement. First, it does not require the processes to actually run sequentially , but only to produce results that are the same as if they had run sequentially . For the example in figure 3.30, the designer of the bank account system can safely allow Paul's deposit and Peter's withdrawal to happen concurrently , because the net result will be the same as if the two operations had happened sequentially . Second, there may be more than one possible \u201ccorrect\u201d result produced by a concurrent program, because"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6605184
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " we require only that the result be the same as for some  sequential order . For example, suppose that Peter and Paul's joint account starts out with $100, and Peter deposits $40 while Paul concurrently withdraws half the money in the account. Then sequential execution could result in the account balance being either $70 or $90 (see exercise 3.38).39 There are still weaker requirements for correct execution of concurrent programs. A program for simulating diffusion (say , the flow of heat in an object) might consist of a lar ge number of processes, each one representing a small volume of space, that update their values concurrently . Each process repeatedly changes its value to the average of its own value and its neighbors' values. This algorithm conver ges to the right answer independentof the order in which the operations are done; there is no need for any restrictions on concurrent use of the shared values. Exer cise 3.38.   Suppose that Peter , Paul, and Mary share a joint bank account that initially con"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6606208t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tains $100. Concurrently , Peter deposits $10, Paul withdraws $20, and Mary withdraws half the money in the account, by executing the following commands: Peter:(set! balance (+ balance 10)) Paul:(set! balance (- balance 20)) Mary:(set! balance (- balance (/ balance 2))) a. List all the dif ferent possible values for balance  after these three transactions have been completed, assuming that the banking system forces the three processes to run sequentially in some order . b. What are some other values that could be produced if the system allows the processes to be interleaved? Draw timing diagrams like the one in figure 3.29 to explain how these values can occur . 3.4.2  Mechanisms for Contr olling Concurr ency We've seen that the dif ficulty in dealing with concurrent processes is rooted in the need to consider the interleaving of the order of events in the dif ferent processes. For example, suppose we have two processes, one with three ordered events ( a,b,c) and one with three ordered events ( x,y,z). If the"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6607232
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " two processes run concurrently , with no constraints on how their execution is interleaved, then there are 20 dif ferent possible orderings for the events that are consistent with the individual orderings for the two processes: As programmers designing this system, we would have to consider the effects of each of these 20 orderings and check that each behavior isacceptable. Such an approach rapidly becomes unwieldy as the numbers of processes and events increase. A more practical approach to the design of concurrent systems is to devise general mechanisms that allow us to constrain the interleaving of concurrent processes so that we can be sure that the program behavior is correct. Many mechanisms have been developed for this purpose. In this section, we describe one of them, the serializer . Serializing access to shar ed state Serialization implements the following idea: Processes will execute concurrently , but there will be certain collections of procedures that cannot be executed concurrently . More prec"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6608256i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "isely , serialization creates distinguished sets of procedures such that only one execution of a procedure in each serialized set is permitted to happen at a time. If some procedure in the set is being executed, then a process that attempts to execute any procedure in the set will be forced to wait until the first execution has finished. We can use serialization to control access to shared variables. For example, if we want to update a shared variable based on the previous value of that variable, we put the access to the previous value of the variable and the assignment of the new value to the variable in the same procedure. We then ensure that no other procedure that assigns to the variable can run concurrently with this procedure by serializing all of these procedures with the same serializer . This guarantees that the value of the variable cannot be changed between an access and the corresponding assignment. Serializers in Scheme To make the above mechanism more concrete, suppose that we have extended Sche"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6609280m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "me to include a procedure called parallel-execute : (parallel-execute < p1> <p2> ... <pk>)  Each < p> must be a procedure of no ar guments. Parallel-execute  creates a separate process for each < p>, which applies < p> (to no ar guments).These processes all run concurrently .40 As an example of how this is used, consider (define x 10)     (parallel-execute (lambda () (set! x (* x x)))                     (lambda () (set! x (+ x 1))))   This creates two concurrent processes \u2013 P1, which sets x to x times x, and P2, which increments x. After execution is complete, x will be left with one of five possible values, depending on the interleaving of the events of P1 and P2: 101: P1 sets x to 100 and then P2 increments x to 101. 121: P2 increments x to 11 and then P1 sets x to x times x. 110:P2 changes x from 10 to 1 1 between the two times that P1 accesses the value of x during the evaluation of (* x x) . 11:P2 accesses x, then P1 sets x to 100, then P2 sets x. 100: P1 accesses x (twice), then P2 sets x to 11, then P"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch66103041
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "1 sets x. We can constrain the concurrency by using serialized procedures, which are created by serializers . Serializers are constructed by make-serializer , whose implementation is given below . A serializer takes a procedure as argument and returns a serialized procedure that behaves like the original procedure. All calls to a given serializer return serialized procedures in the same set. Thus, in contrast to the example above, executing (define x 10)     (define s (make-serializer))    (parallel-execute (s (lambda () (set! x (* x x))))                     (s (lambda () (set! x (+ x 1)))))   can produce only two possible values for x, 101 or 121. The other possibilities are eliminated, because the execution of P1 and P2 cannot be interleaved. Here is a version of the make-account  procedure from section 3.1.1 , where the deposits and withdrawals have been serialized: (define (make-account balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6611328
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "                  balance)           \"Insufficient funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     (let ((protected (make-serializer)))       (define (dispatch m)         (cond ((eq? m 'withdraw) (protected withdraw))               ((eq? m 'deposit) (protected deposit))               ((eq? m 'balance) balance)               (else (error \"Unknown request -- MAKE-ACCOUNT\"                            m))))       dispatch))   With this implementation, two processes cannot be withdrawing from or depositing into a single account concurrently . This eliminates the source of the error illustrated in figure 3.29, where Peter changes the account balance between the times when Paul accesses the balance to compute the new value and when Paul actually performs the assignment. On the other hand, each account has its own serializer , so that deposits and withdrawals for different accounts can proceed concurrently . Exer cise 3.39.   Which of the five possibilities in the paral"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6612352l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "lel execution shown above remain if we instead serialize execution as follows:(define x 10)     (define s (make-serializer))     (parallel- execute (lambda () (set! x ((s (lambda () (* x x))))))                     (s (lambda () (set! x (+ x 1)))))   Exer cise 3.40.   Give all possible values of x that can result from executing (define x 10)     (parallel-execute (lambda () (set! x (* x x)))                     (lambda () (set! x (* x x x))))   Which of these possibilities remain if we instead use serialized procedures: (define x 10)     (define s (make-serializer))     (parallel-execute (s (lambda () (set! x (* x x))))                     (s (lambda () (set! x (* x x x)))))   Exer cise 3.41.   Ben Bitdiddle worries that it would be better to implement the bank account as follows (where the commented line has been changed): (define (make-account balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))                  balance)           \"Insuffici"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6613376e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ent funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     ;; continued on next page      (let ((protected (make-serializer)))       (define (dispatch m)         (cond ((eq? m 'withdraw) (protected withdraw))               ((eq? m 'deposit) (protected deposit))               ((eq? m 'balance)                ((protected (lambda () balance)))) ; serialized               (else (error \"Unknown request -- MAKE-ACCOUNT\"                            m))))       dispatch))   because allowing unserialized access to the bank balance can result in anomalous behavior . Do you agree? Is there any scenario that demonstrates Ben's concern? Exer cise 3.42.   Ben Bitdiddle suggests that it's a waste of time to create a new serialized procedure in response to every withdraw  and deposit message. He says that make-account  could be changed so that the calls to protected  are done outside the dispatch  procedure. That is, an account would return the same serialized procedure (which was cre"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6614400a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ated at the same time as the account) each time it is asked for a withdrawal procedure. (define (make-account balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))                  balance)           \"Insufficient funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     (let ((protected (make-serializer)))       (let ((protected-withdraw (protected withdraw))             (protected-deposit (protected deposit)))         (define (dispatch m)           (cond ((eq? m 'withdraw) protected-withdraw)                 ((eq? m 'deposit) protected-deposit)                 ((eq? m 'balance) balance)                (else (error \"Unknown request -- MAKE-ACCOUNT\"                              m))))         dispatch)))   Is this a safe change to make? In particular , is there any dif ference in what concurrency is allowed by these two versions of make-account  ? Complexity of using multiple shar ed resour ces Serializers "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6615424p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "provide a powerful abstraction that helps isolate the complexities of concurrent programs so that they can be dealt with carefully and (hopefully) correctly . However , while using serializers is relatively straightforward when there is only a single shared resource (such as a single bank account), concurrent programming can be treacherously dif ficult when there are multiple shared resources. To illustrate one of the dif ficulties that can arise, suppose we wish to swap the balances in two bank accounts. We access each account to find the balance, compute the dif ference between the balances, withdraw this difference from one account, and deposit it in the other account. We could implement this as follows:41 (define (exchange account1 account2)     (let ((difference (- (account1 'balance)                          (account2 'balance))))       ((account1 'withdraw) difference)       ((account2 'deposit) difference)))   This procedure works well when only a single process is trying to do the exchange. Suppose, "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6616448h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "however , that Peter and Paul both have access to accounts a1, a2, and a3, and that Peter exchanges a1 and a2 while Paul concurrently exchanges a1 and a3. Even with account deposits and withdrawals serialized for individual accounts (as in the make-account procedure shown above in this section), exchange  can still produce incorrect results. For example, Peter might compute the dif ference in the balances for a1 and a2, but then Paul might change the balance in a1 before Peter is able to complete the exchange.42 For correct behavior , we mustarrange for the exchange  procedure to lock out any other concurrent accesses to the accounts during the entire time of the exchange. One way we can accomplish this is by using both accounts' serializers to serialize the entire exchange  procedure. To do this, we will arrange for access to an account's serializer . Note that we are deliberately breaking the modularity of the bank-account object by exposing the serializer . The following version of make-account  is identic"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6617472a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "al to the original version given in section 3.1.1 , except that a serializer is provided to protect the balance variable, and the serializer is exported via message passing: (define (make-account-and-serializer balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))                  balance)           \"Insufficient funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     (let ((balance-serializer (make-serializer)))       (define (dispatch m)         (cond ((eq? m 'withdraw) withdraw)               ((eq? m 'deposit) deposit)               ((eq? m 'balance) balance)               ((eq? m 'serializer) balance-serializer)               (else (error \"Unknown request -- MAKE-ACCOUNT\"                            m))))       dispatch))   We can use this to do serialized deposits and withdrawals. However , unlike our earlier serialized account, it is now the responsibility of each user of bank-account objects to exp"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6618496l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "licitly manage the serialization, for example as follows:43 (define (deposit account amount)     (let ((s (account 'serializer))          (d (account 'deposit)))       ((s d) amount)))   Exporting the serializer in this way gives us enough flexibility to implement a serialized exchange program. We simply serialize the original exchange procedure with the serializers for both accounts: (define (serialized-exchange account1 account2)     (let ((serializer1 (account1 'serializer))           (serializer2 (account2 'serializer)))       ((serializer1 (serializer2 exchange))        account1        account2)))   Exer cise 3.43.   Suppose that the balances in three accounts start out as $10, $20, and $30, and that multiple processes run, exchanging the balances in the accounts. Argue that if the processes are run sequentially , after any number of concurrent exchanges, the account balances should be $10, $20, and $30 in some order . Draw a timing diagram like the one in figure 3.29 to show how this condition can be vi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6619520o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "olated if the exchanges are implemented using the first version of the account-exchange program in this section. On the other hand, ar gue that even with this exchange  program, the sum of the balances in the accounts will be preserved. Draw a timing diagram to show how even this condition would be violated if we did not serialize the transactions on individual accounts. Exer cise 3.44.   Consider the problem of transferring an amount from one account to another . Ben Bitdiddle claims that this can be accomplished with the following procedure, even if there are multiple people concurrently transferring money among multiple accounts, using any account mechanism that serializes deposit and withdrawal transactions, for example, the version of make-account  in the text above. (define (transfer from-account to-account amount)     ((from-account 'withdraw) amount)     ((to-account 'deposit) amount))  Louis Reasoner claims that there is a problem here, and that we need to use a more sophisticated method, such as the"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6620544
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " one required for dealing with the exchange problem. Is Louis right? If not, what is the essential dif ference between the transfer problem and the exchange problem? (You should assume that the balance in from-account  is at least amount .) Exer cise 3.45.   Louis Reasoner thinks our bank-account system is unnecessarily complex and error -prone now that deposits and withdrawals aren't automatically serialized. He suggests that make-account-and- serializer  should have exported the serializer (for use by such procedures as serialized-exchange ) in addition to (rather than instead of) using it to serialize accounts and deposits as make-account  did. He proposes to redefine accounts as follows: (define (make-account-and-serializer balance)     (define (withdraw amount)       (if (>= balance amount)           (begin (set! balance (- balance amount))                  balance)           \"Insufficient funds\"))     (define (deposit amount)       (set! balance (+ balance amount))       balance)     (let ((balance-seri"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6621568a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "alizer (make-serializer)))       (define (dispatch m)         (cond ((eq? m 'withdraw) (balance-serializer withdraw))               ((eq? m 'deposit) (balance-serializer deposit))               ((eq? m 'balance) balance)               ((eq? m 'serializer) balance-serializer)               (else (error \"Unknown request -- MAKE-ACCOUNT\"                            m))))       dispatch))   Then deposits are handled as with the original make-account : (define (deposit account amount)    ((account 'deposit) amount))  Explain what is wrong with Louis's reasoning. In particular , consider what happens when serialized-exchange  is called. Implementing serializers We implement serializers in terms of a more primitive synchronization mechanism called a mutex . A mutex is an object that supports two operations \u2013 the mutex can be acquir ed, and the mutex can be released . Once a mutex has been acquired, no other acquire operations on that mutex may proceed until the mutex is released.44 In our implementation, each seriali"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6622592z
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "zer has an associated mutex. Given a procedure p, the serializer returns a procedure that acquires the mutex, runs p, and then releases the mutex. This ensures that only one of the procedures produced by the serializer can be running at once, which is precisely the serialization property that we need to guarantee. (define (make-serializer)     (let ((mutex (make-mutex)))       (lambda (p)         (define (serialized-p . args)           (mutex 'acquire)           (let ((val (apply p args)))             (mutex 'release)             val))         serialized-p)))   The mutex is a mutable object (here we'll use a one-element list, which we'll refer to as a cell) that can hold the value true or false. When the value is false, the mutex is available to be acquired. When the value is true, the mutex is unavailable, and any process that attempts to acquire the mutex must wait. Our mutex constructor make-mutex  begins by initializing the cell contents to false. To acquire the mutex, we test the cell. If the mutex is av"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6623616a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ailable, we set the cell contents to true and proceed. Otherwise, we wait in a loop, attempting to acquire over and over again, until we find that the mutex is available.45 To release the mutex, we set the cell contents to false.(define (make-mutex)     (let ((cell (list false)))                  (define (the-mutex m)         (cond ((eq? m 'acquire)                (if (test-and-set! cell)                    (the-mutex 'acquire))) ; retry              ((eq? m 'release) (clear! cell))))       the-mutex))   (define (clear! cell)     (set-car! cell false))   Test-and-set!  tests the cell and returns the result of the test. In addition, if the test was false, test-and-set!  sets the cell contents to true before returning false. We can express this behavior as the following procedure: (define (test-and-set! cell)     (if (car cell)         true         (begin (set-car! cell true)                false)))   However , this implementation of test-and-set!  does not suf fice as it stands. There is a crucial subtlety her"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6624640e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e, which is the essential place where concurrency control enters the system: The test-and-set!  operation must be performed atomically . That is, we must guarantee that, once a process has tested the cell and found it to be false, the cell contents will actually be set to true before any other process can test the cell. If we do not make this guarantee, then the mutex can fail in a way similar to the bank-account failure in figure 3.29. (See exercise 3.46.) The actual implementation of test-and-set!  depends on the details of how our system runs concurrent processes. For example, we might be executing concurrent processes on a sequential processor using a time-slicing mechanism that cycles through the processes, permitting each process to run for a short time before interrupting it and moving on to the next process. In that case, test-and-set!  can work by disabling time slicing during thetesting and setting.46 Alternatively , multiprocessing computers provide instructions that support atomic operations direc"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6625664t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tly in hardware.47 Exer cise 3.46.   Suppose that we implement test-and-set!  using an ordinary procedure as shown in the text, without attempting to make the operation atomic. Draw a timing diagram like the one in figure 3.29 to demonstrate how the mutex implementation can fail by allowing two processes to acquire the mutex at the same time. Exer cise 3.47.   A semaphore (of size n) is a generalization of a mutex. Like a mutex, a semaphore supports acquire and release operations, but it is more general in that up to n processes can acquire it concurrently . Additional processes that attempt to acquire the semaphore must wait for release operations. Give implementations of semaphores a. in terms of mutexes b. in terms of atomic test-and-set!  operations. Deadlock Now that we have seen how to implement serializers, we can see that account exchanging still has a problem, even with the serialized- exchange  procedure above. Imagine that Peter attempts to exchange a1 with a2 while Paul concurrently attempts to ex"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6626688c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "change a2 with a1. Suppose that Peter's process reaches the point where it has entered a serialized procedure protecting a1 and, just after that, Paul's process enters a serialized procedure protecting a2. Now Peter cannot proceed (to enter a serialized procedure protecting a2) until Paul exits the serialized procedure protecting a2. Similarly , Paul cannot proceed until Peter exits the serialized procedure protecting a1. Each process is stalled forever , waiting for the other . This situation is called a deadlock . Deadlock is always a danger in systems that provide concurrent access to multiple shared resources. One way to avoid the deadlock in this situation is to give each account a unique identification number and rewrite serialized-exchange  so that a process will always attempt to enter a procedure protecting the lowest- numbered account first. Although this method works well for the exchangeproblem, there are other situations that require more sophisticated deadlock- avoidance techniques, or where dea"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6627712d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "dlock cannot be avoided at all. (See exercises 3.48 and 3.49.)48 Exer cise 3.48.   Explain in detail why the deadlock-avoidance method described above, (i.e., the accounts are numbered, and each process attempts to acquire the smaller -numbered account first) avoids deadlock in the exchange problem. Rewrite serialized-exchange  to incorporate this idea. (Y ou will also need to modify make-account  so that each account is created with a number , which can be accessed by sending an appropriate message.) Exer cise 3.49.   Give a scenario where the deadlock-avoidance mechanism described above does not work. (Hint: In the exchange problem, each process knows in advance which accounts it will need to get access to. Consider a situation where a process must get access to some shared resources before it can know which additional shared resources it will require.) Concurr ency , time, and communication We've seen how programming concurrent systems requires controlling the ordering of events when dif ferent processes a"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6628736c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ccess shared state, and we've seen how to achieve this control through judicious use of serializers. But the problems of concurrency lie deeper than this, because, from a fundamental point of view , it's not always clear what is meant by \u201cshared state.\u201d Mechanisms such as test-and-set!  require processes to examine a global shared flag at arbitrary times. This is problematic and inef ficient to implement in modern high-speed processors, where due to optimization techniques such as pipelining and cached memory , the contents of memory may not be in a consistent state at every instant. In contemporary multiprocessing systems, therefore, the serializer paradigm is being supplanted by new approaches to concurrency control.49 The problematic aspects of shared state also arise in lar ge, distributed systems. For instance, imagine a distributed banking system whereindividual branch banks maintain local values for bank balances and periodically compare these with values maintained by other branches. In such a system "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6629760t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "the value of \u201cthe account balance\u201d would be undetermined, except right after synchronization. If Peter deposits money in an account he holds jointly with Paul, when should we say that the account balance has changed \u2013 when the balance in the local branch changes, or not until after the synchronization? And if Paul accesses the account from a dif ferent branch, what are the reasonable constraints to place on the banking system such that the behavior is \u201ccorrect\u201d? The only thing that might matter for correctness is the behavior observed by Peter and Paul individually and the \u201cstate\u201d of the account immediately after synchronization. Questions about the \u201creal\u201d account balance or the order of events between synchronizations may be irrelevant or meaningless.50 The basic phenomenon here is that synchronizing dif ferent processes, establishing shared state, or imposing an order on events requires communication among the processes. In essence, any notion of time in concurrency control must be intimately tied to commun"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6630784i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ication.51 It is intriguing that a similar connection between time and communication also arises in the Theory of Relativity , where the speed of light (the fastest signal that can be used to synchronize events) is a fundamental constant relating time and space. The complexities we encounter in dealing with time and state in our computational models may in fact mirror a fundamental complexity of the physical universe. 34 Most real processors actually execute a few operations at a time, following a strategy called pipelining . Although this technique greatly improves the ef fective utilization of the hardware, it is used only to speed up the execution of a sequential instruction stream, while retaining the behavior of the sequential program. 35 To quote some graf fiti seen on a Cambridge building wall: \u201cT ime is a device that was invented to keep everything from happening at once.\u201d 36 An even worse failure for this system could occur if the two set!  operations attempt to change the balance simultaneously , in"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6631808
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " which case the actual data appearing in memory might end up being a random combination of the information being written by the two processes. Most computers have interlocks on the primitive memory-write operations, which protect against such simultaneous access. Even this seemingly simple kind of protection, however , raises implementation challenges in the design of multiprocessing computers, where elaborate cache-coher ence protocols are required to ensure that the various processors will maintain a consistent view of memory contents, despite thefact that data may be replicated (\u201ccached\u201d) among the dif ferent processors to increase the speed of memory access. 37 The factorial program in section 3.1.3  illustrates this for a single sequential process. 38 The columns show the contents of Peter's wallet, the joint account (in Bank1), Paul's wallet, and Paul's private account (in Bank2), before and after each withdrawal (W) and deposit (D). Peter withdraws $10 from Bank1; Paul deposits $5 in Bank2, then withdr"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6632832a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "aws $25 from Bank1. 39 A more formal way to express this idea is to say that concurrent programs are inherently nondeterministic . That is, they are described not by single-valued functions, but by functions whose results are sets of possible values. In section 4.3 we will study a language for expressing nondeterministic computations. 40 Parallel-execute  is not part of standard Scheme, but it can be implemented in MIT Scheme. In our implementation, the new concurrent processes also run concurrently with the original Scheme process. Also, in our implementation, the value returned by parallel-execute  is a special control object that can be used to halt the newly created processes. 41 We have simplified exchange  by exploiting the fact that our deposit  message accepts negative amounts. (This is a serious bug in our banking system!) 42 If the account balances start out as $10, $20, and $30, then after any number of concurrent exchanges, the balances should still be $10, $20, and $30 in some order . Serializing"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6633856
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " the deposits to individual accounts is not suf ficient to guarantee this. See exercise 3.43. 43 Exercise 3.45 investigates why deposits and withdrawals are no longer automatically serialized by the account. 44 The term \u201cmutex\u201d is an abbreviation for mutual exclusion . The general problem of arranging a mechanism that permits concurrent processes to safely share resources is called the mutual exclusion problem. Our mutex is a simple variant of the semaphor e mechanism (see exercise 3.47), which was introduced in the \u201cTHE\u201d Multiprogramming System developed at the Technological University of Eindhoven and named for the university's initials in Dutch (Dijkstra 1968a). The acquire and release operations were originally called P and V , from the Dutch words passer en (to pass) and vrijgeven  (to release), in reference to the semaphores used on railroad systems. Dijkstra's classic exposition (1968b) was one of the first to clearly present the issues of concurrency control, and showed how to use semaphores to handle"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6634880
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " a variety of concurrency problems. 45 In most time-shared operating systems, processes that are blocked by a mutex do not waste time \u201cbusy-waiting\u201d as above. Instead, the system schedules another process to run while the first is waiting, and the blocked process is awakened when the mutex becomes available. 46 In MIT Scheme for a single processor , which uses a time-slicing model, test-and-set!  can be implemented as follows: (define (test-and-set! cell)     (without-interrupts      (lambda ()        (if (car cell)           true            (begin (set-car! cell true)                   false)))))   Without-interrupts  disables time-slicing interrupts while its procedure ar gument is being executed. 47 There are many variants of such instructions \u2013 including test-and-set, test-and-clear , swap, compare-and-exchange, load-reserve, and store-conditional \u2013 whose design must be carefully matched to the machine's processor -memory interface. One issue that arises here is to determine what happens if two processes "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6635904a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "attempt to acquire the same resource at exactly the same time by using such an instruction. This requires some mechanism for making a decision about which process gets control. Such a mechanism is called an arbiter . Arbiters usually boil down to some sort of hardware device. Unfortunately , it is possible to prove that one cannot physically construct a fair arbiter that works 100% of the time unless one allows the arbiter an arbitrarily long time to make its decision. The fundamental phenomenon here was originally observed by the fourteenth-century French philosopher Jean Buridan in his commentary on Aristotle's De caelo . Buridan ar gued that a perfectly rational dog placed between two equally attractive sources of food will starve to death, because it is incapable of deciding which to go to first. 48 The general technique for avoiding deadlock by numbering the shared resources and acquiring them in order is due to Havender (1968). Situations where deadlock cannot be avoided require deadlock-r ecovery  meth"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6636928o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ods, which entail having processes \u201cback out\u201d of the deadlocked state and try again. Deadlock-recovery mechanisms are widely used in database management systems, a topic that is treated in detail in Gray and Reuter 1993. 49 One such alternative to serialization is called barrier synchr onization . The programmer permits concurrent processes to execute as they please, but establishes certain synchronization points (\u201cbarriers\u201d) through which no process can proceed until all the processes have reached the barrier . Modern processors provide machine instructions that permit programmers to establish synchronization points at places where consistency is required. The PowerPCTM, for example, includes for this purpose two instructions called SYNC and EIEIO (Enforced In-order Execution of Input/Output). 50 This may seem like a strange point of view , but there are systems that work this way . International charges to credit-card accounts, for example, are normally cleared on a per -country basis, and the charges made "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6637952i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "in dif ferent countries are periodically reconciled. Thus the account balance may be different in dif ferent countries. 51 For distributed systems, this perspective was pursued by Lamport (1978), who showed how to use communication to establish \u201cglobal clocks\u201d that can be used to establish orderings on events in distributed systems.3.5  Streams We've gained a good understanding of assignment as a tool in modeling, as well as an appreciation of the complex problems that assignment raises. It is time to ask whether we could have gone about things in a dif ferent way , so as to avoid some of these problems. In this section, we explore an alternative approach to modeling state, based on data structures called streams . As we shall see, streams can mitigate some of the complexity of modeling state. Let's step back and review where this complexity comes from. In an attempt to model real-world phenomena, we made some apparently reasonable decisions: W e modeled real-world objects with local state by computational ob"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6638976j
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "jects with local variables. We identified time variation in the real world with time variation in the computer . We implemented the time variation of the states of the model objects in the computer with assignments to the local variables of the model objects. Is there another approach? Can we avoid identifying time in the computer with time in the modeled world? Must we make the model change with time in order to model phenomena in a changing world? Think about the issue in terms of mathematical functions. We can describe the time-varying behavior of a quantity x as a function of time x(t). If we concentrate on x instant by instant, we think of it as a changing quantity . Yet if we concentrate on the entire time history of values, we do not emphasize change \u2013 the function itself does not change.52 If time is measured in discrete steps, then we can model a time function as a (possibly infinite) sequence. In this section, we will see how to model change in terms of sequences that represent the time histories of"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6640000
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " the systems being modeled. To accomplish this, we introduce new data structures called streams . From an abstract point of view , a stream is simply a sequence. However , we will find that the straightforward implementation of streams as lists (as in section 2.2.1 ) doesn't fully reveal the power of stream processing. As an alternative, we introduce the technique of delayedevaluation , which enables us to represent very lar ge (even infinite) sequences as streams. Stream processing lets us model systems that have state without ever using assignment or mutable data. This has important implications, both theoretical and practical, because we can build models that avoid the drawbacks inherent in introducing assignment. On the other hand, the stream framework raises dif ficulties of its own, and the question of which modeling technique leads to more modular and more easily maintained systems remains open. 3.5.1  Str eams Ar e Delayed Lists As we saw in section 2.2.3 , sequences can serve as standard interfaces f"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6641024o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "or combining program modules. We formulated powerful abstractions for manipulating sequences, such as map, filter , and accumulate , that capture a wide variety of operations in a manner that is both succinct and elegant. Unfortunately , if we represent sequences as lists, this elegance is bought at the price of severe inef ficiency with respect to both the time and space required by our computations. When we represent manipulations on sequences as transformations of lists, our programs must construct and copy data structures (which may be huge) at every step of a process. To see why this is true, let us compare two programs for computing the sum of all the prime numbers in an interval. The first program is written in standard iterative style:53 (define (sum-primes a b)     (define (iter count accum)       (cond ((> count b) accum)             ((prime? count) (iter (+ count 1) (+ count accum)))             (else (iter (+ count 1) accum))))     (iter a 0))   The second program performs the same computation usi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6642048n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ng the sequence operations of section 2.2.3 :(define (sum-primes a b)     (accumulate +                 0                 (filter prime? (enumerate-interval a b))))   In carrying out the computation, the first program needs to store only the sum being accumulated. In contrast, the filter in the second program cannot do any testing until enumerate-interval  has constructed a complete list of the numbers in the interval. The filter generates another list, which in turn is passed to accumulate  before being collapsed to form a sum. Such lar ge intermediate storage is not needed by the first program, which we can think of as enumerating the interval incrementally , adding each prime to the sum as it is generated. The inef ficiency in using lists becomes painfully apparent if we use the sequence paradigm to compute the second prime in the interval from 10,000 to 1,000,000 by evaluating the expression (car (cdr (filter prime?                     (enumerate-interval 10000 1000000))))   This expression does find the "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6643072s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "second prime, but the computational overhead is outrageous. We construct a list of almost a million integers, filter this list by testing each element for primality , and then ignore almost all of the result. In a more traditional programming style, we would interleave the enumeration and the filtering, and stop when we reached the second prime. Streams are a clever idea that allows one to use sequence manipulations without incurring the costs of manipulating sequences as lists. With streams we can achieve the best of both worlds: W e can formulate programs elegantly as sequence manipulations, while attaining the ef ficiency of incremental computation. The basic idea is to arrange to construct a stream only partially , and to pass the partial construction to the program that consumes the stream. If the consumer attempts to access a part of the stream that has not yet been constructed, the stream will automatically construct just enough more of itself to produce the required part, thus preserving the illusion "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6644096t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "that the entire stream exists. In other words, although we will write programs as if we were processing complete sequences, wedesign our stream implementation to automatically and transparently interleave the construction of the stream with its use. On the surface, streams are just lists with dif ferent names for the procedures that manipulate them. There is a constructor , cons-stream , and two selectors, stream-car  and stream-cdr , which satisfy the constraints (stream-car (cons-stream x y)) = x   (stream-cdr (cons-stream x y)) = y There is a distinguishable object, the-empty-stream , which cannot be the result of any cons-stream  operation, and which can be identified with the predicate stream-null? .54 Thus we can make and use streams, in just the same way as we can make and use lists, to represent aggregate data arranged in a sequence. In particular , we can build stream analogs of the list operations from chapter 2, such as list-ref , map, and for-each :55 (define (stream-ref s n)     (if (= n 0)      "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6645120
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "   (stream-car s)         (stream-ref (stream-cdr s) (- n 1))))   (define (stream-map proc s)     (if (stream-null? s)         the-empty-stream         (cons-stream (proc (stream-car s))                      (stream-map proc (stream-cdr s)))))   (define (stream-for-each proc s)     (if (stream-null? s)         'done         (begin (proc (stream-car s))                (stream-for-each proc (stream-cdr s)))))   Stream-for-each  is useful for viewing streams: (define (display-stream s)     (stream-for-each display-line s))     (define (display-line x)    (newline)     (display x))   To make the stream implementation automatically and transparently interleave the construction of a stream with its use, we will arrange for the cdr of a stream to be evaluated when it is accessed by the stream-cdr procedure rather than when the stream is constructed by cons-stream . This implementation choice is reminiscent of our discussion of rational numbers in section 2.1.2 , where we saw that we can choose to implement rational "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6646144n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "numbers so that the reduction of numerator and denominator to lowest terms is performed either at construction time or at selection time. The two rational-number implementations produce the same data abstraction, but the choice has an ef fect on ef ficiency . There is a similar relationship between streams and ordinary lists. As a data abstraction, streams are the same as lists. The dif ference is the time at which the elements are evaluated. With ordinary lists, both the car and the cdr are evaluated at construction time. With streams, the cdr is evaluated at selection time. Our implementation of streams will be based on a special form called delay . Evaluating (delay < exp>) does not evaluate the expression < exp>, but rather returns a so-called delayed object , which we can think of as a \u201cpromise\u201d to evaluate < exp> at some future time. As a companion to delay , there is a procedure called force  that takes a delayed object as ar gument and performs the evaluation \u2013 in ef fect, forcing the delay  to fulfil"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6647168l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "l its promise. We will see below how delay  and force  can be implemented, but first let us use these to construct streams. Cons-stream  is a special form defined so that (cons-stream < a> <b>)  is equivalent to (cons <a> (delay < b>))  What this means is that we will construct streams using pairs. However , rather than placing the value of the rest of the stream into the cdr of the pairwe will put there a promise to compute the rest if it is ever requested. Stream-car  and stream-cdr  can now be defined as procedures: (define (stream-car stream) (car stream))     (define (stream-cdr stream) (force (cdr stream)))   Stream-car  selects the car of the pair; stream-cdr  selects the cdr of the pair and evaluates the delayed expression found there to obtain the rest of the stream.56 The str eam implementation in action To see how this implementation behaves, let us analyze the \u201coutrageous\u201d prime computation we saw above, reformulated in terms of streams: (stream-car    (stream-cdr     (stream-filter prime?        "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6648192
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "            (stream-enumerate-interval 10000 1000000))))   We will see that it does indeed work ef ficiently . We begin by calling stream-enumerate-interval  with the ar guments 10,000 and 1,000,000. Stream-enumerate-interval  is the stream analog of enumerate-interval  (section 2.2.3 ): (define (stream-enumerate-interval low high)     (if (> low high)         the-empty-stream         (cons-stream          low          (stream-enumerate-interval (+ low 1) high))))   and thus the result returned by stream-enumerate-interval , formed by the cons-stream , is57(cons 10000         (delay (stream-enumerate-interval 10001 1000000)))   That is, stream-enumerate-interval  returns a stream represented as a pair whose car is 10,000 and whose cdr is a promise to enumerate more of the interval if so requested. This stream is now filtered for primes, using the stream analog of the filter  procedure (section 2.2.3 ): (define (stream-filter pred stream)     (cond ((stream-null? stream) the-empty-stream)           ((pred (str"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6649216e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eam-car stream))            (cons-stream (stream-car stream)                         (stream-filter pred                                        (stream-cdr stream))))           (else (stream-filter pred (stream-cdr stream)))))   Stream-filter  tests the stream-car  of the stream (the car of the pair , which is 10,000). Since this is not prime, stream-filter  examines the stream-cdr  of its input stream. The call to stream-cdr  forces evaluation of the delayed stream-enumerate-interval , which now returns (cons 10001         (delay (stream-enumerate-interval 10002 1000000)))   Stream-filter  now looks at the stream-car  of this stream, 10,001, sees that this is not prime either , forces another stream-cdr , and so on, until stream-enumerate-interval  yields the prime 10,007, whereupon stream- filter , according to its definition, returns (cons-stream (stream-car stream)                (stream-filter pred (stream-cdr stream)))   which in this case is (cons 10007         (delay           (stream-filter          "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6650240
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "  prime?           (cons 10008                  (delay                    (stream-enumerate-interval 10009                                               1000000))))))   This result is now passed to stream-cdr  in our original expression. This forces the delayed stream-filter , which in turn keeps forcing the delayed stream-enumerate-interval  until it finds the next prime, which is 10,009. Finally , the result passed to stream-car  in our original expression is (cons 10009         (delay           (stream-filter            prime?            (cons 10010                  (delay                    (stream-enumerate-interval 10011                                               1000000))))))   Stream-car  returns 10,009, and the computation is complete. Only as many integers were tested for primality as were necessary to find the second prime, and the interval was enumerated only as far as was necessary to feed the prime filter . In general, we can think of delayed evaluation as \u201cdemand-driven\u201d programming, whereby"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6651264
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " each stage in the stream process is activated only enough to satisfy the next stage. What we have done is to decouple the actual order of events in the computation from the apparent structure of our procedures. We write procedures as if the streams existed \u201call at once\u201d when, in reality , the computation is performed incrementally , as in traditional programming styles. Implementing delay  and force Although delay  and force  may seem like mysterious operations, their implementation is really quite straightforward. Delay  must package an expression so that it can be evaluated later on demand, and we canaccomplish this simply by treating the expression as the body of a procedure. Delay  can be a special form such that (delay < exp>)  is syntactic sugar for (lambda () < exp>)  Force  simply calls the procedure (of no ar guments) produced by delay , so we can implement force  as a procedure: (define (force delayed-object)     (delayed-object))   This implementation suf fices for delay  and force  to work as adv"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6652288e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ertised, but there is an important optimization that we can include. In many applications, we end up forcing the same delayed object many times. This can lead to serious inef ficiency in recursive programs involving streams. (See exercise 3.57.) The solution is to build delayed objects so that the first time they are forced, they store the value that is computed. Subsequent forcings will simply return the stored value without repeating the computation. In other words, we implement delay  as a special-purpose memoized procedure similar to the one described in exercise 3.27. One way to accomplish this is to use the following procedure, which takes as argument a procedure (of no ar guments) and returns a memoized version of the procedure. The first time the memoized procedure is run, it saves the computed result. On subsequent evaluations, it simply returns the result. (define (memo-proc proc)     (let ((already-run? false) (result false))       (lambda ()         (if (not already-run?)             (begin (set! "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6653312r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "result (proc))                    (set! already-run? true)                    result)             result))))  Delay  is then defined so that (delay < exp>) is equivalent to (memo-proc (lambda () < exp>))  and force  is as defined previously .58 Exer cise 3.50.   Complete the following definition, which generalizes stream-map  to allow procedures that take multiple ar guments, analogous to map in section 2.2.3 , footnote 12. (define (stream-map proc . argstreams)     (if (< ??> (car argstreams))         the-empty-stream         (< ??>         (apply proc (map < ??> argstreams))          (apply stream-map                 (cons proc (map < ??> argstreams))))))   Exer cise 3.51.   In order to take a closer look at delayed evaluation, we will use the following procedure, which simply returns its ar gument after printing it: (define (show x)     (display-line x)     x)  What does the interpreter print in response to evaluating each expression in the following sequence?59 (define x (stream-map show (stream-enumerate"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6654336-
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "-interval 0 10)))   (stream-ref x 5)   (stream-ref x 7)   Exer cise 3.52.   Consider the sequence of expressions (define sum 0)   (define (accum x)     (set! sum (+ x sum))    sum)  (define seq (stream-map accum (stream-enumerate- interval 1 20)))   (define y (stream-filter even? seq))   (define z (stream-filter (lambda (x) (= (remainder x 5) 0))                            seq))   (stream-ref y 7)   (display-stream z)   What is the value of sum after each of the above expressions is evaluated? What is the printed response to evaluating the stream-ref  and display- stream  expressions? Would these responses dif fer if we had implemented (delay < exp>) simply as (lambda () < exp>) without using the optimization provided by memo-proc  ? Explain. 3.5.2  Infinite Str eams We have seen how to support the illusion of manipulating streams as complete entities even though, in actuality , we compute only as much of the stream as we need to access. We can exploit this technique to represent sequences ef ficiently as str"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6655360e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eams, even if the sequences are very long. What is more striking, we can use streams to represent sequences that are infinitely long. For instance, consider the following definition of the stream of positive integers: (define (integers-starting-from n)     (cons-stream n (integers-starting-from (+ n 1))))     (define integers (integers-starting-from 1))   This makes sense because integers  will be a pair whose car is 1 and whose cdr is a promise to produce the integers beginning with 2. This is an infinitely long stream, but in any given time we can examine only a finite portion of it. Thus, our programs will never know that the entire infinite stream is not there. Using integers  we can define other infinite streams, such as the stream of integers that are not divisible by 7:(define (divisible? x y) (= (remainder x y) 0))   (define no-sevens     (stream-filter (lambda (x) (not (divisible? x 7)))                    integers))   Then we can find integers not divisible by 7 simply by accessing elements of this "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6656384s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "stream: (stream-ref no-sevens 100)   117  In analogy with integers , we can define the infinite stream of Fibonacci numbers: (define (fibgen a b)     (cons-stream a (fibgen b (+ a b))))   (define fibs (fibgen 0 1))   Fibs  is a pair whose car is 0 and whose cdr is a promise to evaluate (fibgen 1 1) . When we evaluate this delayed (fibgen 1 1) , it will produce a pair whose car is 1 and whose cdr is a promise to evaluate (fibgen 1 2) , and so on. For a look at a more exciting infinite stream, we can generalize the no- sevens  example to construct the infinite stream of prime numbers, using a method known as the sieve of Eratosthenes .60 We start with the integers beginning with 2, which is the first prime. To get the rest of the primes, we start by filtering the multiples of 2 from the rest of the integers. This leaves a stream beginning with 3, which is the next prime. Now we filter the multiples of 3 from the rest of this stream. This leaves a stream beginning with 5, which is the next prime, and so on. In o"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6657408t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ther words, we construct the primes by a sieving process, described as follows: T o sieve a stream S, form a stream whose first element is the first element of S and the rest of which is obtained by filtering all multiples of the first element of S out of the rest of S and sieving the result. This process is readily described in terms of stream operations:(define (sieve stream)     (cons-stream      (stream-car stream)      (sieve (stream-filter              (lambda (x)                (not (divisible? x (stream-car stream))))              (stream-cdr stream)))))     (define primes (sieve (integers-starting-from 2)))   Now to find a particular prime we need only ask for it: (stream-ref primes 50)   233  It is interesting to contemplate the signal-processing system set up by sieve , shown in the \u201cHenderson diagram\u201d in figure 3.31.61 The input stream feeds into an \u201cun cons er\u201d that separates the first element of the stream from the rest of the stream. The first element is used to construct a divisibility filter "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6658432,
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ", through which the rest is passed, and the output of the filter is fed to another sieve box. Then the original first element is cons ed onto the output of the internal sieve to form the output stream. Thus, not only is the stream infinite, but the signal processor is also infinite, because the sieve contains a sieve within it. Figur e 3.31:   The prime sieve viewed as a signal-processing system. Defining str eams implicitly The integers  and fibs  streams above were defined by specifying \u201cgenerating\u201d procedures that explicitly compute the stream elements one byone. An alternative way to specify streams is to take advantage of delayed evaluation to define streams implicitly . For example, the following expression defines the stream ones  to be an infinite stream of ones: (define ones (cons-stream 1 ones))   This works much like the definition of a recursive procedure: ones  is a pair whose car is 1 and whose cdr is a promise to evaluate ones . Evaluating the cdr gives us again a 1 and a promise to evaluate on"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6659456e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "es , and so on. We can do more interesting things by manipulating streams with operations such as add-streams , which produces the elementwise sum of two given streams:62 (define (add-streams s1 s2)     (stream-map + s1 s2))   Now we can define the integers as follows: (define integers (cons-stream 1 (add-streams ones integers)))   This defines integers  to be a stream whose first element is 1 and the rest of which is the sum of ones  and integers . Thus, the second element of integers  is 1 plus the first element of integers , or 2; the third element of integers  is 1 plus the second element of integers , or 3; and so on. This definition works because, at any point, enough of the integers  stream has been generated so that we can feed it back into the definition to produce the next integer . We can define the Fibonacci numbers in the same style: (define fibs     (cons-stream 0                  (cons-stream 1                               (add-streams (stream-cdr fibs)                                         "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6660480
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "   fibs))))  This definition says that fibs  is a stream beginning with 0 and 1, such that the rest of the stream can be generated by adding fibs  to itself shifted by one place: 1123581321... = (stream-cdr fibs) 011235813... = fibs 0112358132134... = fibs Scale-stream  is another useful procedure in formulating such stream definitions. This multiplies each item in a stream by a given constant: (define (scale-stream stream factor)     (stream-map (lambda (x) (* x factor)) stream))   For example, (define double (cons-stream 1 (scale-stream double 2)))   produces the stream of powers of 2: 1, 2, 4, 8, 16, 32, .... An alternate definition of the stream of primes can be given by starting with the integers and filtering them by testing for primality . We will need the first prime, 2, to get started: (define primes     (cons-stream      2     (stream-filter prime? (integers-starting-from 3))))   This definition is not so straightforward as it appears, because we will test whether a number n is prime by checking whe"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6661504t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ther n is divisible by a prime (not by just any integer) less than or equal to \u221a n: (define (prime? n)     (define (iter ps)       (cond ((> (square (stream-car ps)) n) true)             ((divisible? n (stream-car ps)) false)            (else (iter (stream-cdr ps)))))     (iter primes))   This is a recursive definition, since primes  is defined in terms of the prime? predicate, which itself uses the primes  stream. The reason this procedure works is that, at any point, enough of the primes  stream has been generated to test the primality of the numbers we need to check next. That is, for every n we test for primality , either n is not prime (in which case there is a prime already generated that divides it) or n is prime (in which case there is a prime already generated \u2013 i.e., a prime less than n \u2013 that is greater than \u221an).63 Exer cise 3.53.   Without running the program, describe the elements of the stream defined by (define s (cons-stream 1 (add-streams s s)))   Exer cise 3.54.   Define a procedure mul-stre"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6662528a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ams , analogous to add- streams , that produces the elementwise product of its two input streams. Use this together with the stream of integers  to complete the following definition of the stream whose nth element (counting from 0) is n + 1 factorial: (define factorials (cons-stream 1 (mul-streams < ??> <??>)))  Exer cise 3.55.   Define a procedure partial-sums  that takes as ar gument a stream S and returns the stream whose elements are S0, S0 + S1, S0 + S1 + S2, .... For example, (partial-sums integers)  should be the stream 1, 3, 6, 10, 15, .... Exer cise 3.56.   A famous problem, first raised by R. Hamming, is to enumerate, in ascending order with no repetitions, all positive integers with no prime factors other than 2, 3, or 5. One obvious way to do this is to simply test each integer in turn to see whether it has any factors other than 2, 3, and 5. But this is very inef ficient, since, as the integers get lar ger, fewer and fewer of them fit the requirement. As an alternative, let us call the required s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6663552t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tream of numbers S and notice the following facts about it.S begins with 1. The elements of (scale-stream S 2)  are also elements of S. The same is true for (scale-stream S 3)  and (scale-stream 5 S) . These are all the elements of S. Now all we have to do is combine elements from these sources. For this we define a procedure merge  that combines two ordered streams into one ordered result stream, eliminating repetitions: (define (merge s1 s2)     (cond ((stream-null? s1) s2)           ((stream-null? s2) s1)           (else            (let ((s1car (stream-car s1))                  (s2car (stream-car s2)))              (cond ((< s1car s2car)                     (cons-stream s1car (merge (stream- cdr s1) s2)))                    ((> s1car s2car)                     (cons-stream s2car (merge s1 (stream- cdr s2))))                    (else                     (cons-stream s1car                                  (merge (stream-cdr s1)                                         (stream-cdr s2)))))))))   Then the requir"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6664576e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ed stream may be constructed with merge , as follows: (define S (cons-stream 1 (merge < ??> <??>)))  Fill in the missing expressions in the places marked < ??> above. Exer cise 3.57.   How many additions are performed when we compute the nth Fibonacci number using the definition of fibs  based on the add- streams  procedure? Show that the number of additions would beexponentially greater if we had implemented (delay < exp>) simply as (lambda () < exp>), without using the optimization provided by the memo- proc  procedure described in section 3.5.1 .64 Exer cise 3.58.   Give an interpretation of the stream computed by the following procedure: (define (expand num den radix)     (cons-stream      (quotient (* num radix) den)      (expand (remainder (* num radix) den) den radix)))   (Quotient  is a primitive that returns the integer quotient of two integers.) What are the successive elements produced by (expand 1 7 10)  ? What is produced by (expand 3 8 10)  ? Exer cise 3.59.   In section 2.5.3  we saw how to imp"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6665600l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "lement a polynomial arithmetic system representing polynomials as lists of terms. In a similar way, we can work with power series , such as represented as infinite streams. We will represent the series a0 + a1x + a2x2 + a3x3 + \u00b7\u00b7\u00b7 as the stream whose elements are the coef ficients a0, a1, a2, a3, .... a. The integral of the series a0 + a1x + a2x2 + a3x3 + \u00b7\u00b7\u00b7 is the series where c is any constant. Define a procedure integrate-series  that takes as input a stream a0, a1, a2, ... representing a power series and returns the stream a0, (1/2) a1, (1/3) a2, ... of coef ficients of the non-constant terms of the integral of the series. (Since the result has no constant term, it doesn't represent a power series; when we use integrate-series , we will cons  on the appropriate constant.) b. The function x \u27fc ex is its own derivative. This implies that ex and the integral of ex are the same series, except for the constant term, which is e0 = 1. Accordingly , we can generate the series for ex as (define exp-series     (con"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6666624s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s-stream 1 (integrate-series exp-series)))   Show how to generate the series for sine and cosine, starting from the facts that the derivative of sine is cosine and the derivative of cosine is the negative of sine: (define cosine-series     (cons-stream 1 < ??>))  (define sine-series     (cons-stream 0 < ??>))  Exer cise 3.60.   With power series represented as streams of coef ficients as in exercise 3.59, adding series is implemented by add-streams . Complete the definition of the following procedure for multiplying series: (define (mul-series s1 s2)     (cons-stream < ??> (add-streams < ??> <??>)))  You can test your procedure by verifying that sin2x + cos2x = 1, using the series from exercise 3.59. Exer cise 3.61.   Let S be a power series (exercise 3.59) whose constant term is 1. Suppose we want to find the power series 1/ S, that is, the series X such that S \u00b7 X = 1. Write S = 1 + SR where SR is the part of S after the constant term. Then we can solve for X as follows:In other words, X is the power series"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6667648
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " whose constant term is 1 and whose higher -order terms are given by the negative of SR times X. Use this idea to write a procedure invert-unit-series  that computes 1/ S for a power series S with constant term 1. You will need to use mul-series  from exercise 3.60. Exer cise 3.62.   Use the results of exercises 3.60 and 3.61 to define a procedure div-series  that divides two power series. Div-series  should work for any two series, provided that the denominator series begins with a nonzero constant term. (If the denominator has a zero constant term, then div-series  should signal an error .) Show how to use div-series  together with the result of exercise 3.59 to generate the power series for tangent. 3.5.3  Exploiting the Str eam Paradigm Streams with delayed evaluation can be a powerful modeling tool, providing many of the benefits of local state and assignment. Moreover , they avoid some of the theoretical tangles that accompany the introduction of assignment into a programming language. The stream approa"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6668672c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ch can be illuminating because it allows us to build systems with dif ferent module boundaries than systems or ganized around assignment to state variables. For example, we can think of an entire time series (or signal) as a focus of interest, rather than the values of the state variables at individual moments. This makes it convenient to combine and compare components of state from dif ferent moments. Formulating iterations as str eam pr ocesses In section 1.2.1 , we introduced iterative processes, which proceed by updating state variables. We know now that we can represent state as a \u201ctimeless\u201d stream of values rather than as a set of variables to be updated. Let's adopt this perspective in revisiting the square-root procedure fromsection 1.1.7 . Recall that the idea is to generate a sequence of better and better guesses for the square root of x by applying over and over again the procedure that improves guesses: (define (sqrt-improve guess x)     (average guess (/ x guess)))   In our original sqrt  procedu"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6669696r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "re, we made these guesses be the successive values of a state variable. Instead we can generate the infinite stream of guesses, starting with an initial guess of 1:65 (define (sqrt-stream x)     (define guesses       (cons-stream 1.0                    (stream-map (lambda (guess)                                  (sqrt-improve guess x))                                guesses)))     guesses)   (display-stream (sqrt-stream 2))   1.  1.5  1.4166666666666665   1.4142156862745097   1.4142135623746899   ... We can generate more and more terms of the stream to get better and better guesses. If we like, we can write a procedure that keeps generating terms until the answer is good enough. (See exercise 3.64.) Another iteration that we can treat in the same way is to generate an approximation to \u03c0, based upon the alternating series that we saw in section 1.3.1 : We first generate the stream of summands of the series (the reciprocals of the odd integers, with alternating signs). Then we take the stream of sums of more an"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6670720d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "d more terms (using the partial-sums  procedure of exercise 3.55) and scale the result by 4: (define (pi-summands n)     (cons-stream (/ 1.0 n)                  (stream-map - (pi-summands (+ n 2)))))   (define pi-stream     (scale-stream (partial-sums (pi-summands 1)) 4))   (display-stream pi-stream)   4.  2.666666666666667   3.466666666666667   2.8952380952380956   3.3396825396825403   2.9760461760461765   3.2837384837384844   3.017071817071818   ... This gives us a stream of better and better approximations to \u03c0, although the approximations conver ge rather slowly . Eight terms of the sequence bound the value of \u03c0 between 3.284 and 3.017. So far , our use of the stream of states approach is not much dif ferent from updating state variables. But streams give us an opportunity to do some interesting tricks. For example, we can transform a stream with a sequence accelerator  that converts a sequence of approximations to a new sequence that conver ges to the same value as the original, only faster . One such ac"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6671744c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "celerator , due to the eighteenth-century Swiss mathematician Leonhard Euler , works well with sequences that are partial sums of alternating series (series of terms with alternating signs). In Euler's technique, if Sn is the nth term of the original sum sequence, then the accelerated sequence has termsThus, if the original sequence is represented as a stream of values, the transformed sequence is given by (define (euler-transform s)     (let ((s0 (stream-ref s 0))           ; Sn-1          (s1 (stream-ref s 1))           ; Sn          (s2 (stream-ref s 2)))          ; Sn+1      (cons-stream (- s2 (/ (square (- s2 s1))                             (+ s0 (* -2 s1) s2)))                    (euler-transform (stream-cdr s)))))   We can demonstrate Euler acceleration with our sequence of approximations to \u03c0: (display-stream (euler-transform pi-stream))   3.166666666666667   3.1333333333333337   3.1452380952380956   3.13968253968254   3.1427128427128435   3.1408813408813416   3.142071817071818   3.1412548236077655  "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6672768
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " ... Even better , we can accelerate the accelerated sequence, and recursively accelerate that, and so on. Namely , we create a stream of streams (a structure we'll call a tableau ) in which each stream is the transform of the preceding one: (define (make-tableau transform s)     (cons-stream s                  (make-tableau transform                                (transform s))))  The tableau has the form Finally , we form a sequence by taking the first term in each row of the tableau: (define (accelerated-sequence transform s)     (stream-map stream-car                 (make-tableau transform s)))   We can demonstrate this kind of \u201csuper -acceleration\u201d of the \u03c0 sequence: (display-stream (accelerated-sequence euler-transform                                         pi-stream))   4.  3.166666666666667   3.142105263157895   3.141599357319005   3.1415927140337785   3.1415926539752927   3.1415926535911765   3.141592653589778   ... The result is impressive. Taking eight terms of the sequence yields the correct va"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6673792l
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "lue of \u03c0 to 14 decimal places. If we had used only the original \u03c0 sequence, we would need to compute on the order of 1013 terms (i.e., expanding the series far enough so that the individual terms are less then 10-13) to get that much accuracy! We could have implemented these acceleration techniques without using streams. But the stream formulation is particularly elegant and convenient because the entire sequence of states is available to us as a data structure that can be manipulated with a uniform set of operations.Exer cise 3.63.   Louis Reasoner asks why the sqrt-stream  procedure was not written in the following more straightforward way , without the local variable guesses : (define (sqrt-stream x)     (cons-stream 1.0                  (stream-map (lambda (guess)                                (sqrt-improve guess x))                              (sqrt-stream x))))   Alyssa P . Hacker replies that this version of the procedure is considerably less ef ficient because it performs redundant computation. Expl"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6674816a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ain Alyssa's answer . Would the two versions still dif fer in ef ficiency if our implementation of delay  used only (lambda () < exp>) without using the optimization provided by memo-proc  (section 3.5.1 )? Exer cise 3.64.   Write a procedure stream-limit  that takes as ar guments a stream and a number (the tolerance). It should examine the stream until it finds two successive elements that dif fer in absolute value by less than the tolerance, and return the second of the two elements. Using this, we could compute square roots up to a given tolerance by (define (sqrt x tolerance)     (stream-limit (sqrt-stream x) tolerance))   Exer cise 3.65.   Use the series to compute three sequences of approximations to the natural logarithm of 2, in the same way we did above for \u03c0. How rapidly do these sequences conver ge? Infinite str eams of pairs In section 2.2.3 , we saw how the sequence paradigm handles traditional nested loops as processes defined on sequences of pairs. If we generalizethis technique to infinite str"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6675840e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eams, then we can write programs that are not easily represented as loops, because the \u201clooping\u201d must range over an infinite set. For example, suppose we want to generalize the prime-sum-pairs procedure of section 2.2.3  to produce the stream of pairs of all integers ( i,j) with i < j such that i + j is prime. If int-pairs  is the sequence of all pairs of integers ( i,j) with i < j, then our required stream is simply66 (stream-filter (lambda (pair)                    (prime? (+ (car pair) (cadr pair))))                  int-pairs)   Our problem, then, is to produce the stream int-pairs . More generally , suppose we have two streams S = (Si) and T = (Tj), and imagine the infinite rectangular array We wish to generate a stream that contains all the pairs in the array that lie on or above the diagonal, i.e., the pairs (If we take both S and T to be the stream of integers, then this will be our desired stream int-pairs .) Call the general stream of pairs (pairs S T) , and consider it to be composed of three parts"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6676864:
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ": the pair ( S0,T0), the rest of the pairs in the first row, and the remaining pairs:67Observe that the third piece in this decomposition (pairs that are not in the first row) is (recursively) the pairs formed from (stream-cdr S)  and (stream-cdr T) . Also note that the second piece (the rest of the first row) is (stream-map (lambda (x) (list (stream-car s) x))               (stream-cdr t))   Thus we can form our stream of pairs as follows: (define (pairs s t)     (cons-stream      (list (stream-car s) (stream-car t))      (<combine-in-some-way >         (stream-map (lambda (x) (list (stream-car s) x))                      (stream-cdr t))          (pairs (stream-cdr s) (stream-cdr t)))))   In order to complete the procedure, we must choose some way to combine the two inner streams. One idea is to use the stream analog of the append procedure from section 2.2.1 : (define (stream-append s1 s2)     (if (stream-null? s1)         s2         (cons-stream (stream-car s1)                      (stream-append (stream-c"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6677888d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "dr s1) s2))))   This is unsuitable for infinite streams, however , because it takes all the elements from the first stream before incorporating the second stream. In particular , if we try to generate all pairs of positive integers using (pairs integers integers)  our stream of results will first try to run through all pairs with the first integer equal to 1, and hence will never produce pairs with any other value of the first integer . To handle infinite streams, we need to devise an order of combination that ensures that every element will eventually be reached if we let our program run long enough. An elegant way to accomplish this is with the following interleave  procedure:68 (define (interleave s1 s2)     (if (stream-null? s1)         s2         (cons-stream (stream-car s1)                      (interleave s2 (stream-cdr s1)))))   Since interleave  takes elements alternately from the two streams, every element of the second stream will eventually find its way into the interleaved stream, even if the fir"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6678912s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "st stream is infinite. We can thus generate the required stream of pairs as (define (pairs s t)     (cons-stream      (list (stream-car s) (stream-car t))      (interleave       (stream-map (lambda (x) (list (stream-car s) x))                   (stream-cdr t))       (pairs (stream-cdr s) (stream-cdr t)))))   Exer cise 3.66.   Examine the stream (pairs integers integers) . Can you make any general comments about the order in which the pairs are placed into the stream? For example, about how many pairs precede the pair (1,100)? the pair (99,100)? the pair (100,100)? (If you can make precise mathematical statements here, all the better . But feel free to give more qualitative answers if you find yourself getting bogged down.) Exer cise 3.67.   Modify the pairs  procedure so that (pairs integers integers)  will produce the stream of all pairs of integers ( i,j) (without thecondition i < j). Hint: Y ou will need to mix in an additional stream. Exer cise 3.68.   Louis Reasoner thinks that building a stream of pairs"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6679936
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " from three parts is unnecessarily complicated. Instead of separating the pair (S0,T0) from the rest of the pairs in the first row , he proposes to work with the whole first row , as follows: (define (pairs s t)     (interleave      (stream-map (lambda (x) (list (stream-car s) x))                  t)      (pairs (stream-cdr s) (stream-cdr t))))   Does this work? Consider what happens if we evaluate (pairs integers integers)  using Louis's definition of pairs . Exer cise 3.69.   Write a procedure triples  that takes three infinite streams, S, T, and U, and produces the stream of triples ( Si,Tj,Uk) such that i < j < k. Use triples  to generate the stream of all Pythagorean triples of positive integers, i.e., the triples ( i,j,k) such that i < j and i2 + j2 = k2. Exer cise 3.70.   It would be nice to be able to generate streams in which the pairs appear in some useful order , rather than in the order that results from an ad hoc  interleaving process. We can use a technique similar to the merge procedure of exer"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6680960c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cise 3.56, if we define a way to say that one pair of integers is \u201cless than\u201d another . One way to do this is to define a \u201cweighting function\u201d W(i,j) and stipulate that ( i1,j1) is less than ( i2,j2) if W(i1,j1) < W(i2,j2). Write a procedure merge-weighted  that is like merge , except that merge-weighted  takes an additional ar gument weight , which is a procedure that computes the weight of a pair , and is used to determine the order in which elements should appear in the resulting mer ged stream.69 Using this, generalize pairs  to a procedure weighted-pairs  that takes two streams, together with a procedure that computes a weighting function, and generates the stream of pairs, ordered according to weight. Use your procedure to generatea. the stream of all pairs of positive integers ( i,j) with i < j ordered according to the sum i + j b. the stream of all pairs of positive integers ( i,j) with i < j, where neither i nor j is divisible by 2, 3, or 5, and the pairs are ordered according to the sum 2 i + 3 j + "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch66819845
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "5 i j. Exer cise 3.71.   Numbers that can be expressed as the sum of two cubes in more than one way are sometimes called Ramanujan numbers , in honor of the mathematician Srinivasa Ramanujan.70 Ordered streams of pairs provide an elegant solution to the problem of computing these numbers. To find a number that can be written as the sum of two cubes in two dif ferent ways, we need only generate the stream of pairs of integers ( i,j) weighted according to the sum i3 + j3 (see exercise 3.70), then search the stream for two consecutive pairs with the same weight. Write a procedure to generate the Ramanujan numbers. The first such number is 1,729. What are the next five? Exer cise 3.72.   In a similar way to exercise 3.71 generate a stream of all numbers that can be written as the sum of two squares in three dif ferent ways (showing how they can be so written). Streams as signals We began our discussion of streams by describing them as computational analogs of the \u201csignals\u201d in signal-processing systems. In fact, w"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6683008e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e can use streams to model signal-processing systems in a very direct way , representing the values of a signal at successive time intervals as consecutive elements of a stream. For instance, we can implement an integrator  or summer  that, for an input stream x = (xi), an initial value C, and a small increment dt, accumulates the sum and returns the stream of values S = (Si). The following integral  procedure is reminiscent of the \u201cimplicit style\u201d definition of the stream of integers(section 3.5.2 ): (define (integral integrand initial-value dt)     (define int       (cons-stream initial-value                    (add-streams (scale-stream integrand dt)                                 int)))     int)  Figur e 3.32:   The integral  procedure viewed as a signal-processing system. Figure 3.32 is a picture of a signal-processing system that corresponds to the integral  procedure. The input stream is scaled by dt and passed through an adder , whose output is passed back through the same adder . The self-reference "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6684032i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "in the definition of int is reflected in the figure by the feedback loop that connects the output of the adder to one of the inputs. Exer cise 3.73.               v = v0 + (1/C)\u222b0ti dt + R i       Figur e 3.33:   An RC circuit and the associated signal-flow diagram.We can model electrical circuits using streams to represent the values of currents or voltages at a sequence of times. For instance, suppose we have an RC cir cuit consisting of a resistor of resistance R and a capacitor of capacitance C in series. The voltage response v of the circuit to an injected current i is determined by the formula in figure 3.33, whose structure is shown by the accompanying signal-flow diagram. Write a procedure RC that models this circuit. RC should take as inputs the values of R, C, and dt and should return a procedure that takes as inputs a stream representing the current i and an initial value for the capacitor voltage v0 and produces as output the stream of voltages v. For example, you should be able to use RC to model"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6685056
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " an RC circuit with R = 5 ohms, C = 1 farad, and a 0.5-second time step by evaluating (define RC1 (RC 5 1 0.5)) . This defines RC1 as a procedure that takes a stream representing the time sequence of currents and an initial capacitor voltage and produces the output stream of voltages. Exer cise 3.74.   Alyssa P . Hacker is designing a system to process signals coming from physical sensors. One important feature she wishes to produce is a signal that describes the zero crossings  of the input signal. That is, the resulting signal should be + 1 whenever the input signal changes from negative to positive, - 1 whenever the input signal changes from positive to negative, and 0 otherwise. (Assume that the sign of a 0 input is positive.) For example, a typical input signal with its associated zero-crossing signal would be ...1  2  1.5  1  0.5  -0.1  -2  -3  -2  -0.5  0.2  3  4 ......  0  0    0  0    0     -1  0   0   0     0    1  0  0 ... In Alyssa's system, the signal from the sensor is represented as a stream se"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6686080n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "nse-data  and the stream zero-crossings  is the corresponding stream of zero crossings. Alyssa first writes a procedure sign-change-detector  that takes two values as ar guments and compares the signs of the values to produce an appropriate 0, 1, or - 1. She then constructs her zero-crossing stream as follows:(define (make-zero-crossings input-stream last-value)     (cons-stream      (sign-change-detector (stream-car input-stream) last-value)      (make-zero-crossings (stream-cdr input-stream)                           (stream-car input-stream))))     (define zero-crossings (make-zero-crossings sense-data 0))   Alyssa's boss, Eva Lu Ator , walks by and suggests that this program is approximately equivalent to the following one, which uses the generalized version of stream-map  from exercise 3.50: (define zero-crossings     (stream-map sign-change-detector sense-data < expression >))  Complete the program by supplying the indicated < expression >. Exer cise 3.75.   Unfortunately , Alyssa's zero-crossing detect"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6687104o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "or in exercise 3.74 proves to be insuf ficient, because the noisy signal from the sensor leads to spurious zero crossings. Lem E. Tweakit, a hardware specialist, suggests that Alyssa smooth the signal to filter out the noise before extracting the zero crossings. Alyssa takes his advice and decides to extract the zero crossings from the signal constructed by averaging each value of the sense data with the previous value. She explains the problem to her assistant, Louis Reasoner , who attempts to implement the idea, altering Alyssa's program as follows: (define (make-zero-crossings input-stream last-value)     (let ((avpt (/ (+ (stream-car input-stream) last-value) 2)))       (cons-stream (sign-change-detector avpt last-value)                    (make-zero-crossings (stream-cdr input-stream)                                         avpt))))   This does not correctly implement Alyssa's plan. Find the bug that Louis has installed and fix it without changing the structure of the program. (Hint: You will need to inc"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6688128r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "rease the number of ar guments to make-zero- crossings .)Exer cise 3.76.   Eva Lu Ator has a criticism of Louis's approach in exercise 3.75. The program he wrote is not modular , because it intermixes the operation of smoothing with the zero-crossing extraction. For example, the extractor should not have to be changed if Alyssa finds a better way to condition her input signal. Help Louis by writing a procedure smooth  that takes a stream as input and produces a stream in which each element is the average of two successive input stream elements. Then use smooth  as a component to implement the zero-crossing detector in a more modular style. 3.5.4  Str eams and Delayed Evaluation The integral  procedure at the end of the preceding section shows how we can use streams to model signal-processing systems that contain feedback loops. The feedback loop for the adder shown in figure 3.32 is modeled by the fact that integral 's internal stream int is defined in terms of itself: (define int     (cons-stream initial-val"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6689152u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ue                  (add-streams (scale-stream integrand dt)                               int)))   The interpreter's ability to deal with such an implicit definition depends on the delay  that is incorporated into cons-stream . Without this delay , the interpreter could not construct int before evaluating both ar guments to cons-stream , which would require that int already be defined. In general, delay  is crucial for using streams to model signal-processing systems that contain loops. Without delay , our models would have to be formulated so that the inputs to any signal-processing component would be fully evaluated before the output could be produced. This would outlaw loops. Unfortunately , stream models of systems with loops may require uses of delay  beyond the \u201chidden\u201d delay  supplied by cons-stream . For instance, figure 3.34 shows a signal-processing system for solving the differential equation dy/dt = f(y) where f is a given function. The figure shows a mapping component, which applies f to its inp"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6690176u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ut signal, linked in a feedbackloop to an integrator in a manner very similar to that of the analog computer circuits that are actually used to solve such equations. Figur e 3.34:   An \u201canalog computer circuit\u201d that solves the equation dy/dt = f(y). Assuming we are given an initial value y0 for y, we could try to model this system using the procedure (define (solve f y0 dt)     (define y (integral dy y0 dt))     (define dy (stream-map f y))     y)  This procedure does not work, because in the first line of solve  the call to integral  requires that the input dy be defined, which does not happen until the second line of solve . On the other hand, the intent of our definition does make sense, because we can, in principle, begin to generate the y stream without knowing dy. Indeed, integral  and many other stream operations have properties similar to those of cons-stream , in that we can generate part of the answer given only partial information about the ar guments. For integral , the first element of the output"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6691200
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " stream is the specified initial-value . Thus, we can generate the first element of the output stream without evaluating the integrand dy. Once we know the first element of y, the stream-map  in the second line of solve  can begin working to generate the first element of dy, which will produce the next element of y, and so on. To take advantage of this idea, we will redefine integral  to expect the integrand stream to be a delayed ar gument . Integral  will force  the integrand to be evaluated only when it is required to generate more than the first element of the output stream:(define (integral delayed-integrand initial-value dt)     (define int       (cons-stream initial-value                    (let ((integrand (force delayed-integrand)))                      (add-streams (scale-stream integrand dt)                                   int))))     int)  Now we can implement our solve  procedure by delaying the evaluation of dy in the definition of y:71 (define (solve f y0 dt)     (define y (integral (delay dy"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6692224)
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ") y0 dt))     (define dy (stream-map f y))     y)  In general, every caller of integral  must now delay  the integrand argument. We can demonstrate that the solve  procedure works by approximating e \u2248 2.718 by computing the value at y = 1 of the solution to the dif ferential equation dy/dt = y with initial condition y(0) = 1: (stream-ref (solve (lambda (y) y) 1 0.001) 1000)   2.716924 Exer cise 3.77.   The integral  procedure used above was analogous to the \u201cimplicit\u201d definition of the infinite stream of integers in section 3.5.2 . Alternatively , we can give a definition of integral  that is more like integers-starting-from  (also in section 3.5.2 ): (define (integral integrand initial-value dt)     (cons-stream initial-value                  (if (stream-null? integrand)                      the-empty-stream                      (integral (stream-cdr integrand)                                (+ (* dt (stream-car integrand))                                   initial-value)                                dt)))"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6693248)
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ")  When used in systems with loops, this procedure has the same problem as does our original version of integral . Modify the procedure so that it expects the integrand  as a delayed ar gument and hence can be used in the solve  procedure shown above. Exer cise 3.78.    Figur e 3.35:   Signal-flow diagram for the solution to a second-order linear differential equation. Consider the problem of designing a signal-processing system to study the homogeneous second-order linear dif ferential equation The output stream, modeling y, is generated by a network that contains a loop. This is because the value of d2y/dt2 depends upon the values of y and dy/dt and both of these are determined by integrating d2y/dt2. The diagram we would like to encode is shown in figure 3.35. Write a procedure solve- 2nd that takes as ar guments the constants a, b, and dt and the initial values y0 and dy0 for y and dy/dt and generates the stream of successive values of y. Exer cise 3.79.   Generalize the solve-2nd  procedure of exercise 3"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6694272.
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ".78 so that it can be used to solve general second-order dif ferential equations d2y/dt2 = f(dy/dt, y).Exer cise 3.80.   A series RLC cir cuit consists of a resistor , a capacitor , and an inductor connected in series, as shown in figure 3.36. If R, L, and C are the resistance, inductance, and capacitance, then the relations between voltage ( v) and current ( i) for the three components are described by the equations and the circuit connections dictate the relations Combining these equations shows that the state of the circuit (summarized by vC, the voltage across the capacitor , and iL, the current in the inductor) is described by the pair of dif ferential equations The signal-flow diagram representing this system of dif ferential equations is shown in figure 3.37. Figur e 3.36:   A series RLC circuit. Figur e 3.37:   A signal-flow diagram for the solution to a series RLC circuit.Write a procedure RLC that takes as ar guments the parameters R, L, and C of the circuit and the time increment dt. In a manner si"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6695296m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "milar to that of the RC procedure of exercise 3.73, RLC should produce a procedure that takes the initial values of the state variables, vC0 and iL0, and produces a pair (using cons ) of the streams of states vC and iL. Using RLC, generate the pair of streams that models the behavior of a series RLC circuit with R = 1 ohm, C = 0.2 farad, L = 1 henry , dt = 0.1 second, and initial values iL0 = 0 amps and vC0 = 10 volts. Normal-order evaluation The examples in this section illustrate how the explicit use of delay  and force  provides great programming flexibility , but the same examples also show how this can make our programs more complex. Our new integral procedure, for instance, gives us the power to model systems with loops, but we must now remember that integral  should be called with a delayed integrand, and every procedure that uses integral  must be aware of this. In effect, we have created two classes of procedures: ordinary procedures and procedures that take delayed ar guments. In general, creating s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6696320e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "eparate classes of procedures forces us to create separate classes of higher -order procedures as well.72One way to avoid the need for two dif ferent classes of procedures is to make all procedures take delayed ar guments. We could adopt a model of evaluation in which all ar guments to procedures are automatically delayed and ar guments are forced only when they are actually needed (for example, when they are required by a primitive operation). This would transform our language to use normal-order evaluation, which we first described when we introduced the substitution model for evaluation in section 1.1.5 . Converting to normal-order evaluation provides a uniform and elegant way to simplify the use of delayed evaluation, and this would be a natural strategy to adopt if we were concerned only with stream processing. In section 4.2, after we have studied the evaluator , we will see how to transform our language in just this way . Unfortunately , including delays in procedure calls wreaks havoc with our ability"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6697344
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " to design programs that depend on the order of events, such as programs that use assignment, mutate data, or perform input or output. Even the single delay  in cons- stream  can cause great confusion, as illustrated by exercises 3.51 and 3.52. As far as anyone knows, mutability and delayed evaluation do not mix well in programming languages, and devising ways to deal with both of these at once is an active area of research. 3.5.5  Modularity of Functional Pr ograms and Modularity of Objects As we saw in section 3.1.2 , one of the major benefits of introducing assignment is that we can increase the modularity of our systems by encapsulating, or \u201chiding,\u201d parts of the state of a lar ge system within local variables. Stream models can provide an equivalent modularity without the use of assignment. As an illustration, we can reimplement the Monte Carlo estimation of \u03c0, which we examined in section 3.1.2 , from a stream- processing point of view . The key modularity issue was that we wished to hide the internal s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6698368t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tate of a random-number generator from programs that used random numbers. We began with a procedure rand-update , whose successive values furnished our supply of random numbers, and used this to produce a random-number generator:(define rand     (let ((x random-init))       (lambda ()         (set! x (rand-update x))         x)))   In the stream formulation there is no random-number generator per se , just a stream of random numbers produced by successive calls to rand-update : (define random-numbers     (cons-stream random-init                  (stream-map rand-update random-numbers)))   We use this to construct the stream of outcomes of the Ces\u00e0ro experiment performed on consecutive pairs in the random-numbers  stream: (define cesaro-stream     (map-successive-pairs (lambda (r1 r2) (= (gcd r1 r2) 1))                           random-numbers))     (define (map-successive-pairs f s)     (cons-stream      (f (stream-car s) (stream-car (stream-cdr s)))      (map-successive-pairs f (stream-cdr (stream-cdr s)))))"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6699392
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "   The cesaro-stream  is now fed to a monte-carlo  procedure, which produces a stream of estimates of probabilities. The results are then converted into a stream of estimates of \u03c0. This version of the program doesn't need a parameter telling how many trials to perform. Better estimates of \u03c0 (from performing more experiments) are obtained by looking farther into the pi stream: (define (monte-carlo experiment-stream passed failed)     (define (next passed failed)       (cons-stream        (/ passed (+ passed failed))        (monte-carlo         (stream-cdr experiment-stream) passed failed)))    (if (stream-car experiment-stream)         (next (+ passed 1) failed)         (next passed (+ failed 1))))     (define pi     (stream-map (lambda (p) (sqrt (/ 6 p)))                 (monte-carlo cesaro-stream 0 0)))   There is considerable modularity in this approach, because we still can formulate a general monte-carlo  procedure that can deal with arbitrary experiments. Yet there is no assignment or local state. Exer c"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6700416i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ise 3.81.   Exercise 3.6 discussed generalizing the random-number generator to allow one to reset the random-number sequence so as to produce repeatable sequences of \u201crandom\u201d numbers. Produce a stream formulation of this same generator that operates on an input stream of requests to generate  a new random number or to reset  the sequence to a specified value and that produces the desired stream of random numbers. Don't use assignment in your solution. Exer cise 3.82.   Redo exercise 3.5 on Monte Carlo integration in terms of streams. The stream version of estimate-integral  will not have an argument telling how many trials to perform. Instead, it will produce a stream of estimates based on successively more trials. A functional-pr ogramming view of time Let us now return to the issues of objects and state that were raised at the beginning of this chapter and examine them in a new light. We introduced assignment and mutable objects to provide a mechanism for modular construction of programs that model systems "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6701440w
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "with state. We constructed computational objects with local state variables and used assignment to modify these variables. We modeled the temporal behavior of the objects in the world by the temporal behavior of the corresponding computational objects. Now we have seen that streams provide an alternative way to model objects with local state. We can model a changing quantity , such as the local stateof some object, using a stream that represents the time history of successive states. In essence, we represent time explicitly , using streams, so that we decouple time in our simulated world from the sequence of events that take place during evaluation. Indeed, because of the presence of delay  there may be little relation between simulated time in the model and the order of events during the evaluation. In order to contrast these two approaches to modeling, let us reconsider the implementation of a \u201cwithdrawal processor\u201d that monitors the balance in a bank account. In section 3.1.3  we implemented a simplified v"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6702464e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ersion of such a processor: (define (make-simplified-withdraw balance)     (lambda (amount)       (set! balance (- balance amount))       balance))   Calls to make-simplified-withdraw  produce computational objects, each with a local state variable balance  that is decremented by successive calls to the object. The object takes an amount  as an ar gument and returns the new balance. We can imagine the user of a bank account typing a sequence of inputs to such an object and observing the sequence of returned values shown on a display screen. Alternatively , we can model a withdrawal processor as a procedure that takes as input a balance and a stream of amounts to withdraw and produces the stream of successive balances in the account: (define (stream-withdraw balance amount-stream)     (cons-stream      balance      (stream-withdraw (- balance (stream-car amount-stream))                       (stream-cdr amount-stream))))   Stream-withdraw  implements a well-defined mathematical function whose output is fully d"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6703488e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "etermined by its input. Suppose, however , that the input amount-stream  is the stream of successive values typed by the user and that the resulting stream of balances is displayed. Then, from the perspective ofthe user who is typing values and watching results, the stream process has the same behavior as the object created by make-simplified-withdraw . However , with the stream version, there is no assignment, no local state variable, and consequently none of the theoretical dif ficulties that we encountered in section 3.1.3 . Yet the system has state! This is really remarkable. Even though stream-withdraw  implements a well-defined mathematical function whose behavior does not change, the user's perception here is one of interacting with a system that has a changing state. One way to resolve this paradox is to realize that it is the user's temporal existence that imposes state on the system. If the user could step back from the interaction and think in terms of streams of balances rather than individual tra"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6704512n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "nsactions, the system would appear stateless.73 From the point of view of one part of a complex process, the other parts appear to change with time. They have hidden time-varying local state. If we wish to write programs that model this kind of natural decomposition in our world (as we see it from our viewpoint as a part of that world) with structures in our computer , we make computational objects that are not functional \u2013 they must change with time. We model state with local state variables, and we model the changes of state with assignments to those variables. By doing this we make the time of execution of a computation model time in the world that we are part of, and thus we get \u201cobjects\u201d in our computer . Modeling with objects is powerful and intuitive, lar gely because this matches the perception of interacting with a world of which we are part. However , as we've seen repeatedly throughout this chapter , these models raise thorny problems of constraining the order of events and of synchronizing multipl"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6705536e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e processes. The possibility of avoiding these problems has stimulated the development of functional pr ogramming languages , which do not include any provision for assignment or mutable data. In such a language, all procedures implement well-defined mathematical functions of their ar guments, whose behavior does not change. The functional approach is extremely attractive for dealing with concurrent systems.74On the other hand, if we look closely , we can see time-related problems creeping into functional models as well. One particularly troublesome area arises when we wish to design interactive systems, especially ones that model interactions between independent entities. For instance, consider once more the implementation a banking system that permits joint bank accounts. In a conventional system using assignment and objects, we would model the fact that Peter and Paul share an account by having both Peter and Paul send their transaction requests to the same bank-account object, as we saw in section 3.1.3 ."}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6706560
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " From the stream point of view , where there are no \u201cobjects\u201d per se , we have already indicated that a bank account can be modeled as a process that operates on a stream of transaction requests to produce a stream of responses. Accordingly , we could model the fact that Peter and Paul have a joint bank account by mer ging Peter's stream of transaction requests with Paul's stream of requests and feeding the result to the bank-account stream process, as shown in figure 3.38. Figur e 3.38:   A joint bank account, modeled by mer ging two streams of transaction requests. The trouble with this formulation is in the notion of merge. It will not do to merge the two streams by simply taking alternately one request from Peter and one request from Paul. Suppose Paul accesses the account only very rarely . We could hardly force Peter to wait for Paul to access the account before he could issue a second transaction. However such a mer ge is implemented, it must interleave the two transaction streams in some way that is c"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6707584o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "onstrained by \u201creal time\u201d as perceived by Peter and Paul, in the sense that, if Peter and Paul meet, they can agree that certain transactions were processed before the meeting, and other transactions were processed after the meeting.75 This is precisely the same constraint that we had to deal with in section 3.4.1 , where we found the need to introduce explicit synchronization to ensure a \u201ccorrect\u201d order of events in concurrent processing of objects with state. Thus, in an attempt to support the functional style, the need to mer ge inputs from dif ferent agents reintroduces the same problems that the functional style was meant to eliminate.We began this chapter with the goal of building computational models whose structure matches our perception of the real world we are trying to model. We can model the world as a collection of separate, time-bound, interacting objects with state, or we can model the world as a single, timeless, stateless unity . Each view has powerful advantages, but neither view alone is co"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6708608m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "mpletely satisfactory . A grand unification has yet to emer ge.76 52 Physicists sometimes adopt this view by introducing the \u201cworld lines\u201d of particles as a device for reasoning about motion. We've also already mentioned (section 2.2.3 ) that this is the natural way to think about signal-processing systems. We will explore applications of streams to signal processing in section 3.5.3 . 53 Assume that we have a predicate prime?  (e.g., as in section 1.2.6 ) that tests for primality . 54 In the MIT implementation, the-empty-stream  is the same as the empty list '(), and stream- null?  is the same as null? . 55 This should bother you. The fact that we are defining such similar procedures for streams and lists indicates that we are missing some underlying abstraction. Unfortunately , in order to exploit this abstraction, we will need to exert finer control over the process of evaluation than we can at present. We will discuss this point further at the end of section 3.5.4 . In section 4.2, we'll develop a framewo"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6709632r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "rk that unifies lists and streams. 56 Although stream-car  and stream-cdr  can be defined as procedures, cons-stream  must be a special form. If cons-stream  were a procedure, then, according to our model of evaluation, evaluating (cons-stream < a> <b>) would automatically cause < b> to be evaluated, which is precisely what we do not want to happen. For the same reason, delay  must be a special form, though force  can be an ordinary procedure. 57 The numbers shown here do not really appear in the delayed expression. What actually appears is the original expression, in an environment in which the variables are bound to the appropriate numbers. For example, (+ low 1)  with low bound to 10,000 actually appears where 10001  is shown. 58 There are many possible implementations of streams other than the one described in this section. Delayed evaluation, which is the key to making streams practical, was inherent in Algol 60's call-by- name  parameter -passing method. The use of this mechanism to implement streams wa"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6710656s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s first described by Landin (1965). Delayed evaluation for streams was introduced into Lisp by Friedman and W ise (1976). In their implementation, cons  always delays evaluating its ar guments, so that lists automatically behave as streams. The memoizing optimization is also known as call-by-need . The Algol community would refer to our original delayed objects as call-by-name thunks  and to the optimized versions as call-by-need thunks . 59 Exercises such as 3.51 and 3.52 are valuable for testing our understanding of how delay  works. On the other hand, intermixing delayed evaluation with printing \u2013 and, even worse, with assignment \u2013 is extremely confusing, and instructors of courses on computer languages have traditionally tormentedtheir students with examination questions such as the ones in this section. Needless to say , writing programs that depend on such subtleties is odious programming style. Part of the power of stream processing is that it lets us ignore the order in which events actually happen in"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6711680
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " our programs. Unfortunately , this is precisely what we cannot af ford to do in the presence of assignment, which forces us to be concerned with time and change. 60 Eratosthenes, a third-century B.C. Alexandrian Greek philosopher , is famous for giving the first accurate estimate of the circumference of the Earth, which he computed by observing shadows cast at noon on the day of the summer solstice. Eratosthenes's sieve method, although ancient, has formed the basis for special-purpose hardware \u201csieves\u201d that, until recently , were the most powerful tools in existence for locating lar ge primes. Since the 70s, however , these methods have been superseded by outgrowths of the probabilistic techniques discussed in section 1.2.6 . 61 We have named these figures after Peter Henderson, who was the first person to show us diagrams of this sort as a way of thinking about stream processing. Each solid line represents a stream of values being transmitted. The dashed line from the car to the cons  and the filter  indic"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6712704a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ates that this is a single value rather than a stream. 62 This uses the generalized version of stream-map  from exercise 3.50. 63 This last point is very subtle and relies on the fact that pn+1< pn2. (Here, pk denotes the kth prime.) Estimates such as these are very dif ficult to establish. The ancient proof by Euclid that there are an infinite number of primes shows that pn+1< p1p2\u00b7\u00b7\u00b7 pn + 1, and no substantially better result was proved until 1851, when the Russian mathematician P . L. Chebyshev established that pn+1< 2pn for all n. This result, originally conjectured in 1845, is known as Bertrand's hypothesis . A proof can be found in section 22.3 of Hardy and W right 1960. 64 This exercise shows how call-by-need is closely related to ordinary memoization as described in exercise 3.27. In that exercise, we used assignment to explicitly construct a local table. Our call-by- need stream optimization ef fectively constructs such a table automatically , storing values in the previously forced parts of the stre"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6713728a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "am. 65 We can't use let to bind the local variable guesses , because the value of guesses  depends on guesses  itself. Exercise 3.63 addresses why we want a local variable here. 66 As in section 2.2.3 , we represent a pair of integers as a list rather than a Lisp pair . 67 See exercise 3.68 for some insight into why we chose this decomposition. 68 The precise statement of the required property on the order of combination is as follows: There should be a function f of two ar guments such that the pair corresponding to element i of the first stream and element j of the second stream will appear as element number f(i,j) of the output stream. The trick of using interleave  to accomplish this was shown to us by David T urner , who employed it in the language KRC (T urner 1981). 69 We will require that the weighting function be such that the weight of a pair increases as we move out along a row or down along a column of the array of pairs.70 To quote from G. H. Hardy's obituary of Ramanujan (Hardy 1921): \u201cIt was Mr"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6714752
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " . Littlewood (I believe) who remarked that `every positive integer was one of his friends.' I remember once going to see him when he was lying ill at Putney . I had ridden in taxi-cab No. 1729, and remarked that the number seemed to me a rather dull one, and that I hoped it was not an unfavorable omen. `No,' he replied, `it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two dif ferent ways.' \u201d The trick of using weighted pairs to generate the Ramanujan numbers was shown to us by Charles Leiserson. 71 This procedure is not guaranteed to work in all Scheme implementations, although for any implementation there is a simple variation that will work. The problem has to do with subtle differences in the ways that Scheme implementations handle internal definitions. (See section 4.1.6 .) 72 This is a small reflection, in Lisp, of the dif ficulties that conventional strongly typed languages such as Pascal have in coping with higher -order procedures. In such languages, "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6715776t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "the programmer must specify the data types of the ar guments and the result of each procedure: number , logical value, sequence, and so on. Consequently , we could not express an abstraction such as \u201cmap a given procedure proc  over all the elements in a sequence\u201d by a single higher -order procedure such as stream-map . Rather , we would need a dif ferent mapping procedure for each dif ferent combination of argument and result data types that might be specified for a proc . Maintaining a practical notion of \u201cdata type\u201d in the presence of higher -order procedures raises many dif ficult issues. One way of dealing with this problem is illustrated by the language ML  (Gordon, Milner , and W adsworth 1979), whose \u201cpolymorphic data types\u201d include templates for higher -order transformations between data types. Moreover , data types for most procedures in ML are never explicitly declared by the programmer . Instead, ML includes a type-infer encing  mechanism that uses information in the environment to deduce the data"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6716800
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " types for newly defined procedures. 73 Similarly in physics, when we observe a moving particle, we say that the position (state) of the particle is changing. However , from the perspective of the particle's world line in space-time there is no change involved. 74 John Backus, the inventor of Fortran, gave high visibility to functional programming when he was awarded the ACM T uring award in 1978. His acceptance speech (Backus 1978) strongly advocated the functional approach. A good overview of functional programming is given in Henderson 1980 and in Darlington, Henderson, and T urner 1982. 75 Observe that, for any two streams, there is in general more than one acceptable order of interleaving. Thus, technically , \u201cmer ge\u201d is a relation rather than a function \u2013 the answer is not a deterministic function of the inputs. We already mentioned (footnote 39) that nondeterminism is essential when dealing with concurrency . The mer ge relation illustrates the same essential nondeterminism, from the functional perspec"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6717824t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tive. In section 4.3, we will look at nondeterminism from yet another point of view . 76 The object model approximates the world by dividing it into separate pieces. The functional model does not modularize along object boundaries. The object model is useful when the unshared state of the \u201cobjects\u201d is much lar ger than the state that they share. An example of a place where the object viewpoint fails is quantum mechanics, where thinking of things as individual particles leads to paradoxes and confusions. Unifying the object view with the functional view may have little to do with programming, but rather with fundamental epistemological issues.Chapter 4 Metalinguistic Abstraction ... It's in words that the magic is \u2013 Abracadabra, Open Sesame, and the rest \u2013 but the magic words in one story aren't magical in the next. The real magic is to understand which words work, and when, and for what; the trick is to learn the trick.   ... And those words are made from the letters of our alphabet: a couple-dozen squiggles "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6718848w
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "we can draw with the pen. This is the key! And the treasure, too, if we can only get our hands on it! It's as if \u2013 as if the key to the treasure is the treasure! John Barth, Chimera In our study of program design, we have seen that expert programmers control the complexity of their designs with the same general techniques used by designers of all complex systems. They combine primitive elements to form compound objects, they abstract compound objects to form higher - level building blocks, and they preserve modularity by adopting appropriate large-scale views of system structure. In illustrating these techniques, we have used Lisp as a language for describing processes and for constructing computational data objects and processes to model complex phenomena in the real world. However , as we confront increasingly complex problems, we will find that Lisp, or indeed any fixed programming language, is not sufficient for our needs. We must constantly turn to new languages in order to express our ideas more ef fect"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6719872i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ively . Establishing new languages is a powerful strategy for controlling complexity in engineering design; we can often enhance our ability to deal with a complex problem by adopting a new language that enables us to describe (and hence to think about) the problem in a dif ferent way , using primitives, means of combination, and means of abstraction that are particularly well suited to the problem at hand.1 Programming is endowed with a multitude of languages. There are physical languages, such as the machine languages for particular computers. These languages are concerned with the representation of data and control in termsof individual bits of storage and primitive machine instructions. The machine-language programmer is concerned with using the given hardware to erect systems and utilities for the ef ficient implementation of resource- limited computations. High-level languages, erected on a machine-language substrate, hide concerns about the representation of data as collections of bits and the represen"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6720896t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "tation of programs as sequences of primitive instructions. These languages have means of combination and abstraction, such as procedure definition, that are appropriate to the lar ger-scale organization of systems. Metalinguistic abstraction  \u2013 establishing new languages \u2013 plays an important role in all branches of engineering design. It is particularly important to computer programming, because in programming not only can we formulate new languages but we can also implement these languages by constructing evaluators. An evaluator  (or interpr eter) for a programming language is a procedure that, when applied to an expression of the language, performs the actions required to evaluate that expression. It is no exaggeration to regard this as the most fundamental idea in programming: The evaluator , which determines the meaning of expressions in a programming language, is just another program. To appreciate this point is to change our images of ourselves as programmers. We come to see ourselves as designers of l"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6721920a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "anguages, rather than only users of languages designed by others. In fact, we can regard almost any program as the evaluator for some language. For instance, the polynomial manipulation system of section 2.5.3 embodies the rules of polynomial arithmetic and implements them in terms of operations on list-structured data. If we augment this system with procedures to read and print polynomial expressions, we have the core of a special-purpose language for dealing with problems in symbolic mathematics. The digital-logic simulator of section 3.3.4  and the constraint propagator of section 3.3.5  are legitimate languages in their own right, each with its own primitives, means of combination, and means of abstraction. Seen from this perspective, the technology for coping with lar ge-scalecomputer systems mer ges with the technology for building new computer languages, and computer science itself becomes no more (and no less) than the discipline of constructing appropriate descriptive languages. We now embark on a to"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6722944u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ur of the technology by which languages are established in terms of other languages. In this chapter we shall use Lisp as a base, implementing evaluators as Lisp procedures. Lisp is particularly well suited to this task, because of its ability to represent and manipulate symbolic expressions. We will take the first step in understanding how languages are implemented by building an evaluator for Lisp itself. The language implemented by our evaluator will be a subset of the Scheme dialect of Lisp that we use in this book. Although the evaluator described in this chapter is written for a particular dialect of Lisp, it contains the essential structure of an evaluator for any expression-oriented language designed for writing programs for a sequential machine. (In fact, most language processors contain, deep within them, a little \u201cLisp\u201d evaluator .) The evaluator has been simplified for the purposes of illustration and discussion, and some features have been left out that would be important to include in a producti"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6723968o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "on-quality Lisp system. Nevertheless, this simple evaluator is adequate to execute most of the programs in this book.2 An important advantage of making the evaluator accessible as a Lisp program is that we can implement alternative evaluation rules by describing these as modifications to the evaluator program. One place where we can use this power to good ef fect is to gain extra control over the ways in which computational models embody the notion of time, which was so central to the discussion in chapter 3. There, we mitigated some of the complexities of state and assignment by using streams to decouple the representation of time in the world from time in the computer . Our stream programs, however , were sometimes cumbersome, because they were constrained by the applicative-order evaluation of Scheme. In section 4.2, we'll change the underlying language to provide for a more elegant approach, by modifying the evaluator to provide for normal-or der evaluation . Section 4.3 implements a more ambitious lingui"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6724992s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "stic change, whereby expressions have many values, rather than just a single value. In this language of nondeterministic computing , it is natural to express processesthat generate all possible values for expressions and then search for those values that satisfy certain constraints. In terms of models of computation and time, this is like having time branch into a set of \u201cpossible futures\u201d and then searching for appropriate time lines. With our nondeterministic evaluator , keeping track of multiple values and performing searches are handled automatically by the underlying mechanism of the language. In section 4.4 we implement a logic-pr ogramming  language in which knowledge is expressed in terms of relations, rather than in terms of computations with inputs and outputs. Even though this makes the language drastically dif ferent from Lisp, or indeed from any conventional language, we will see that the logic-programming evaluator shares the essential structure of the Lisp evaluator . 1 The same idea is pervasi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6726016v
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ve throughout all of engineering. For example, electrical engineers use many dif ferent languages for describing circuits. Two of these are the language of electrical networks and the language of electrical systems . The network language emphasizes the physical modeling of devices in terms of discrete electrical elements. The primitive objects of the network language are primitive electrical components such as resistors, capacitors, inductors, and transistors, which are characterized in terms of physical variables called voltage and current. When describing circuits in the network language, the engineer is concerned with the physical characteristics of a design. In contrast, the primitive objects of the system language are signal-processing modules such as filters and amplifiers. Only the functional behavior of the modules is relevant, and signals are manipulated without concern for their physical realization as voltages and currents. The system language is erected on the network language, in the sense that t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6727040h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "he elements of signal-processing systems are constructed from electrical networks. Here, however , the concerns are with the lar ge-scale organization of electrical devices to solve a given application problem; the physical feasibility of the parts is assumed. This layered collection of languages is another example of the stratified design technique illustrated by the picture language of section 2.2.4 . 2 The most important features that our evaluator leaves out are mechanisms for handling errors and supporting debugging. For a more extensive discussion of evaluators, see Friedman, W and, and Haynes 1992, which gives an exposition of programming languages that proceeds via a sequence of evaluators written in Scheme.4.1  The Metacircular Evaluator Our evaluator for Lisp will be implemented as a Lisp program. It may seem circular to think about evaluating Lisp programs using an evaluator that is itself implemented in Lisp. However , evaluation is a process, so it is appropriate to describe the evaluation proces"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6728064s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s using Lisp, which, after all, is our tool for describing processes.3 An evaluator that is written in the same language that it evaluates is said to be metacir cular . The metacircular evaluator is essentially a Scheme formulation of the environment model of evaluation described in section 3.2. Recall that the model has two basic parts: 1. To evaluate a combination (a compound expression other than a special form), evaluate the subexpressions and then apply the value of the operator subexpression to the values of the operand subexpressions. 2. To apply a compound procedure to a set of ar guments, evaluate the body of the procedure in a new environment. To construct this environment, extend the environment part of the procedure object by a frame in which the formal parameters of the procedure are bound to the ar guments to which the procedure is applied. These two rules describe the essence of the evaluation process, a basic cycle in which expressions to be evaluated in environments are reduced to procedures "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6729088t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "to be applied to ar guments, which in turn are reduced to new expressions to be evaluated in new environments, and so on, until we get down to symbols, whose values are looked up in the environment, and to primitive procedures, which are applied directly (see figure 4.1).4 This evaluation cycle will be embodied by the interplay between the two critical procedures in the evaluator , eval  and apply , which are described in section 4.1.1  (see figure 4.1). The implementation of the evaluator will depend upon procedures that define the syntax  of the expressions to be evaluated. We will use dataabstraction to make the evaluator independent of the representation of the language. For example, rather than committing to a choice that an assignment is to be represented by a list beginning with the symbol set!  we use an abstract predicate assignment?  to test for an assignment, and we use abstract selectors assignment-variable  and assignment-value  to access the parts of an assignment. Implementation of expressions "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6730112w
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "will be described in detail in section 4.1.2 . There are also operations, described in section 4.1.3 , that specify the representation of procedures and environments. For example, make-procedure  constructs compound procedures, lookup-variable-value  accesses the values of variables, and apply-primitive-procedure  applies a primitive procedure to a given list of arguments. 4.1.1  The Cor e of the Evaluator Figur e 4.1:   The eval -apply  cycle exposes the essence of a computer language. The evaluation process can be described as the interplay between two procedures: eval  and apply . Eval Eval  takes as ar guments an expression and an environment. It classifies the expression and directs its evaluation. Eval  is structured as a case analysis of the syntactic type of the expression to be evaluated. In order to keep the procedure general, we express the determination of the type of an expression abstractly , making no commitment to any particular representation for the various types of expressions. Each type of"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6731136
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " expression has a predicate that tests for it and an abstract means for selecting its parts.This abstract syntax  makes it easy to see how we can change the syntax of the language by using the same evaluator , but with a dif ferent collection of syntax procedures. Primitive expr essions For self-evaluating expressions, such as numbers, eval  returns the expression itself. Eval  must look up variables in the environment to find their values. Special forms For quoted expressions, eval  returns the expression that was quoted. An assignment to (or a definition of) a variable must recursively call eval  to compute the new value to be associated with the variable. The environment must be modified to change (or create) the binding of the variable. An if expression requires special processing of its parts, so as to evaluate the consequent if the predicate is true, and otherwise to evaluate the alternative. A lambda  expression must be transformed into an applicable procedure by packaging together the parameters and b"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6732160o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ody specified by the lambda  expression with the environment of the evaluation. A begin  expression requires evaluating its sequence of expressions in the order in which they appear . A case analysis ( cond ) is transformed into a nest of if expressions and then evaluated. Combinations For a procedure application, eval  must recursively evaluate the operator part and the operands of the combination. The resultingprocedure and ar guments are passed to apply , which handles the actual procedure application. Here is the definition of eval : (define (eval exp env)     (cond ((self-evaluating? exp) exp)           ((variable? exp) (lookup-variable-value exp env))           ((quoted? exp) (text-of-quotation exp))           ((assignment? exp) (eval-assignment exp env))           ((definition? exp) (eval-definition exp env))           ((if? exp) (eval-if exp env))           ((lambda? exp)            (make-procedure (lambda-parameters exp)                            (lambda-body exp)                            env))   "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6733184
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "        ((begin? exp)            (eval-sequence (begin-actions exp) env))           ((cond? exp) (eval (cond->if exp) env))           ((application? exp)            (apply (eval (operator exp) env)                   (list-of-values (operands exp) env)))           (else            (error \"Unknown expression type -- EVAL\" exp))))   For clarity , eval  has been implemented as a case analysis using cond . The disadvantage of this is that our procedure handles only a few distinguishable types of expressions, and no new ones can be defined without editing the definition of eval . In most Lisp implementations, dispatching on the type of an expression is done in a data-directed style. This allows a user to add new types of expressions that eval  can distinguish, without modifying the definition of eval  itself. (See exercise 4.3.) ApplyApply  takes two ar guments, a procedure and a list of ar guments to which the procedure should be applied. Apply  classifies procedures into two kinds: It calls apply-primitive-proced"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6734208u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ure  to apply primitives; it applies compound procedures by sequentially evaluating the expressions that make up the body of the procedure. The environment for the evaluation of the body of a compound procedure is constructed by extending the base environment carried by the procedure to include a frame that binds the parameters of the procedure to the ar guments to which the procedure is to be applied. Here is the definition of apply : (define (apply procedure arguments)     (cond ((primitive-procedure? procedure)            (apply-primitive-procedure procedure arguments))           ((compound-procedure? procedure)            (eval-sequence              (procedure-body procedure)              (extend-environment                (procedure-parameters procedure)                arguments                (procedure-environment procedure))))           (else            (error             \"Unknown procedure type -- APPLY\" procedure))))   Procedur e arguments When eval  processes a procedure application, it uses list-o"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6735232f
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "f-values  to produce the list of ar guments to which the procedure is to be applied. List- of-values  takes as an ar gument the operands of the combination. It evaluates each operand and returns a list of the corresponding values:5 (define (list-of-values exps env)     (if (no-operands? exps)         '()         (cons (eval (first-operand exps) env)               (list-of-values (rest-operands exps) env))))  Conditionals Eval-if  evaluates the predicate part of an if expression in the given environment. If the result is true, eval-if  evaluates the consequent, otherwise it evaluates the alternative: (define (eval-if exp env)     (if (true? (eval (if-predicate exp) env))         (eval (if-consequent exp) env)         (eval (if-alternative exp) env)))   The use of true?  in eval-if  highlights the issue of the connection between an implemented language and an implementation language. The if- predicate  is evaluated in the language being implemented and thus yields a value in that language. The interpreter predi"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6736256c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cate true?  translates that value into a value that can be tested by the if in the implementation language: The metacircular representation of truth might not be the same as that of the underlying Scheme.6 Sequences Eval-sequence  is used by apply  to evaluate the sequence of expressions in a procedure body and by eval  to evaluate the sequence of expressions in a begin  expression. It takes as ar guments a sequence of expressions and an environment, and evaluates the expressions in the order in which they occur . The value returned is the value of the final expression. (define (eval-sequence exps env)     (cond ((last-exp? exps) (eval (first-exp exps) env))           (else (eval (first-exp exps) env)                 (eval-sequence (rest-exps exps) env))))   Assignments and definitions The following procedure handles assignments to variables. It calls eval  to find the value to be assigned and transmits the variable and the resultingvalue to set-variable-value!  to be installed in the designated environment. "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6737280(
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "(define (eval-assignment exp env)     (set-variable-value! (assignment-variable exp)                          (eval (assignment-value exp) env)                          env)     'ok)  Definitions of variables are handled in a similar manner .7 (define (eval-definition exp env)     (define-variable! (definition-variable exp)                       (eval (definition-value exp) env)                       env)     'ok)  We have chosen here to return the symbol ok as the value of an assignment or a definition.8 Exer cise 4.1.   Notice that we cannot tell whether the metacircular evaluator evaluates operands from left to right or from right to left. Its evaluation order is inherited from the underlying Lisp: If the ar guments to cons  in list-of-values  are evaluated from left to right, then list-of-values  will evaluate operands from left to right; and if the ar guments to cons  are evaluated from right to left, then list-of-values  will evaluate operands from right to left. Write a version of list-of-values  that "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6738304e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "evaluates operands from left to right regardless of the order of evaluation in the underlying Lisp. Also write a version of list-of-values  that evaluates operands from right to left. 4.1.2  Repr esenting Expr essions The evaluator is reminiscent of the symbolic dif ferentiation program discussed in section 2.3.2 . Both programs operate on symbolic expressions. In both programs, the result of operating on a compound expression is determined by operating recursively on the pieces of the expression andcombining the results in a way that depends on the type of the expression. In both programs we used data abstraction to decouple the general rules of operation from the details of how expressions are represented. In the differentiation program this meant that the same dif ferentiation procedure could deal with algebraic expressions in prefix form, in infix form, or in some other form. For the evaluator , this means that the syntax of the language being evaluated is determined solely by the procedures that classify"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6739328
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " and extract pieces of expressions. Here is the specification of the syntax of our language: \u00a4 The only self-evaluating items are numbers and strings: (define (self-evaluating? exp)     (cond ((number? exp) true)           ((string? exp) true)           (else false)))   \u00a4 Variables are represented by symbols: (define (variable? exp) (symbol? exp))   \u00a4 Quotations have the form (quote < text-of-quotation >):9 (define (quoted? exp)     (tagged-list? exp 'quote))     (define (text-of-quotation exp) (cadr exp))   Quoted?  is defined in terms of the procedure tagged-list? , which identifies lists beginning with a designated symbol: (define (tagged-list? exp tag)     (if (pair? exp)         (eq? (car exp) tag)         false))   \u00a4 Assignments have the form (set! <var> <value>):(define (assignment? exp)     (tagged-list? exp 'set!))   (define (assignment-variable exp) (cadr exp))   (define (assignment-value exp) (caddr exp))   \u00a4 Definitions have the form (define < var> <value>)  or the form (define (< var> <parameter1"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6740352>
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "> ... <parametern>)    <body>)  The latter form (standard procedure definition) is syntactic sugar for (define < var>    (lambda (< parameter1> ... <parametern>)      <body>))  The corresponding syntax procedures are the following: (define (definition? exp)     (tagged-list? exp 'define))   (define (definition-variable exp)     (if (symbol? (cadr exp))         (cadr exp)         (caadr exp)))   (define (definition-value exp)     (if (symbol? (cadr exp))         (caddr exp)         (make-lambda (cdadr exp)   ; formal parameters                      (cddr exp)))) ; body  \u00a4 Lambda  expressions are lists that begin with the symbol lambda : (define (lambda? exp) (tagged-list? exp 'lambda))   (define (lambda-parameters exp) (cadr exp))  (define (lambda-body exp) (cddr exp))   We also provide a constructor for lambda  expressions, which is used by definition-value , above: (define (make-lambda parameters body)     (cons 'lambda (cons parameters body)))   \u00a4 Conditionals begin with if and have a predicate, a consequen"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6741376t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "t, and an (optional) alternative. If the expression has no alternative part, we provide false  as the alternative.10 (define (if? exp) (tagged-list? exp 'if))   (define (if-predicate exp) (cadr exp))   (define (if-consequent exp) (caddr exp))   (define (if-alternative exp)     (if (not (null? (cdddr exp)))         (cadddr exp)         'false))   We also provide a constructor for if expressions, to be used by cond->if  to transform cond  expressions into if expressions: (define (make-if predicate consequent alternative)     (list 'if predicate consequent alternative))   \u00a4 Begin  packages a sequence of expressions into a single expression. We include syntax operations on begin  expressions to extract the actual sequence from the begin  expression, as well as selectors that return the first expression and the rest of the expressions in the sequence.11 (define (begin? exp) (tagged-list? exp 'begin))   (define (begin-actions exp) (cdr exp))   (define (last-exp? seq) (null? (cdr seq)))   (define (first-exp seq) (ca"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6742400r
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "r seq))   (define (rest-exps seq) (cdr seq))  We also include a constructor sequence->exp  (for use by cond->if ) that transforms a sequence into a single expression, using begin  if necessary: (define (sequence->exp seq)     (cond ((null? seq) seq)           ((last-exp? seq) (first-exp seq))           (else (make-begin seq))))   (define (make-begin seq) (cons 'begin seq))   \u00a4 A procedure application is any compound expression that is not one of the above expression types. The car of the expression is the operator , and the cdr is the list of operands: (define (application? exp) (pair? exp))   (define (operator exp) (car exp))   (define (operands exp) (cdr exp))   (define (no-operands? ops) (null? ops))   (define (first-operand ops) (car ops))   (define (rest-operands ops) (cdr ops))   Derived expr essions Some special forms in our language can be defined in terms of expressions involving other special forms, rather than being implemented directly . One example is cond , which can be implemented as a nest of "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6743424i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "if expressions. For example, we can reduce the problem of evaluating the expression (cond ((> x 0) x)         ((= x 0) (display 'zero) 0)         (else (- x)))   to the problem of evaluating the following expression involving if and begin  expressions: (if (> x 0)       x      (if (= x 0)           (begin (display 'zero)                 0)           (- x)))   Implementing the evaluation of cond  in this way simplifies the evaluator because it reduces the number of special forms for which the evaluation process must be explicitly specified. We include syntax procedures that extract the parts of a cond  expression, and a procedure cond->if  that transforms cond  expressions into if expressions. A case analysis begins with cond  and has a list of predicate- action clauses. A clause is an else  clause if its predicate is the symbol else .12 (define (cond? exp) (tagged-list? exp 'cond))   (define (cond-clauses exp) (cdr exp))   (define (cond-else-clause? clause)     (eq? (cond-predicate clause) 'else))   (define ("}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6744448c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cond-predicate clause) (car clause))   (define (cond-actions clause) (cdr clause))   (define (cond->if exp)     (expand-clauses (cond-clauses exp)))     (define (expand-clauses clauses)     (if (null? clauses)         'false                          ; no else clause        (let ((first (car clauses))               (rest (cdr clauses)))           (if (cond-else-clause? first)               (if (null? rest)                   (sequence->exp (cond-actions first))                   (error \"ELSE clause isn't last -- COND->IF\"                          clauses))               (make-if (cond-predicate first)                        (sequence->exp (cond-actions first))                        (expand-clauses rest))))))   Expressions (such as cond ) that we choose to implement as syntactic transformations are called derived expr essions . Let expressions are alsoderived expressions (see exercise 4.6).13 Exer cise 4.2.   Louis Reasoner plans to reorder the cond  clauses in eval  so that the clause for procedure application"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6745472s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "s appears before the clause for assignments. He ar gues that this will make the interpreter more ef ficient: Since programs usually contain more applications than assignments, definitions, and so on, his modified eval  will usually check fewer clauses than the original eval  before identifying the type of an expression. a. What is wrong with Louis's plan? (Hint: What will Louis's evaluator do with the expression (define x 3) ?) b. Louis is upset that his plan didn't work. He is willing to go to any lengths to make his evaluator recognize procedure applications before it checks for most other kinds of expressions. Help him by changing the syntax of the evaluated language so that procedure applications start with call . For example, instead of (factorial 3)  we will now have to write (call factorial 3)  and instead of (+ 1 2)  we will have to write (call + 1 2) . Exer cise 4.3.   Rewrite eval  so that the dispatch is done in data-directed style. Compare this with the data-directed dif ferentiation procedure of "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6746496e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "exercise 2.73. (You may use the car of a compound expression as the type of the expression, as is appropriate for the syntax implemented in this section.) . Exer cise 4.4.   Recall the definitions of the special forms and and or from chapter 1: and: The expressions are evaluated from left to right. If any expression evaluates to false, false is returned; any remaining expressions 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 true is returned. or: The expressions are evaluated from left to right. If any expression evaluates to a true value, that value is returned; any remaining expressions are not evaluated. If all expressions evaluate to false, or if there are no expressions, then false is returned.Install and and or as new special forms for the evaluator by defining appropriate syntax procedures and evaluation procedures eval-and  and eval-or . Alternatively , show how to implement and and or as derived expres"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6747520s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "sions. Exer cise 4.5.   Scheme allows an additional syntax for cond  clauses, (<test> => <recipient >). If <test> evaluates to a true value, then <recipient > is evaluated. Its value must be a procedure of one ar gument; this procedure is then invoked on the value of the < test>, and the result is returned as the value of the cond  expression. For example (cond ((assoc 'b '((a 1) (b 2))) => cadr)         (else false))   returns 2. Modify the handling of cond  so that it supports this extended syntax. Exer cise 4.6.   Let expressions are derived expressions, because (let ((< var1> <exp1>) ... (<varn> <expn>))    <body>)  is equivalent to ((lambda (< var1> ... <varn>)     <body>)   <exp1>   \u22ee   <expn>)  Implement a syntactic transformation let->combination  that reduces evaluating let expressions to evaluating combinations of the type shown above, and add the appropriate clause to eval  to handle let expressions. Exer cise 4.7.   Let*  is similar to let, except that the bindings of the let variables are perform"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6748544e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ed sequentially from left to right, and each binding is made in an environment in which all of the preceding bindings are visible. For example(let* ((x 3)          (y (+ x 2))          (z (+ x y 5)))     (* x z))   returns 39. Explain how a let*  expression can be rewritten as a set of nested let expressions, and write a procedure let*->nested-lets  that performs this transformation. If we have already implemented let (exercise 4.6) and we want to extend the evaluator to handle let* , is it sufficient to add a clause to eval  whose action is (eval (let*->nested-lets exp) env)   or must we explicitly expand let*  in terms of non-derived expressions? Exer cise 4.8.   \u201cNamed let\u201d is a variant of let that has the form (let <var> <bindings > <body>)  The < bindings > and < body > are just as in ordinary let, except that < var> is bound within < body > to a procedure whose body is < body > and whose parameters are the variables in the < bindings >. Thus, one can repeatedly execute the < body > by invoking the proce"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6749568d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "dure named < var>. For example, the iterative Fibonacci procedure (section 1.2.2 ) can be rewritten using named let as follows: (define (fib n)     (let fib-iter ((a 1)                    (b 0)                    (count n))       (if (= count 0)           b           (fib-iter (+ a b) a (- count 1)))))   Modify let->combination  of exercise 4.6 to also support named let. Exer cise 4.9.   Many languages support a variety of iteration constructs, such as do, for, while , and until . In Scheme, iterative processes can beexpressed in terms of ordinary procedure calls, so special iteration constructs provide no essential gain in computational power . On the other hand, such constructs are often convenient. Design some iteration constructs, give examples of their use, and show how to implement them as derived expressions. Exer cise 4.10.   By using data abstraction, we were able to write an eval procedure that is independent of the particular syntax of the language to be evaluated. To illustrate this, design and im"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6750592p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "plement a new syntax for Scheme by modifying the procedures in this section, without changing eval  or apply . 4.1.3  Evaluator Data Structur es In addition to defining the external syntax of expressions, the evaluator implementation must also define the data structures that the evaluator manipulates internally , as part of the execution of a program, such as the representation of procedures and environments and the representation of true and false. Testing of pr edicates For conditionals, we accept anything to be true that is not the explicit false object. (define (true? x)     (not (eq? x false)))   (define (false? x)     (eq? x false))   Repr esenting pr ocedur es To handle primitives, we assume that we have available the following procedures: (apply-primitive-procedure < proc> <args>)  applies the given primitive procedure to the ar gument values in the list<args> and returns the result of the application. (primitive-procedure? < proc>)  tests whether < proc> is a primitive procedure. These mechanisms for"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6751616
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " handling primitives are further described in section 4.1.4 . Compound procedures are constructed from parameters, procedure bodies, and environments using the constructor make-procedure : (define (make-procedure parameters body env)     (list 'procedure parameters body env))   (define (compound-procedure? p)     (tagged-list? p 'procedure))   (define (procedure-parameters p) (cadr p))   (define (procedure-body p) (caddr p))   (define (procedure-environment p) (cadddr p))   Operations on Envir onments The evaluator needs operations for manipulating environments. As explained in section 3.2, an environment is a sequence of frames, where each frame is a table of bindings that associate variables with their corresponding values. We use the following operations for manipulating environments: (lookup-variable-value < var> <env>)  returns the value that is bound to the symbol < var> in the environment <env>, or signals an error if the variable is unbound. (extend-environment < variables > <values> <base-env >)  ret"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6752640u
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "urns a new environment, consisting of a new frame in which the symbols in the list < variables > are bound to the corresponding elements in the list < values >, where the enclosing environment is the environment < base-env >.(define-variable! < var> <value> <env>)  adds to the first frame in the environment < env> a new binding that associates the variable < var> with the value < value >. (set-variable-value! < var> <value> <env>)  changes the binding of the variable < var> in the environment < env> so that the variable is now bound to the value < value >, or signals an error if the variable is unbound. To implement these operations we represent an environment as a list of frames. The enclosing environment of an environment is the cdr of the list. The empty environment is simply the empty list. (define (enclosing-environment env) (cdr env))   (define (first-frame env) (car env))   (define the-empty-environment '())   Each frame of an environment is represented as a pair of lists: a list of the variables bound"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6753664
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " in that frame and a list of the associated values.14 (define (make-frame variables values)     (cons variables values))   (define (frame-variables frame) (car frame))   (define (frame-values frame) (cdr frame))   (define (add-binding-to-frame! var val frame)     (set-car! frame (cons var (car frame)))     (set-cdr! frame (cons val (cdr frame))))   To extend an environment by a new frame that associates variables with values, we make a frame consisting of the list of variables and the list of values, and we adjoin this to the environment. We signal an error if the number of variables does not match the number of values. (define (extend-environment vars vals base-env)     (if (= (length vars) (length vals))         (cons (make-frame vars vals) base-env)         (if (< (length vars) (length vals))            (error \"Too many arguments supplied\" vars vals)             (error \"Too few arguments supplied\" vars vals))))   To look up a variable in an environment, we scan the list of variables in the first frame. If "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6754688w
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "we find the desired variable, we return the corresponding element in the list of values. If we do not find the variable in the current frame, we search the enclosing environment, and so on. If we reach the empty environment, we signal an \u201cunbound variable\u201d error . (define (lookup-variable-value var env)     (define (env-loop env)       (define (scan vars vals)         (cond ((null? vars)                (env-loop (enclosing-environment env)))               ((eq? var (car vars))                (car vals))               (else (scan (cdr vars) (cdr vals)))))       (if (eq? env the-empty-environment)           (error \"Unbound variable\" var)           (let ((frame (first-frame env)))             (scan (frame-variables frame)                   (frame-values frame)))))     (env-loop env))   To set a variable to a new value in a specified environment, we scan for the variable, just as in lookup-variable-value , and change the corresponding value when we find it. (define (set-variable-value! var val env)     (define (e"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6755712n
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "nv-loop env)       (define (scan vars vals)         (cond ((null? vars)                (env-loop (enclosing-environment env)))               ((eq? var (car vars))                (set-car! vals val))               (else (scan (cdr vars) (cdr vals)))))       (if (eq? env the-empty-environment)           (error \"Unbound variable -- SET!\" var)          (let ((frame (first-frame env)))             (scan (frame-variables frame)                   (frame-values frame)))))     (env-loop env))   To define a variable, we search the first frame for a binding for the variable, and change the binding if it exists (just as in set-variable-value! ). If no such binding exists, we adjoin one to the first frame. (define (define-variable! var val env)     (let ((frame (first-frame env)))       (define (scan vars vals)         (cond ((null? vars)                (add-binding-to-frame! var val frame))               ((eq? var (car vars))                (set-car! vals val))               (else (scan (cdr vars) (cdr vals)))))       (s"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6756736c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "can (frame-variables frame)             (frame-values frame))))   The method described here is only one of many plausible ways to represent environments. Since we used data abstraction to isolate the rest of the evaluator from the detailed choice of representation, we could change the environment representation if we wanted to. (See exercise 4.11.) In a production-quality Lisp system, the speed of the evaluator's environment operations \u2013 especially that of variable lookup \u2013 has a major impact on the performance of the system. The representation described here, although conceptually simple, is not ef ficient and would not ordinarily be used in a production system.15 Exer cise 4.1 1.  Instead of representing a frame as a pair of lists, we can represent a frame as a list of bindings, where each binding is a name-value pair. Rewrite the environment operations to use this alternative representation. Exer cise 4.12.   The procedures set-variable-value! , define-variable! , and lookup-variable-value  can be expresse"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6757760d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "d in terms of more abstract procedures for traversing the environment structure. Define abstractionsthat capture the common patterns and redefine the three procedures in terms of these abstractions. Exer cise 4.13.   Scheme allows us to create new bindings for variables by means of define , but provides no way to get rid of bindings. Implement for the evaluator a special form make-unbound!  that removes the binding of a given symbol from the environment in which the make-unbound! expression is evaluated. This problem is not completely specified. For example, should we remove only the binding in the first frame of the environment? Complete the specification and justify any choices you make. 4.1.4  Running the Evaluator as a Pr ogram Given the evaluator , we have in our hands a description (expressed in Lisp) of the process by which Lisp expressions are evaluated. One advantage of expressing the evaluator as a program is that we can run the program. This gives us, running within Lisp, a working model of how Lis"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6758784p
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "p itself evaluates expressions. This can serve as a framework for experimenting with evaluation rules, as we shall do later in this chapter . Our evaluator program reduces expressions ultimately to the application of primitive procedures. Therefore, all that we need to run the evaluator is to create a mechanism that calls on the underlying Lisp system to model the application of primitive procedures. There must be a binding for each primitive procedure name, so that when eval  evaluates the operator of an application of a primitive, it will find an object to pass to apply . We thus set up a global environment that associates unique objects with the names of the primitive procedures that can appear in the expressions we will be evaluating. The global environment also includes bindings for the symbols true  and false , so that they can be used as variables in expressions to be evaluated. (define (setup-environment)     (let ((initial-env            (extend-environment (primitive-procedure-names)                "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6759808
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "                (primitive-procedure-objects)                                the-empty-environment)))      (define-variable! 'true true initial-env)       (define-variable! 'false false initial-env)       initial-env))   (define the-global-environment (setup-environment))   It does not matter how we represent the primitive procedure objects, so long as apply  can identify and apply them by using the procedures primitive- procedure?  and apply-primitive-procedure . We have chosen to represent a primitive procedure as a list beginning with the symbol primitive  and containing a procedure in the underlying Lisp that implements that primitive. (define (primitive-procedure? proc)     (tagged-list? proc 'primitive))     (define (primitive-implementation proc) (cadr proc))   Setup-environment  will get the primitive names and implementation procedures from a list:16 (define primitive-procedures     (list (list 'car car)           (list 'cdr cdr)           (list 'cons cons)           (list 'null? null?)           < m"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6760832o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ore primitives >          ))   (define (primitive-procedure-names)     (map car          primitive-procedures))     (define (primitive-procedure-objects)     (map (lambda (proc) (list 'primitive (cadr proc)))          primitive-procedures))   To apply a primitive procedure, we simply apply the implementation procedure to the ar guments, using the underlying Lisp system:17(define (apply-primitive-procedure proc args)     (apply-in-underlying-scheme      (primitive-implementation proc) args))   For convenience in running the metacircular evaluator , we provide a driver loop that models the read-eval-print loop of the underlying Lisp system. It prints a prompt , reads an input expression, evaluates this expression in the global environment, and prints the result. We precede each printed result by an output pr ompt  so as to distinguish the value of the expression from other output that may be printed.18 (define input-prompt \";;; M-Eval input:\")   (define output-prompt \";;; M-Eval value:\")   (define (driver-loop)"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6761856
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "     (prompt-for-input input-prompt)     (let ((input (read)))       (let ((output (eval input the-global-environment)))         (announce-output output-prompt)         (user-print output)))     (driver-loop))   (define (prompt-for-input string)     (newline) (newline) (display string) (newline))     (define (announce-output string)     (newline) (display string) (newline))   We use a special printing procedure, user-print , to avoid printing the environment part of a compound procedure, which may be a very long list (or may even contain cycles). (define (user-print object)     (if (compound-procedure? object)         (display (list 'compound-procedure                        (procedure-parameters object)                        (procedure-body object)                        '<procedure-env>))         (display object)))  Now all we need to do to run the evaluator is to initialize the global environment and start the driver loop. Here is a sample interaction: (define the-global-environment (setup-environment))  "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6762880
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " (driver-loop)   ;;; M-Eval input:   (define (append x y)     (if (null? x)         y        (cons (car x)               (append (cdr x) y))))   ;;; M-Eval value:   ok  ;;; M-Eval input:   (append '(a b c) '(d e f))   ;;; M-Eval value:   (a b c d e f)   Exer cise 4.14.   Eva Lu Ator and Louis Reasoner are each experimenting with the metacircular evaluator . Eva types in the definition of map, and runs some test programs that use it. They work fine. Louis, in contrast, has installed the system version of map as a primitive for the metacircular evaluator . When he tries it, things go terribly wrong. Explain why Louis's map fails even though Eva's works. 4.1.5  Data as Pr ograms In thinking about a Lisp program that evaluates Lisp expressions, an analogy might be helpful. One operational view of the meaning of a program is that a program is a description of an abstract (perhaps infinitely large) machine. For example, consider the familiar program to compute factorials: (define (factorial n)     (if (= n 1)      "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6763904
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "   1        (* (factorial (- n 1)) n)))  We may regard this program as the description of a machine containing parts that decrement, multiply , and test for equality , together with a two- position switch and another factorial machine. (The factorial machine is infinite because it contains another factorial machine within it.) Figure 4.2 is a flow diagram for the factorial machine, showing how the parts are wired together . Figur e 4.2:   The factorial program, viewed as an abstract machine. In a similar way , we can regard the evaluator as a very special machine that takes as input a description of a machine. Given this input, the evaluator configures itself to emulate the machine described. For example, if we feed our evaluator the definition of factorial , as shown in figure 4.3, the evaluator will be able to compute factorials. Figur e 4.3:   The evaluator emulating a factorial machine. From this perspective, our evaluator is seen to be a universal machine . It mimics other machines when these are describ"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6764928e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ed as Lisp programs.19 This is striking. T ry to imagine an analogous evaluator for electrical circuits. Thiswould be a circuit that takes as input a signal encoding the plans for some other circuit, such as a filter . Given this input, the circuit evaluator would then behave like a filter with the same description. Such a universal electrical circuit is almost unimaginably complex. It is remarkable that the program evaluator is a rather simple program.20 Another striking aspect of the evaluator is that it acts as a bridge between the data objects that are manipulated by our programming language and the programming language itself. Imagine that the evaluator program (implemented in Lisp) is running, and that a user is typing expressions to the evaluator and observing the results. From the perspective of the user , an input expression such as (* x x)  is an expression in the programming language, which the evaluator should execute. From the perspective of the evaluator , however , the expression is simply a li"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6765952s
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "st (in this case, a list of three symbols: *, x, and x) that is to be manipulated according to a well- defined set of rules. That the user's programs are the evaluator's data need not be a source of confusion. In fact, it is sometimes convenient to ignore this distinction, and to give the user the ability to explicitly evaluate a data object as a Lisp expression, by making eval  available for use in programs. Many Lisp dialects provide a primitive eval  procedure that takes as ar guments an expression and an environment and evaluates the expression relative to the environment.21 Thus, (eval '(* 5 5) user-initial-environment)   and (eval (cons '* (list 5 5)) user-initial-environment)   will both return 25.22 Exer cise 4.15.   Given a one-ar gument procedure p and an object a, p is said to \u201chalt\u201d on a if evaluating the expression (p a)  returns a value (as opposed to terminating with an error message or running forever). Show that it is impossible to write a procedure halts?  that correctly determines whether p"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6766976
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " halts on a for any procedure p and object a. Use the following reasoning: Ifyou had such a procedure halts? , you could implement the following program: (define (run-forever) (run-forever))     (define (try p)     (if (halts? p p)         (run-forever)         'halted))   Now consider evaluating the expression (try try)  and show that any possible outcome (either halting or running forever) violates the intended behavior of halts? .23 4.1.6  Internal Definitions Our environment model of evaluation and our metacircular evaluator execute definitions in sequence, extending the environment frame one definition at a time. This is particularly convenient for interactive program development, in which the programmer needs to freely mix the application of procedures with the definition of new procedures. However , if we think carefully about the internal definitions used to implement block structure (introduced in section 1.1.8 ), we will find that name-by-name extension of the environment may not be the best way to "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6768000d
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "define local variables. Consider a procedure with internal definitions, such as (define (f x)     (define (even? n)       (if (= n 0)           true           (odd? (- n 1))))     (define (odd? n)       (if (= n 0)           false           (even? (- n 1))))     <rest of body of f>) Our intention here is that the name odd?  in the body of the procedure even? should refer to the procedure odd?  that is defined after even? . The scope of the name odd?  is the entire body of f, not just the portion of the body of f starting at the point where the define  for odd?  occurs. Indeed, when we consider that odd?  is itself defined in terms of even?  \u2013 so that even?  and odd?  are mutually recursive procedures \u2013 we see that the only satisfactory interpretation of the two define s is to regard them as if the names even? and odd?  were being added to the environment simultaneously . More generally , in block structure, the scope of a local name is the entire procedure body in which the define  is evaluated. As it happens"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6769024,
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ", our interpreter will evaluate calls to f correctly , but for an \u201caccidental\u201d reason: Since the definitions of the internal procedures come first, no calls to these procedures will be evaluated until all of them have been defined. Hence, odd?  will have been defined by the time even?  is executed. In fact, our sequential evaluation mechanism will give the same result as a mechanism that directly implements simultaneous definition for any procedure in which the internal definitions come first in a body and evaluation of the value expressions for the defined variables doesn't actually use any of the defined variables. (For an example of a procedure that doesn't obey these restrictions, so that sequential definition isn't equivalent to simultaneous definition, see exercise 4.19.)24 There is, however , a simple way to treat definitions so that internally defined names have truly simultaneous scope \u2013 just create all local variables that will be in the current environment before evaluating any of the value express"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6770048i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ions. One way to do this is by a syntax transformation on lambda expressions. Before evaluating the body of a lambda  expression, we \u201cscan out\u201d and eliminate all the internal definitions in the body . The internally defined variables will be created with a let and then set to their values by assignment. For example, the procedure (lambda < vars>    (define u < e1>)    (define v < e2>)    <e3>)  would be transformed into(lambda < vars>    (let ((u '*unassigned*)           (v '*unassigned*))       (set! u < e1>)      (set! v < e2>)      <e3>))  where *unassigned*  is a special symbol that causes looking up a variable to signal an error if an attempt is made to use the value of the not-yet- assigned variable. An alternative strategy for scanning out internal definitions is shown in exercise 4.18. Unlike the transformation shown above, this enforces the restriction that the defined variables' values can be evaluated without using any of the variables' values.25 Exer cise 4.16.   In this exercise we implement the "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6771072m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "method just described for interpreting internal definitions. We assume that the evaluator supports let (see exercise 4.6). a.  Change lookup-variable-value  (section 4.1.3 ) to signal an error if the value it finds is the symbol *unassigned* . b.  Write a procedure scan-out-defines  that takes a procedure body and returns an equivalent one that has no internal definitions, by making the transformation described above. c.  Install scan-out-defines  in the interpreter , either in make-procedure  or in procedure-body  (see section 4.1.3 ). Which place is better? Why? Exer cise 4.17.   Draw diagrams of the environment in ef fect when evaluating the expression < e3> in the procedure in the text, comparing how this will be structured when definitions are interpreted sequentially with how it will be structured if definitions are scanned out as described. Why is there an extra frame in the transformed program? Explain why this difference in environment structure can never make a dif ference in the behavior of a corre"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6772096c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ct program. Design a way to make the interpreterimplement the \u201csimultaneous\u201d scope rule for internal definitions without constructing the extra frame. Exer cise 4.18.   Consider an alternative strategy for scanning out definitions that translates the example in the text to (lambda < vars>    (let ((u '*unassigned*)           (v '*unassigned*))       (let ((a < e1>)            (b < e2>))        (set! u a)         (set! v b))       <e3>))  Here a and b are meant to represent new variable names, created by the interpreter , that do not appear in the user's program. Consider the solve procedure from section 3.5.4 : (define (solve f y0 dt)     (define y (integral (delay dy) y0 dt))     (define dy (stream-map f y))     y)  Will this procedure work if internal definitions are scanned out as shown in this exercise? What if they are scanned out as shown in the text? Explain. Exer cise 4.19.   Ben Bitdiddle, Alyssa P . Hacker , and Eva Lu Ator are arguing about the desired result of evaluating the expression (let ((a 1"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6773120)
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "))     (define (f x)       (define b (+ a x))       (define a 5)       (+ a b))     (f 10))  Ben asserts that the result should be obtained using the sequential rule for define : b is defined to be 1 1, then a is defined to be 5, so the result is 16. Alyssa objects that mutual recursion requires the simultaneous scope rule for internal procedure definitions, and that it is unreasonable to treat procedure names dif ferently from other names. Thus, she ar gues for the mechanism implemented in exercise 4.16. This would lead to a being unassigned at the time that the value for b is to be computed. Hence, in Alyssa's view the procedure should produce an error . Eva has a third opinion. She says that if the definitions of a and b are truly meant to be simultaneous, then the value 5 for a should be used in evaluating b. Hence, in Eva's view a should be 5, b should be 15, and the result should be 20. Which (if any) of these viewpoints do you support? Can you devise a way to implement internal definitions so that they"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6774144
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " behave as Eva prefers?26 Exer cise 4.20.   Because internal definitions look sequential but are actually simultaneous, some people prefer to avoid them entirely , and use the special form letrec  instead. Letrec  looks like let, so it is not surprising that the variables it binds are bound simultaneously and have the same scope as each other . The sample procedure f above can be written without internal definitions, but with exactly the same meaning, as (define (f x)     (letrec ((even?               (lambda (n)                 (if (= n 0)                     true                     (odd? (- n 1)))))              (odd?               (lambda (n)                 (if (= n 0)                     false                     (even? (- n 1))))))       <rest of body of f>))  Letrec  expressions, which have the form(letrec ((< var1> <exp1>) ... (<varn> <expn>))    <body>)  are a variation on let in which the expressions < expk> that provide the initial values for the variables < vark> are evaluated in an environment t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6775168h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "hat includes all the letrec  bindings. This permits recursion in the bindings, such as the mutual recursion of even?  and odd?  in the example above, or the evaluation of 10 factorial with (letrec ((fact             (lambda (n)               (if (= n 1)                   1                   (* n (fact (- n 1)))))))     (fact 10))   a. Implement letrec  as a derived expression, by transforming a letrec expression into a let expression as shown in the text above or in exercise 4.18. That is, the letrec  variables should be created with a let and then be assigned their values with set! . b. Louis Reasoner is confused by all this fuss about internal definitions. The way he sees it, if you don't like to use define  inside a procedure, you can just use let. Illustrate what is loose about his reasoning by drawing an environment diagram that shows the environment in which the < rest of body of f> is evaluated during evaluation of the expression (f 5) , with f defined as in this exercise. Draw an environment diagram f"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6776192o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "or the same evaluation, but with let in place of letrec  in the definition of f. Exer cise 4.21.   Amazingly , Louis's intuition in exercise 4.20 is correct. It is indeed possible to specify recursive procedures without using letrec  (or even define ), although the method for accomplishing this is much more subtle than Louis imagined. The following expression computes 10 factorial by applying a recursive factorial procedure:27 ((lambda (n)      ((lambda (fact)        (fact fact n))       (lambda (ft k)         (if (= k 1)             1             (* k (ft ft (- k 1)))))))    10)  a. Check (by evaluating the expression) that this really does compute factorials. Devise an analogous expression for computing Fibonacci numbers. b. Consider the following procedure, which includes mutually recursive internal definitions: (define (f x)     (define (even? n)       (if (= n 0)           true           (odd? (- n 1))))     (define (odd? n)       (if (= n 0)           false           (even? (- n 1))))     (even? x))   F"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6777216i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ill in the missing expressions to complete an alternative definition of f, which uses neither internal definitions nor letrec : (define (f x)     ((lambda (even? odd?)        (even? even? odd? x))      (lambda (ev? od? n)        (if (= n 0) true (od? <??> <??> <??>)))      (lambda (ev? od? n)        (if (= n 0) false (ev? <??> <??> <??>)))))   4.1.7  Separating Syntactic Analysis fr om ExecutionThe evaluator implemented above is simple, but it is very inef ficient, because the syntactic analysis of expressions is interleaved with their execution. Thus if a program is executed many times, its syntax is analyzed many times. Consider , for example, evaluating (factorial 4)  using the following definition of factorial : (define (factorial n)     (if (= n 1)         1        (* (factorial (- n 1)) n)))   Each time factorial  is called, the evaluator must determine that the body is an if expression and extract the predicate. Only then can it evaluate the predicate and dispatch on its value. Each time it evaluates t"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6778240h
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "he expression (* (factorial (- n 1)) n) , or the subexpressions (factorial (- n 1)) and (- n 1) , the evaluator must perform the case analysis in eval  to determine that the expression is an application, and must extract its operator and operands. This analysis is expensive. Performing it repeatedly is wasteful. We can transform the evaluator to be significantly more ef ficient by arranging things so that syntactic analysis is performed only once.28 We split eval , which takes an expression and an environment, into two parts. The procedure analyze  takes only the expression. It performs the syntactic analysis and returns a new procedure, the execution pr ocedur e, that encapsulates the work to be done in executing the analyzed expression. The execution procedure takes an environment as its ar gument and completes the evaluation. This saves work because analyze  will be called only once on an expression, while the execution procedure may be called many times. With the separation into analysis and execution, ev"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6779264a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "al  now becomes (define (eval exp env)     ((analyze exp) env))   The result of calling analyze  is the execution procedure to be applied to the environment. The analyze  procedure is the same case analysis asperformed by the original eval  of section 4.1.1 , except that the procedures to which we dispatch perform only analysis, not full evaluation: (define (analyze exp)     (cond ((self-evaluating? exp)            (analyze-self-evaluating exp))           ((quoted? exp) (analyze-quoted exp))           ((variable? exp) (analyze-variable exp))           ((assignment? exp) (analyze-assignment exp))           ((definition? exp) (analyze-definition exp))           ((if? exp) (analyze-if exp))           ((lambda? exp) (analyze-lambda exp))           ((begin? exp) (analyze-sequence (begin-actions exp)))           ((cond? exp) (analyze (cond->if exp)))           ((application? exp) (analyze-application exp))           (else            (error \"Unknown expression type -- ANALYZE\" exp))))   Here is the simplest syntacti"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6780288c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "c analysis procedure, which handles self- evaluating expressions. It returns an execution procedure that ignores its environment ar gument and just returns the expression: (define (analyze-self-evaluating exp)     (lambda (env) exp))   For a quoted expression, we can gain a little ef ficiency by extracting the text of the quotation only once, in the analysis phase, rather than in the execution phase. (define (analyze-quoted exp)     (let ((qval (text-of-quotation exp)))       (lambda (env) qval)))   Looking up a variable value must still be done in the execution phase, since this depends upon knowing the environment.29 (define (analyze-variable exp)     (lambda (env) (lookup-variable-value exp env)))  Analyze-assignment  also must defer actually setting the variable until the execution, when the environment has been supplied. However , the fact that the assignment-value  expression can be analyzed (recursively) during analysis is a major gain in ef ficiency , because the assignment-value expression will now b"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6781312e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e analyzed only once. The same holds true for definitions. (define (analyze-assignment exp)     (let ((var (assignment-variable exp))           (vproc (analyze (assignment-value exp))))       (lambda (env)         (set-variable-value! var (vproc env) env)         'ok)))   (define (analyze-definition exp)     (let ((var (definition-variable exp))           (vproc (analyze (definition-value exp))))       (lambda (env)         (define-variable! var (vproc env) env)         'ok)))   For if expressions, we extract and analyze the predicate, consequent, and alternative at analysis time. (define (analyze-if exp)     (let ((pproc (analyze (if-predicate exp)))           (cproc (analyze (if-consequent exp)))           (aproc (analyze (if-alternative exp))))       (lambda (env)         (if (true? (pproc env))             (cproc env)             (aproc env)))))   Analyzing a lambda  expression also achieves a major gain in ef ficiency: W e analyze the lambda  body only once, even though procedures resulting from evaluati"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6782336o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "on of the lambda  may be applied many times. (define (analyze-lambda exp)     (let ((vars (lambda-parameters exp))          (bproc (analyze-sequence (lambda-body exp))))       (lambda (env) (make-procedure vars bproc env))))   Analysis of a sequence of expressions (as in a begin  or the body of a lambda  expression) is more involved.30 Each expression in the sequence is analyzed, yielding an execution procedure. These execution procedures are combined to produce an execution procedure that takes an environment as argument and sequentially calls each individual execution procedure with the environment as ar gument. (define (analyze-sequence exps)     (define (sequentially proc1 proc2)       (lambda (env) (proc1 env) (proc2 env)))     (define (loop first-proc rest-procs)       (if (null? rest-procs)           first-proc           (loop (sequentially first-proc (car rest-procs))                 (cdr rest-procs))))     (let ((procs (map analyze exps)))       (if (null? procs)           (error \"Empty sequence -- A"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6783360N
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "NALYZE\"))       (loop (car procs) (cdr procs))))   To analyze an application, we analyze the operator and operands and construct an execution procedure that calls the operator execution procedure (to obtain the actual procedure to be applied) and the operand execution procedures (to obtain the actual ar guments). We then pass these to execute- application , which is the analog of apply  in section 4.1.1 . Execute- application  differs from apply  in that the procedure body for a compound procedure has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure for the body on the extended environment. (define (analyze-application exp)     (let ((fproc (analyze (operator exp)))           (aprocs (map analyze (operands exp))))       (lambda (env)         (execute-application (fproc env)                             (map (lambda (aproc) (aproc env))                                   aprocs)))))   (define (execute-application proc args)     (cond ((primitive-pro"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6784384c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cedure? proc)            (apply-primitive-procedure proc args))           ((compound-procedure? proc)            ((procedure-body proc)             (extend-environment (procedure-parameters proc)                                 args                                 (procedure-environment proc))))           (else            (error             \"Unknown procedure type -- EXECUTE-APPLICATION\"             proc))))   Our new evaluator uses the same data structures, syntax procedures, and run-time support procedures as in sections 4.1.2 ,  4.1.3 , and 4.1.4 . Exer cise 4.22.   Extend the evaluator in this section to support the special form let. (See exercise 4.6.) Exer cise 4.23.   Alyssa P . Hacker doesn't understand why analyze- sequence  needs to be so complicated. All the other analysis procedures are straightforward transformations of the corresponding evaluation procedures (or eval  clauses) in section 4.1.1 . She expected analyze-sequence  to look like this: (define (analyze-sequence exps)     (define (execut"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6785408e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e-sequence procs env)       (cond ((null? (cdr procs)) ((car procs) env))             (else ((car procs) env)                   (execute-sequence (cdr procs) env))))     (let ((procs (map analyze exps)))       (if (null? procs)           (error \"Empty sequence -- ANALYZE\"))       (lambda (env) (execute-sequence procs env))))  Eva Lu Ator explains to Alyssa that the version in the text does more of the work of evaluating a sequence at analysis time. Alyssa's sequence- execution procedure, rather than having the calls to the individual execution procedures built in, loops through the procedures in order to call them: In effect, although the individual expressions in the sequence have been analyzed, the sequence itself has not been. Compare the two versions of analyze-sequence . For example, consider the common case (typical of procedure bodies) where the sequence has just one expression. What work will the execution procedure produced by Alyssa's program do? What about the execution procedure produced by the pr"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6786432o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "ogram in the text above? How do the two versions compare for a sequence with two expressions? Exer cise 4.24.   Design and carry out some experiments to compare the speed of the original metacircular evaluator with the version in this section. Use your results to estimate the fraction of time that is spent in analysis versus execution for various procedures. 3 Even so, there will remain important aspects of the evaluation process that are not elucidated by our evaluator . The most important of these are the detailed mechanisms by which procedures call other procedures and return values to their callers. We will address these issues in chapter 5, where we take a closer look at the evaluation process by implementing the evaluator as a simple register machine. 4 If we grant ourselves the ability to apply primitives, then what remains for us to implement in the evaluator? The job of the evaluator is not to specify the primitives of the language, but rather to provide the connective tissue \u2013 the means of combinati"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6787456o
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "on and the means of abstraction \u2013 that binds a collection of primitives to form a language. Specifically: The evaluator enables us to deal with nested expressions. For example, although simply applying primitives would suf fice for evaluating the expression (+ 1 6) , it is not adequate for handling (+ 1 (* 2 3)) . As far as the primitive procedure + is concerned, its ar guments must be numbers, and it would choke if we passed it the expression (* 2 3)  as an ar gument. One important role of the evaluator is to choreograph procedure composition so that (* 2 3)  is reduced to 6 before being passed as an ar gument to +. The evaluator allows us to use variables. For example, the primitive procedure for addition has no way to deal with expressions such as (+ x 1) . We need an evaluator to keep track of variables and obtain their values before invoking the primitive procedures. The evaluator allows us to define compound procedures. This involves keeping track of procedure definitions, knowing how to use these defin"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6788480i
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "itions in evaluating expressions, and providing a mechanism that enables procedures to accept ar guments.The evaluator provides the special forms, which must be evaluated dif ferently from procedure calls. 5 We could have simplified the application?  clause in eval  by using map (and stipulating that operands  returns a list) rather than writing an explicit list-of-values  procedure. We chose not to use map here to emphasize the fact that the evaluator can be implemented without any use of higher - order procedures (and thus could be written in a language that doesn't have higher -order procedures), even though the language that it supports will include higher -order procedures. 6 In this case, the language being implemented and the implementation language are the same. Contemplation of the meaning of true?  here yields expansion of consciousness without the abuse of substance. 7 This implementation of define  ignores a subtle issue in the handling of internal definitions, although it works correctly in most "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6789504c
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "cases. We will see what the problem is and how to solve it in section 4.1.6 . 8 As we said when we introduced define  and set! , these values are implementation-dependent in Scheme \u2013 that is, the implementor can choose what value to return. 9 As mentioned in section 2.3.1 , the evaluator sees a quoted expression as a list beginning with quote , even if the expression is typed with the quotation mark. For example, the expression 'a would be seen by the evaluator as (quote a) . See exercise 2.55. 10 The value of an if expression when the predicate is false and there is no alternative is unspecified in Scheme; we have chosen here to make it false. We will support the use of the variables true  and false  in expressions to be evaluated by binding them in the global environment. See section 4.1.4 . 11 These selectors for a list of expressions \u2013 and the corresponding ones for a list of operands \u2013 are not intended as a data abstraction. They are introduced as mnemonic names for the basic list operations in order to "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6790528m
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "make it easier to understand the explicit-control evaluator in section 5.4. 12 The value of a cond  expression when all the predicates are false and there is no else  clause is unspecified in Scheme; we have chosen here to make it false. 13 Practical Lisp systems provide a mechanism that allows a user to add new derived expressions and specify their implementation as syntactic transformations without modifying the evaluator . Such a user-defined transformation is called a macr o. Although it is easy to add an elementary mechanism for defining macros, the resulting language has subtle name-conflict problems. There has been much research on mechanisms for macro definition that do not cause these dif ficulties. See, for example, Kohlbecker 1986, Clinger and Rees 1991, and Hanson 1991. 14 Frames are not really a data abstraction in the following code: Set-variable-value!  and define- variable!  use set-car!  to directly modify the values in a frame. The purpose of the frame procedures is to make the environment-m"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6791552a
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "anipulation procedures easy to read. 15 The drawback of this representation (as well as the variant in exercise 4.11) is that the evaluator may have to search through many frames in order to find the binding for a given variable. (Such an approach is referred to as deep binding .) One way to avoid this inef ficiency is to make use of a strategy called lexical addr essing , which will be discussed in section 5.5.6 .16 Any procedure defined in the underlying Lisp can be used as a primitive for the metacircular evaluator . The name of a primitive installed in the evaluator need not be the same as the name of its implementation in the underlying Lisp; the names are the same here because the metacircular evaluator implements Scheme itself. Thus, for example, we could put (list 'first car)  or (list 'square (lambda (x) (* x x)))  in the list of primitive-procedures . 17 Apply-in-underlying-scheme  is the apply  procedure we have used in earlier chapters. The metacircular evaluator's apply  procedure (section 4.1.1 "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6792576)
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": ") models the working of this primitive. Having two dif ferent things called apply  leads to a technical problem in running the metacircular evaluator , because defining the metacircular evaluator's apply  will mask the definition of the primitive. One way around this is to rename the metacircular apply  to avoid conflict with the name of the primitive procedure. We have assumed instead that we have saved a reference to the underlying apply  by doing (define apply-in-underlying-scheme apply)   before defining the metacircular apply . This allows us to access the original version of apply  under a different name. 18 The primitive procedure read  waits for input from the user , and returns the next complete expression that is typed. For example, if the user types (+ 23 x) , read  returns a three-element list containing the symbol +, the number 23, and the symbol x. If the user types 'x, read  returns a two- element list containing the symbol quote  and the symbol x. 19 The fact that the machines are described in"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6793600
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " Lisp is inessential. If we give our evaluator a Lisp program that behaves as an evaluator for some other language, say C, the Lisp evaluator will emulate the C evaluator , which in turn can emulate any machine described as a C program. Similarly , writing a Lisp evaluator in C produces a C program that can execute any Lisp program. The deep idea here is that any evaluator can emulate any other . Thus, the notion of \u201cwhat can in principle be computed\u201d (ignoring practicalities of time and memory required) is independent of the language or the computer , and instead reflects an underlying notion of computability . This was first demonstrated in a clear way by Alan M. T uring (1912-1954), whose 1936 paper laid the foundations for theoretical computer science. In the paper , Turing presented a simple computational model \u2013 now known as a Turing machine  \u2013 and ar gued that any \u201cef fective process\u201d can be formulated as a program for such a machine. (This ar gument is known as the Chur ch-Turing thesis .) Turing then"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6794624
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " implemented a universal machine, i.e., a T uring machine that behaves as an evaluator for T uring-machine programs. He used this framework to demonstrate that there are well-posed problems that cannot be computed by Turing machines (see exercise 4.15), and so by implication cannot be formulated as \u201cef fective processes.\u201d Turing went on to make fundamental contributions to practical computer science as well. For example, he invented the idea of structuring programs using general-purpose subroutines. See Hodges 1983 for a biography of Turing. 20 Some people find it counterintuitive that an evaluator , which is implemented by a relatively simple procedure, can emulate programs that are more complex than the evaluator itself. The existence of a universal evaluator machine is a deep and wonderful property of computation. Recursion theory , a branch of mathematical logic, is concerned with logical limits of computation. Douglas Hofstadter's beautiful book G\u00f6del, Escher , Bach  (1979) explores some of these ideas. "}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch67956482
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "21 Warning: This eval  primitive is not identical to the eval  procedure we implemented in section 4.1.1 , because it uses actual  Scheme environments rather than the sample environmentstructures we built in section 4.1.3 . These actual environments cannot be manipulated by the user as ordinary lists; they must be accessed via eval  or other special operations. Similarly , the apply primitive we saw earlier is not identical to the metacircular apply , because it uses actual Scheme procedures rather than the procedure objects we constructed in sections 4.1.3  and 4.1.4 . 22 The MIT  implementation of Scheme includes eval , as well as a symbol user-initial- environment  that is bound to the initial environment in which the user's input expressions are evaluated. 23 Although we stipulated that halts?  is given a procedure object, notice that this reasoning still applies even if halts?  can gain access to the procedure's text and its environment. This is T uring's celebrated Halting Theor em, which gave the first"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6796672
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " clear example of a non-computable  problem, i.e., a well-posed task that cannot be carried out as a computational procedure. 24 Wanting programs to not depend on this evaluation mechanism is the reason for the \u201cmanagement is not responsible\u201d remark in footnote 28 of chapter 1. By insisting that internal definitions come first and do not use each other while the definitions are being evaluated, the IEEE standard for Scheme leaves implementors some choice in the mechanism used to evaluate these definitions. The choice of one evaluation rule rather than another here may seem like a small issue, af fecting only the interpretation of \u201cbadly formed\u201d programs. However , we will see in section 5.5.6  that moving to a model of simultaneous scoping for internal definitions avoids some nasty dif ficulties that would otherwise arise in implementing a compiler . 25 The IEEE standard for Scheme allows for dif ferent implementation strategies by specifying that it is up to the programmer to obey this restriction, not up to"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6797696
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " the implementation to enforce it. Some Scheme implementations, including MIT Scheme, use the transformation shown above. Thus, some programs that don't obey this restriction will in fact run in such implementations. 26 The MIT implementors of Scheme support Alyssa on the following grounds: Eva is in principle correct \u2013 the definitions should be regarded as simultaneous. But it seems dif ficult to implement a general, ef ficient mechanism that does what Eva requires. In the absence of such a mechanism, it is better to generate an error in the dif ficult cases of simultaneous definitions (Alyssa's notion) than to produce an incorrect answer (as Ben would have it). 27 This example illustrates a programming trick for formulating recursive procedures without using define . The most general trick of this sort is the Y operator , which can be used to give a \u201cpure \u03bb- calculus\u201d implementation of recursion. (See Stoy 1977 for details on the lambda calculus, and Gabriel 1988 for an exposition of the Y operator in Schem"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6798720e
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "e.) 28 This technique is an integral part of the compilation process, which we shall discuss in chapter 5. Jonathan Rees wrote a Scheme interpreter like this in about 1982 for the T project (Rees and Adams 1982). Marc Feeley (1986) (see also Feeley and Lapalme 1987) independently invented this technique in his master's thesis. 29 There is, however , an important part of the variable search that can be done as part of the syntactic analysis. As we will show in section 5.5.6 , one can determine the position in the environment structure where the value of the variable will be found, thus obviating the need to scan the environment for the entry that matches the variable. 30 See exercise 4.23 for some insight into the processing of sequences.4.2  Variations on a Scheme \u2013 Lazy Evaluation Now that we have an evaluator expressed as a Lisp program, we can experiment with alternative choices in language design simply by modifying the evaluator . Indeed, new languages are often invented by first writing an evaluator tha"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6799744t
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": "t embeds the new language within an existing high- level language. For example, if we wish to discuss some aspect of a proposed modification to Lisp with another member of the Lisp community , we can supply an evaluator that embodies the change. The recipient can then experiment with the new evaluator and send back comments as further modifications. Not only does the high-level implementation base make it easier to test and debug the evaluator; in addition, the embedding enables the designer to snarf31 features from the underlying language, just as our embedded Lisp evaluator uses primitives and control structure from the underlying Lisp. Only later (if ever) need the designer go to the trouble of building a complete implementation in a low-level language or in hardware. In this section and the next we explore some variations on Scheme that provide significant additional expressive power . 4.2.1  Normal Order and Applicative Order In section 1.1, where we began our discussion of models of evaluation, we noted"}


created_at: 2024-03-15 06:19:17
topic: persistent://default/default/71054ee4-4471-4fe6-a521-830479038f85
id: batch6800768
encoding: FLOAT32
metadata:
{"length": 1024, "chroma:document": " that Scheme is an applicative-or der language, namely , that all the arguments to Scheme procedures are evaluated when the procedure is applied. In contrast, normal-or der languages delay evaluation of procedure arguments until the actual ar gument values are needed. Delaying evaluation of procedure ar guments until the last possible moment (e.g., until they are required by a primitive operation) is called lazy evaluation .32 Consider the procedure (define (try a b)     (if (= a 0) 1 b))   Evaluating (try 0 (/ 1 0))  generates an error in Scheme. With lazy evaluation, there would be no error . Evaluating the expression would return 1, because the ar gument (/ 1 0)  would never be evaluated.An example that exploits lazy evaluation is the definition of a procedure unless (define (unless condition usual-value exceptional-value)     (if condition exceptional-value usual-value))   that can be used in expressions such as (unless (= b 0)           (/ a b)           (begin (display \"exception: returning 0\")         "}


