Com S 342 meeting -*- Outline -*- * trees, hierarchical structures (2.2.2) "Sequences whose elements can themselves be sequences" ** examples (list (list 1 2) 3 4) ==> ((1 2) 3 4) = (cons (list 1 2) (cons 3 (cons 4 nil))) (list 3 nil (list 2 (list 3) 4) 2) ==> (3 () (2 (3) 4) 2) draw the box and pointer diagram for these, explain how these can be interpreted as trees (list) ==> () (list (list)) ==> (()) ** non-examples (cons 1 2) (cons 3 (cons 1 2)) (cons (cons 1 2) nil) ** grammar Note: (cons x y) is written as (x . y) as data. A list such as (list 3 4 5) is (3 . (4 . (5 . nil))) So the grammar for lists: <(list T)> ::= ( {}* ) is equivalent to <(list T)> ::= () | ( . <(list T)> ) --------------------------------------------------------- Trees of atomic items <(tree T)> ::= ( {<(atomic-expression T)>}* ) <(atomic-expression T)> ::= | <(tree T)> where is required to be atomic and not null. The tree grammar is equivalent to: <(tree T)> ::= () | ( . <(tree T)> ) | ( <(tree T)> . <(tree T)> ) A version of atomic-expression that is too liberal, but useful for programming is: <(atomic-expression T)> ::= () | | ( <(atomic-expression T)> . <(atomic-expression T)> ) --------------------------------------------------------- read these as definitions Q: what outline corresponds to the first grammar? the second? Q: How could we implement this in Java? We can use null? pair? and number? to tell cases apart. write the code for atom? ;;; from "The Little Schemer", by Friedman and Felleisen, ;;; (MIT Press, 1996), p. 10. (define (atom? x) ;; TYPE: (-> (datum) boolean) (and (not (pair? x)) (not (null? x)))) ** example procedures (done both ways): (subst-tree 5 7 nil) ==> nil (subst-tree 5 7 (list 6 7 7 (list (list 3 7)) (list 7) (list))) ==> (6 5 5 ((3 5)) (5) ()) what are the related examples? (see the code in the subst-tree*.scm files in this directory) (count-leaves nil) = 0 (count-leaves (list 1 (list 4 5 2 4) 3)) = 6 what are the related examples? (see the code in the count-leaves*.scm files in this directory) tree-map is an exercise!