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))) --------------------------------------------------------------------- ;; 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)))])) --------------------------------------------------------------------- ;; test (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]))