Exercise 4.9. Many languages support a variety of iteration constructs, such as do , for , while , and until . In Scheme, iterative processes can be expressed 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. SOLUTION The code and tests are here . I have implemented the following expressions: do-while do-until for while The 'do-while' construct can be as follows: (do (<one or more statements>) while (condition) ) Use the while block construct to convert it as follows: (begin <statements> (while (condition) <statements> ) ) The 'do-until' construct can be as follows: (do (<one or more statements>) ...
Exercise 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 inefficient, since, as the integers get larger, fewer and fewer of them fit the requirement. As an alternative, let us call the required stream 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...
Exercise 1.22. Most Lisp implementations include a primitive called runtime that returns an integer that specifies the amount of time the system has been running (measured, for example, in microseconds). The following timed-prime-test procedure, when called with an integer n , prints n and checks to see if n is prime. If n is prime, the procedure prints three asterisks followed by the amount of time used in performing the test. (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-time) (if (prime? n) (report-prime (- (runtime) start-time)))) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time)) Using this procedure, ...
Comments
Post a Comment