# SICP Solutions

### Chapter 5, Computing with Register Machines

#### Exercise 5.36

The current order of evaluation of arguments is right to left.

Why we reverse the operator-codes? Because as explained in the book we use cons which causes the list to be built by adding elements at the front of the list.

To understand intuitively, we do two reverses, one explicit reverse and one which happens because of cons. Thus they cancel out each other so that we can have a list of argl which contains arguments in the same order as they are passed.

But still this does not explain why arguments are evaluated from right to left?

Well, if we see constuct-arglist where while we do cons we also generate instructions to evaluate that argument. And we do cons starting from the first element of the reversed list.

#### Changing the order from left->right to right->left

Changes are marked with ;;;

Note that if we remove the reverse of operator-codes we need to reverse the argl because argl is formed by consing which causes the elements present in argl to be in the reverse order of the operand-codes.

If we don’t reverse argl this will happen:

Suppose we evaluate a call (g (+ 5 2) (- 5 2)). Then argl should be (7 3) but without reverse(and bec of using cons) it will be (3 7). Thus when we call g the arguments passed to it will be in reverse order!

This does not happen in the book’s version because we first reversed (+ 5 2) (- 5 2) to (- 5 2) (+ 5 2) and thus when we build argl because of using cons, (7 3). Thus we get the correct order in which we need to pass this in g.

#### Efficiency

Note that earlier the reverse was in the compiler code. Now the reverse is happening while code is executing! It improves the efficiency of compiler as we need not to do reverse but it does have impact in the efficiency of the code generated! For every procedure application, we have to do reverse!

Well, I was first thinking to reverse the formal arguments thus avoiding the reverse of argl. This can be done for compiled procedures but not for primitive procedures!

#### Output

I checked with the code of ex-5.35(compiling (define (f x) (+ x (g (+ x 2)))):

(reverse instruction generated are marked with ;;;)

Note the difference in the order of arguments for procedure +