sicp-ex-2.31



<< Previous exercise (2.30) | Index | Next exercise (2.32) >>


jz

Pretty nice.

  
 (define (tree-map proc tree) 
   (define nil '()) 
   (map (lambda (subtree) 
          (cond ((null? subtree) nil) 
                ((not (pair? subtree)) (proc subtree)) 
                (else (tree-map proc subtree)))) 
        tree)) 
  
 ;; Usage: 
 (define my-tree (list (list 1 2) 3 (list 4 5))) 
 (tree-map square my-tree) 
 (tree-map (lambda (x) (+ x 1)) my-tree) 
  

jwc

my way:

  
 (define (tree-map proc tree) 
   (cond ((null? tree) nil) 
         ((pair? tree)  
          (cons  
           (tree-map proc (car tree))  
           (tree-map proc (cdr tree)))) 
         (else (proc tree)))) 

bishboria

my way. For me this is more succinct than using cond and there's no need to check for nil explicitly (or define it):

  
 (define (tree-map proc tree) 
   (map (lambda (sub-tree) 
          (if (pair? sub-tree) 
            (tree-map proc sub-tree) 
            (proc sub-tree))) 
        tree))