Lecture 25: Transforming into Accumulator Style



  1. MAKEUP: what is backtracking?
    graph, code, what part is backtracking?
    how about making change? finding a route?
    (define (find-route O D graph visited)
      (cond
        ((eq? O D) (list D))
        ((member O visited) #f)
        (else (local ((define route
    		    (try-all-neighbors (neighbors O graph) D graph (cons O visited))))
    	    (cond
    	      ((boolean? route) #f)
    	      (else (cons O route)))))))
    
    (define (try-all-neighbors lo-Os D graph visited)
      (cond
        ((empty? lo-Os) #f)
        (else (local ((define route (find-route (first lo-Os) D graph visited)))
    	    (cond
    	      ((boolean? route) (try-all-neighbors (rest lo-Os) D graph visited))
    	      (else route))))))
    



  2. transform an existing function into accumulator style, exercises
    
    (define (! n)
      (cond
        ((zero? n) 1)
        (else (* n (! (sub1 n))))))
    
    (define (!-A n a)
      (cond
        ((zero? n) a)
        (else (!-A (sub1 n) (* a n)))))
    
    (define (SIGMA alon)
      (cond
        ((empty? alon) 0)
        (else (+ (first alon) (SIGMA (rest alon))))))
    
    (define (SIGMA-A alon a)
      (cond
        ((empty? alon) a)
        (else (SIGMA-A (rest alon) (+ (first alon) a)))))
    
    (define (filter-non-0 alon)
      (cond
        ((empty? alon) empty)
        (else (cond
    	    ((zero? (first alon)) (filter-non-0 (rest alon)))
    	    (else (cons (first alon) (filter-non-0 (rest alon))))))))
    
    (define (filter-non-0-A alon a)
      (cond
        ((empty? alon) a)
        (else (cond
    	    ((zero? (first alon)) (filter-non-0-A (rest alon) a))
    	    (else (filter-non-0-A (rest alon) (cons (first alon) a)))))))
    


  3. use SIGMA-A to compute average, add an accumulator
    (define (SIGMA-A alon sum-so-far num-so-far)
      (cond
        ((empty? alon) (/ sum-so-far num-so-far))
        (else (SIGMA-A (rest alon) (+ (first alon) sum-so-far) (+ 1 num-so-far)))))  
    




Matthias Felleisen This page was generated on Fri Apr 9 09:17:38 CDT 1999.