Lecture 15 : Introduction to Trees (Ancestor Trees) ;; A ftnode is either ;; - 'unknown or ;; - (make-person string number symbol ftnode ftnode) (define-struct person (name year eye mother father)) ;; Example (define MaryTree (make-person "Mary" 1980 'blue (make-person "Ann" 1960 'green 'unknown (make-person "Fred" 1936 'blue 'unknown 'unknown)) (make-person "Joe" 1960 'blue 'unknown 'unknown))) --------------------------------------------------------------------- [Do this one together with class] ;; in-family? : string ftnode -> boolean ;; determine whether tree contains person with given name ;; test cases (check-expect (in-family? "Mary" MaryTree) true) (define (in-family? name aft) (cond [(symbol? aft) false] [(person? aft) (or (string=? name (person-name aft)) (in-family? name (person-mother aft)) (in-family? name (person-father aft)))])) --------------------------------------------------------------------- [Give to class: Hint: use max to get largest of the numbers you give it] ;;Examples (check-expect (count-gens MaryTree) 3) ;; count-gens : ftnode -> number ;; determine how many generations are in the tree (define (count-gens aft) (cond [(symbol? aft) 0] [(person? aft) (+ 1 (max (count-gens (person-mother aft)) (count-gens (person-father aft))))])) --------------------------------------------------------------------- ;; count-blue-eyed : ftnode -> number ;; determine how many blue-eyed people are in the tree (define (count-blue-eyed aft) (cond [(symbol? aft) 0] [(person? aft) (+ (count (person-eye aft)) (count-blue-eyed (person-mother aft)) (count-blue-eyed (person-father aft)))])) ;; count: symbol -> number ;; consumes a color and produces 1 if the color is 'blue, 0 otherwise (define (count eye) (cond [(symbol=? eye 'blue) 1] [else 0])) --------------------------------------------------------------------- ;; gather-green-eyed : ftnode -> list-of-string ;; return list of names of green-eyed people (define (gather-green-eyed aft) (cond [(symbol? aft) empty] [(person? aft) (append (list-if-green aft) (gather-green-eyed (person-mother aft)) (gather-green-eyed (person-father aft)))])) ;; list-if-green : person -> list-of-string ;; return list of person's name if green-eyed, else return empty (define (list-if-green aper) (cond [(symbol=? 'green (person-eye aper)) (list (person-name aper))] [else empty]))