             MASSACHUSETTS INSTITUTE OF TECHNOLOGY
      Department of Electrical Engineering and Computer Science
       6.001 Structure and Interpretation of Computer Programs

                        FINAL EXAMINATION
                          Fall term 1990
                            Open Book

The blue books provided are for SCRAP PAPER ONLY.  You should work out
your answer on scrap paper and then rewrite your final answer NEATLY
in this quiz booklet in the SPACE PROVIDED.  This is the ONLY material
we will look at while grading the exam.

We reserve the right to refuse to grade illegible answers.

Glance through the entire exam before beginning work. There are 7 
problems.

PLEASE WRITE YOUR NAME HERE:

________________________________________________________________

Circle the name of your recitation instructor:


     Joel Moses    Jerry Saltzer    Lynn Stein    Peter Szolovits


Circle the name of your tutor:


  Orca Starbuck     Steven Davis     Mark Day     David Goldstone 

  Tom Simon       Ziggy Blair    Kai-Yee Ho       Barbara Gates 

   Hal Abelson      Eric Grimson       Tom Greene       Joel Moses 

     Jerry Saltzer      Peter Szolovits      Lynn Stein


Before beginning work, please check to see that you have all the pages of 
this exam.  There are 19 pages, numbered at the top.

------------------DO NOT WRITE BELOW THIS LINE-------------------

           1  |   2   |    3   |   4   |   5   |   6   |    7  | TOTAL
SCORE         |       |        |       |       |       |       |  
              |       |        |       |       |       |       |
MAX SCORE  12 |  10   |   15   |   16  |   20  |   12  |   10  |   95
-----------------------------------------------------------------------
GRADER        |       |        |       |       |       |       |
              |       |        |       |       |       |       |
              |       |        |       |       |       |       |



                           Page 1 of 19
PROBLEM 1

Short-answer questions.  Mark the best answer in each case:

(A) In a lexically-scoped language like Scheme, free variables in 
procedures passed as arguments are looked up

___ in the environment from which the procedural argument is called.

___ in the environment where the procedural argument is defined.

___ in the garbage-collected heap.

___ in the register-machine stack.

___ at compile time.


(B) Delayed evaluation is important when using streams to model
processes because it allows one to

___ implement call-by-need thunks without side effects.

___ deal with recursive processes.

___ decouple the order of events in the computer from the apparent
    order of expression evaluation in the procedure.

___ isolate the environment in which the stream is defined from the 
    environment in which it is manipulated.

___ handle side effects conveniently.


(C) The value of inheritance in an object-oriented language is that it 
makes it convenient to define new kinds of objects

___ recursively.

___ that send messages to other objects.

___ at either compile time or run time.

___ as variants of previously defined objects.

___ without modifying the evaluator.



                          Page 2 of 19

(D) Side effects make it difficult to design parallel programs because 

___ the programmer must think carefully about the actual order
    of events.

___ evaluating the operands of a combination in parallel would require 
    more than 7 registers in the parallel machine.

___ garbage collection for a parallel machine is very difficult.

___ the modified state must reside in shared memory.

___ Scheme is lexically scoped.



(E) The explicit-control evaluator uses 7 registers because

___ additional information can be stored in the heap.

___ additional information can be stored on the stack.

___ we need only a single CONTINUE register to implement subroutines.

___ Abelson and Sussman chose to design it like that.

___ implementing tail recursion requires at least this many registers.


(F) For small-memory systems, the main disadvantage of stop-and-copy 
garbage collection over mark-sweep garbage collection is

___ the program must stop in order to garbage collect.

___ you can allocate only half of memory at once.

___ the need to allocate a type tag for each data object.

___ the need to maintain a stack to implement the recursive GC algorithm. 

___ the need for the copy part of the algorithm to scan through all of 
    memory.



                          Page 3 of 19

PROBLEM 2

In what follows, the INSTRUMENT procedure takes as argument a
procedure P of one argument.  INSTRUMENT returns an "instrumented
procedure" that, when given an argument, calls P on that argument,
but also keeps a count of how many times P has been called.  Calling
the instrumented procedure with the special argument COUNT returns
the count.

==>(define i-square (instrument square))

==>(i-square 3)
9

==>(i-square 25)
625

==>(i-square 'count)
2

==>(i-square 10)
100

==>(i-square 'count)
3

The following attempted definition of INSTRUMENT has a bug:

(define (instrument proc)
  (lambda (arg)
    (let ((counter 0))
      (if (eq? arg 'count)
          counter
          (sequence (set! counter (+ 1 counter))
                    (proc arg))))))


                <problem continues on next page>



                          Page 4 of 19

PROBLEM 2 (continued)

(A)  How does this version of INSTRUMENT fail?  Below, we've reprinted
the interaction on the previous page that shows the intended behavior of 
INSTRUMENT.  In the blanks following each of the five calls, show what 
value is actually returned in each case.


==>(define i-square (instrument square))

==>(i-square 3)    
intended value: 9         actual value: _____________

==>(i-square 25)
intended value: 25        actual value: _____________

==>(i-square 'count)
intended value: 2         actual value: ______________

==>(i-square 10)
1intended value: 100      actual value: _____________

==>(i-square 'count)
intended value: 3         actual value: _____________



(B) Correct the bug in the above definition of INSTRUMENT.  (Hint:
Only a small change is required.)



			    Page 5 of 19
PROBLEM 3

Ben Bitdiddle is creating a system to generate sentences in
(pseudo-)English.  He plans to sell it to panicked seniors who have
not yet completed phase 2 of the Writing Requirement.

Ben begins by considering simple sentences that consist of a noun
phrase and a verb phrase.  A noun phrase is defined to be either a
noun, or an adjective followed by a noun phrase.  Similarly, a verb
phrase is either a verb, or a verb followed by an adverb.  Ben sets
up his system by defining four lists, NOUN-LIST, VERB-LIST,
ADVERB-LIST and ADJECTIVE-LIST, which consist respectively of the
nouns, verbs, adverbs and adjectives in the system.

For example,

(define noun-list (list 'dog 'cat 'professor 'student 'rat))

(define verb-list (list 'ran 'ate 'slept 'drank))

(define adjective-list (list 'red 'slow 'dead))

(define adverb-list (list 'quickly 'happily 'well))

(A) Ben also needs procedures that randomly select elements from the
lists.  For example, he needs a procedure called NOUN, of no
arguments, that selects a noun from the noun-list at random.  Using
Scheme's primitive procedure RANDOM, complete the following
procedure.  If you wish, you may use the primitive procedure LENGTH,
which returns the number of items in a list.

(define (noun)
  
_______________________________________________________________________

________________________________________________________________________

________________________________________________________________________

________________________________________________________________________

________________________________________________________________________
  
We will assume that we have similar procedures VERB, ADVERB, and 
ADJECTIVE.

                <problem continues on next page>



			     Page 6 of 19

PROBLEM 3 (continued)

(B) To generate phrases, Ben uses a procedure called EITHER, that
takes as arguments two procedures with no parameters, A and B, and at
random calls either one or the other of them.

(define (either a b)
  (if (= (random 2) 0)
      (a)
      (b)))

Using this procedure Ben can now write a procedure for generating a
verb phrase, which we said consisted either of a verb or of a verb
followed by an adverb.  Using the procedure EITHER, complete the
following definition, so that VERB-PHRASE returns a list of either a
verb or a verb followed by an adverb.

(define (verb-phrase)

  (either ________________________________________________________
	  
	  ___________________________________________________________

	  ___________________________________________________________

	  ___________________________________________________________

	  ___________________________________________________________

	  ___________________________________________________________


                <problem continues on next page>



			     Page 7 of 19

PROBLEM 3 (continued)

(C) The process of generating noun phrases follows a similar pattern.
Remember that a noun phrase is defined as either a noun, or an
adjective followed by a noun phrase.  The procedure NOUN-PHRASE
should return such a phrase as a list.  Complete the following
definition.

(define (noun-phrase)

  (either _______________________________________________________________

          _______________________________________________________________

          _______________________________________________________________

          _______________________________________________________________

          _______________________________________________________________

Using these procedures, Ben is able to use the following procedure

(define (sentence)
  (append (append '(the) (noun-phrase)) (verb-phrase)))

to generate impressive sentences such as

==> (sentence)
(THE CAT SLEPT WELL) 

==> (sentence)
(THE DEAD CAT RAN QUICKLY) 

==> (sentence)
(THE SLOW SLOW SLOW RED CAT ATE) 

==> (sentence)
(THE DEAD PROFESSOR SLEPT HAPPILY) 

                <problem continues on next page>



			     Page 8 of 19

PROBLEM 3 (continued)

(D) Louis Reasoner says he doesn't see why Ben went to such an effort
to make the procedure EITHER behave the way it does.  He claims that
one could just use

(define (either a b)
  (if (= (random 2) 0)
      a
      b))

with the corresponding modifications to VERB-PHRASE and NOUN-PHRASE to
reflect this new definition.  To prove his point, he demonstrates his
new version of the code by successfully running VERB-PHRASE.  Complete
the new definition of VERB-PHRASE below.

(define (verb-phrase)

  (either ________________________________________________________
	  
	  ___________________________________________________________

	  ___________________________________________________________

	  ___________________________________________________________

	  ___________________________________________________________


(E) Ben Bitdiddle claims, however, that this new version of EITHER
will not work for the procedure NOUN-PHRASE.  What will happen if
Louis tries out his new version of NOUN-PHRASE.  Why?



			     Page 9 of 19
PROBLEM 4

An infinite binary tree is a structure that contains a left branch and
a right branch, which are themselves infinite binary trees, together
with a root element.  For example, in the following infinite binary
tree with root 1/2

                                 1/2


                     1/4                     3/4


               1/8        3/8          5/8         7/8


          1/16  3/16  5/16  7/16  9/16  11/16  13/16  15/16



the left branch is the infinite tree whose root is 1/4, and the
right branch is the infinite tree whose root is 3/4.

Alyssa P. Hacker points out that by using DELAY we can represent
infinite binary trees in a manner similar to the way we use streams to
represent infinite sequences.  She proposes a constructor MAKE-TREE
that will construct infinite trees as follows:

(MAKE-TREE ROOT LEFT RIGHT)

will be equivalent to evaluating

(LIST ROOT (DELAY LEFT) (DELAY RIGHT))

There are also three selectors:

(ROOT-NODE TREE) is equivalent to (CAR TREE)

(LEFT-BRANCH TREE) is equivalent to (FORCE (CADR TREE))

(RIGHT-BRANCH TREE) is equivalent to (FORCE (CADDR TREE)).

For example, the infinite binary tree shown above can be
generated by (HALVES 0 1)

where HALVES is defined as:

(define (halves low high)
  (let ((midpoint (/ (+ low high) 2)))
    (make-tree midpoint
               (halves low midpoint)
               (halves midpoint high))))

		   <problem continues on next Page>


			     Page 10 of 19
PROBLEM 4 (continued)

Louis Reasoner decides to implement this idea.  He defines the
procedure MAKE-TREE:

(define (make-tree root left right)
  (list root
        (delay left)
        (delay right)))

(A) What happens when Louis attempts to evaluate the expression
(HALVES 0 1) ?





(B) Alyssa suggests that Louis can fix his problem by defining
MAKE-TREE as a macro, assuming that the evaluator is extended to
include macros as in the exam handout.  What is the appropriate
definition of MAKE-TREE as a macro?

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

		   <problem continues on next page>



			     Page 11 of 19
PROBLEM 4 (continued)

(C) The procedure MAP-TREE is similar to MAP for streams.  Namely, it
takes as arguments a procedure and an infinite binary tree and
returns a new infinite binary tree whose elements are obtained by
applying the procedure to the corresponding elements of the given
tree.  For example

(MAP-TREE (lambda (x) (* x 2))
          (halves 0 1))

returns the infinite tree:

                                  1


                     1/2                     3/2


               1/4        3/4          5/4         7/4



            1/8  3/8   5/8  7/8    9/8  11/8   13/8  15/8




Define the procedure MAP-TREE, using the constructor and
selectors defined above for infinite binary trees.


(define (MAP-TREE proc tree)

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

________________________________________________________________

		   <problem continues on next page>


			    Page 12 of 19
PROBLEM 4 (continued)


(D) Suppose we define the following infinite binary tree:

(define mystery
  (make-tree 1
             (map-tree (lambda (x) (- x 1)) mystery)
             (map-tree square mystery)))

Fill in the boxes to show the elements in the first four levels
of the infinite tree MYSTERY:

                                    

                                              


                                                   



                                            


			    Page 13 of 19


PROBLEM 5

Here is the macro implementation given in the exam handout, with line
numbers added in the EVAL procedure for reference.


1.  (define (eval exp env)
2.    (cond ((self-evaluating? exp) exp)
3.          ((quoted? exp) (text-of-quotation exp))
4.          ((variable? exp) (lookup-variable-value exp env))
5.          ((definition? exp) (eval-definition exp env))
6.          ((MACRO-DEFINITION? EXP) (EVAL-MACRO-DEFINITION EXP ENV))
7.          ((assignment? exp) (eval-assignment exp env))
8.          ((lambda? exp) (make-procedure exp env))
9.          ((conditional? exp) 
10.          (eval-cond (clauses exp) env))
11.         ((application? exp)
12.          (LET ((PROC (EVAL (OPERATOR EXP) ENV)))
13.            (IF (MACRO? PROC)
14.                (EVAL (APPLY (MACRO-EXPANDER PROC) (OPERANDS EXP))
15.                      ENV)
16.                (apply proc 
19.                       (list-of-values (operands exp) env)))))
18.         (else (error "Unknown exp type -- EVAL" exp))))


(define (macro-definition? exp)
  (if (not (atom? exp))
      (eq? (car exp) 'define-macro)))

(define (eval-macro-definition exp env)
  (define-variable! (definition-variable exp)
    (cons 'macro (eval (definition-value exp) env))
    env)
  (definition-variable exp))

(define (macro-expander obj) (cdr obj))

(define (macro? obj)
  (if (not (atom? obj))
      (eq? (car obj) 'macro)))


		   <problem continues on next page>


			    Page 14 of 19
PROBLEM 5 (continued)

(A) Suppose we change line 6 of EVAL to replace ENV by 
THE-GLOBAL-ENVIRONMENT.

What is the best description of how the interpreter will misbehave?
(Check one)

____ When the macro-expander procedure is run, the variable EXP
     will not be bound correctly.

____ Macros will be defined only in the global environment.

____ After the macro has been expanded, evaluating the resulting
     code can reference only variables in the global environment.

____ Procedures called by the expanded macro text will be
     dynamically scoped.

(B) Give the very simplest example you can of a macro definition and
use of that macro that will fail if we make the change described in
part A.  Give a brief description of how the macro will fail.  (That
is, say what error will occur, or what wrong value will be returned.)

EXAMPLE:















DESCRIPTION OF ERROR:













		   <problem continues on next page>


			    Page 15 of 19

PROBLEM 5 (continued) 

(C)  Suppose (without making the change in part A) that we change
line 15 of EVAL to replace ENV by THE-GLOBAL-ENVIRONMENT.

What is the best description of how the interpreter will misbehave?
(Check one)

____ When the macro-expander procedure is run, the variable EXP
     will not be bound correctly.

____ Macros will be defined only in the global environment.

____ After the macro has been expanded, evaluating the resulting
     code can reference only variables in the global environment.

____ Procedures called by the expanded macro text will be
     dynamically scoped.

(D) Give the very simplest example you can of a macro definition and
use of that macro that will fail if we make the change described in
part C.  Give a brief description of how the macro will fail.  (That
is, say what error will occur, or what wrong value will be returned.)

EXAMPLE:















DESCRIPTION OF ERROR:

                          Page 16 of 19
PROBLEM 6
This problem asks you to modify the explicit-control evaluator to
include macros, following the method explained in the handout. We
begin by adding the following clause to the list of branches at
EVAL-DISPATCH:

  (branch (macro-definition? (fetch exp)) ev-macro-definition)

The code for EV-MACRO-DEFINITION is almost identical to the code for
EV-DEFINITION.  Here is EV-DEFINITION, reprinted from page 434 of the
book:

ev-definition
  (assign unev (definition-variable (fetch exp)))
  (save unev)
  (assign exp (definition-value (fetch exp)))
  (save env)
  (save continue)
  (assign continue ev-definition-1)
  (goto eval-dispatch)
ev-definition-1
  (restore continue)
  (restore env)
  (restore unev)
  (perform
   (define-variable! (fetch unev) (fetch val) (fetch env)))
  (assign val (fetch unev)) 
  (goto (fetch continue))

(A) Here is the similar code for EV-MACRO-DEFINITION.  Fill in the two
missing instructions:

ev-macro-definition
  (assign unev (definition-variable (fetch exp)))
  (save unev)
  (assign exp (definition-value (fetch exp)))
  (save env)
  (save continue)

  _______________________________________
  (goto eval-dispatch)
ev-macro-definition-1
  (restore continue)
  (restore env)
  (restore unev)

  _______________________________________
  (perform
   (define-variable! (fetch unev) (fetch val) (fetch env)))
  (assign val (fetch unev)) 
  (goto (fetch continue))

                  <problem continues on next page>

                            Page 17of 19
PROBLEM 6 (continued)

(B) The final change needed to implement macros is at EVAL-ARGS.  Here is
the new code, with lines numbered for reference:

   eval-args
1.   (restore unev)
2.   (restore env)
3.   (assign fun (fetch val))
4.   (branch (macro? (fetch fun)) ev-expand-macro)
5.   (save fun)
6.   (assign argl '())
7.   (goto eval-arg-loop)

   ev-expand-macro
8.   (assign fun (macro-expander (fetch fun)))
9.   (assign argl (reverse (fetch unev)))
10.  (save env)
11.  (assign continue ev-after-expand-macro)
12.  (save continue)
13.  (goto apply-dispatch)

   ev-after-expand-macro
14.  (restore env)
15.  (restore continue)
16.  (assign exp (fetch val))
17.  (goto eval-dispatch)

Using this implementation, suppose we make the following macro
definition:

(define-macro (if pred consequent alternative)
  (list 'cond
        (list pred consequent)
        (list 'else alternative)))

Now suppose we evaluate the expression

==> (if (= 10 20) 1 2)


                   <problem continues on next page>

                           Page 18 of 19

PROBLEM 6 (continued)

When the evaluator reaches ev-expand-macro:

What value is assigned to FUN in line 8?

___ A procedure whose arguments are PRED, CONSEQUENT, and ALTERNATIVE,
    and whose body is the expression
   (LIST 'COND (LIST TRUE 1) (LIST 'ELSE 2)))

___ A procedure whose arguments are PRED, CONSEQUENT, and ALTERNATIVE,
    and whose body is the expression
   (LIST 'COND (LIST PRED CONSEQUENT) (LIST 'ELSE ALTERNATIVE)))

___ A procedure whose arguments are PRED, CONSEQUENT, and ALTERNATIVE,
    and whose body is the expression
   (COND (PRED CONSEQUENT) (ELSE ALTERNATIVE)))

___ A procedure whose arguments are PRED, CONSEQUENT, and ALTERNATIVE,
    and whose body is the expression
   (COND (TRUE 1) (ELSE 2)))

___ The expression (COND (TRUE 1) (ELSE 2)))


What value is assigned to ARGL in line 9?

____ The list (PRED CONSEQUENT ALTERNATIVE)

___  The list (ALTERNATIVE CONSEQUENT PRED)

____ The list ((= 10 20) 1 2)

____ The list (2 1 (= 10 20))

____ The list (TRUE 1 2)

____ The list (2 1 TRUE)





                                   Page 19 of 19
PROBLEM 7

We have numbered the instructions in the following fragment of compiler
object code so that we can refer to them below.

1  (assign val (make-compiled-procedure entry1 (fetch env)))
2  (goto after-lambda0)
   entry1
3  (assign env (compiled-procedure-env (fetch fun)))
4  (assign env (extend-binding-environment '(ans) (fetch argl) (fetch env)))
5  (assign fun (lookup-variable-value 'val (fetch env)))
6  (save fun)
7  (save env)
8  (assign fun (lookup-variable-value 'fun (fetch env)))
9  (assign val (lookup-variable-value 'ans (fetch env)))
10 (assign argl (cons (fetch val) '()))
11 (assign continue after-call2)
12 (save continue)
13 (goto apply-dispatch)
   after-call2
14 (assign argl (cons (fetch val) '()))
15 (restore env)
16 (assign val (lookup-variable-value 'env (fetch env)))
17 (assign argl (cons (fetch val) (fetch argl)))
18 (restore fun)
19 (goto apply-dispatch)
   after-lambda0
20 (perform (define-variable! 'exp (fetch val) (fetch env)))
21 (assign val 'exp)
22 (restore continue)
23 (goto (fetch continue))

(A) Lines 11-13 of the object code constitute a procedure call. What
line will the called procedure return to?
LINE NO:____________________________________________

(B) Line 12 is an isolated (SAVE CONTINUE). The stack discipline requires
that a matching (RESTORE CONTINUE) be executed before any other registers
are restored. Where is the required RESTORE instruction?
WHERE:_________________________________________________

(C) What source-code expression was compiled to produce lines 8-13 of the
object code?
SOURCE CODE:_____________________________________________________________

(D) What source-code expression was compiled to produce lines 5-19 of the 
object code? (Hint: the expression of part C is a
subexpression of this expression.)
SOURCE CODE:___________________________________________________________

(E) What is the overall expression that compiled into the object code 
shown in (lines 1-23)?

SOURCE CODE:_____________________________________________________________

		     THIS IS THE END OF THE EXAM

