{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}


Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
H IERARCHICAL D ATA 8 G EORGE W ANG [email protected] Department of Electrical Engineering and Computer Sciences University of California, Berkeley July 1, 2010 1 Sentences vs. Lists My TA’s have strongly objected to the characterization I gave yesterday and so here’s the final word on that. Lists are NOT sentences, and sentences are NOT lists. We should think about sentences as something completely different from lists. Specifically, we should think about sentences as being an ADT (abstract data type) that is implemented using lists, but doesn’t have to be. We should always respect the abstraction barrier between sentences and lists, by using the sentence constructs ( sentence , every , keep , first , butfirst , etc) only on sentences, and using the list constructs ( list , car , cdr , cons , append , etc) only on lists. 2 Trees from Last Lecture 2.1 Mapping over Trees One thing we might want to do with a tree is create another tree, with the same shape as the original, but with each datum replaced by some function of the original. 2.1.1 Exercise: Generalize! Here’s two examples. Generalize this into a pattern! (define (square-tree tree) (make-tree (square (datum tree)) (map (lambda (tr) (square-tree tr)) (children tree) ))) 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
(define (cube-tree tree) (make-tree (cube (datum tree)) (map (lambda (tr) (cube-tree tr)) (children tree) ))) (define (treemap fn tree) Every tree node consists of a datum and some children. In the new tree, the datum corresponding to this node should be the result of applying fn to the datum of this node in the original tree. What about the children of the new node? There should be the same number of children as there are in the original node, and each new child should be the result of calling treemap on an original child. Since a forest is just a list, we can use map (not treemap !) to generate the new children. This is a remarkably simple and elegant procedure, especially considering the versatility of the data struc- tures it can handle (trees of many different sizes and shapes). 3 Mutual Recursion Pay attention to the strange sort of recursion in this procedure. Treemap does not actually call itself! Treemap calls map , giving it a function that in turn calls treemap . The result is that each call to treemap may give rise to any number of recursive calls, via map : one call for every child of this node.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}