sicp-ex-4.22



<< Previous exercise (4.21) | Index | Next exercise (4.23) >>


meteorgan

  
  
 ;; add this in function analyze  
 ((let? expr) (analyze (let->combination expr))) 

For the sake of completion, adding the let->combination functions (which is already there in exercise 4.6)

  
  
 (define (let? exp) (tagged-list? exp 'let)) 
  
 (define (let-variables exp) 
   (define (internal lis) 
     (if (null? lis) '() 
         (cons (caar lis) (internal (cdr lis))) 
         ) 
     ) 
  
   (internal (cadr exp)) 
   ) 
  
 (define (let-body exp) 
   (cddr exp)) 
  
 (define (let-expressions exp) 
   (define (internal lis) 
     (if (null? lis) '() 
         (cons (cadar lis) (internal (cdr lis)))) 
     ) 
  
   (internal (cadr exp)) 
   ) 
  
 (define (make-lambda-combination lambda-dec expressions) 
   (cons lambda-dec expressions) 
   ) 
  
 (define (let->combination exp) 
   (make-lambda-combination 
    (make-lambda (let-variables exp) (let-body exp)) 
    (let-expressions exp)) 
   ) 
  
 ;; (let->combination '(let ((var1 exp1) (var2 exp2)) (body))) 
 ;; ;Value: ((lambda (var1 var2) (body)) exp1 exp2) 
  


Sphinxsky

  
  
  
  
  
 (define (let? exp-) 
     (tagged-list? exp- 'let-)) 
      
 (define (let-body exp-) 
     (cddr exp-)) 
  
 (define (let-variables exp-) 
     (cadr exp-)) 
  
  
 (define (consortium-variable consortium) 
     (car consortium)) 
 (define (consortium-value consortium) 
     (cadr consortium)) 
 (define (separate variables) 
     (define (iter variables variable value) 
         (if (null? variables) 
             (cons (reverse variable) (reverse value)) 
             (let ((first (car variables))) 
                 (iter 
                     (cdr variables) 
                     (cons (consortium-variable first) variable) 
                     (cons (consortium-value first) value))))) 
     (iter variables '() '())) 
  
 (define (analyze-let exp-) 
     (let* ((vars-vals (separate (let-variables exp-))) 
            (lambda-exp (make-lambda (car vars-vals) (let-body exp-))) 
            (ana-lambda (analyze-lambda lambda-exp)) 
            (args (map analyze (cdr vars-vals)))) 
         (lambda (env) 
             (execute-application 
                 (ana-lambda env) 
                 (map (lambda (arg) (arg env)) args))))) 
  
 ; add in analyze  
 ((let? exp-) (analyze-let exp-))