How to Design Programs: An Introduction to Programming and Computing

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

How to Design Programs: An Introduction to Computing and Programming [Go to first , previous , next page; contents ; index ] Section 32 More Uses of Accumulation This section presents three extended exercises that require the whole range of skills: design by recipe, including generative recursion, and the addition of accumulators for various purposes. 32.1 Extended Exercise: Accumulators on Trees (define-struct child (father mother name date eyes)) A node in a family tree (short: ftn ) is either 1. empty , or 2. (make-child f m na da ec) where f and m are ftn s, na and ec are symbols, and da is a number. ;; all-blue-eyed-ancestors : ftn -> (listof symbol) ;; to construct a list of all blue-eyed ancestors in a-ftree (define (all-blue-eyed-ancestors a-ftree) (cond [(empty? a-ftree) empty] [else (local ((define in-parents (append (all-blue-eyed-ancestors (child-father a-ftree)) (all-blue-eyed-ancestors (child-mother a-ftree))))) (cond [(symbol=? (child-eyes a-ftree) 'blue) (cons (child-name a-ftree) in-parents)] [else in-parents]))])) Figure 91: Collecting family trees with blue-eyed-ancestor? Figure 91 recalls the structure and data definitions of family trees from section 14.1 where we developed the function blue-eyed-ancestor? , which determined whether an ancestor family tree contained a blue-eyed family member. In contrast, all-blue-eyed-ancestors , the function in figure 91 , collects the names of all blue-eyed family in a given family tree. The function's structure is that of a tree-processing function. It has two cases: one for the empty tree and another one for a child node. The latter clause contains two self-references: one per parent. These recursive applications collect (1 of 9) [2/5/2008 4:55:44 PM]
Image of page 1

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