2013-02-24 37 views
1

我正在讀這本書,並且遇到了一個例子。這決定了a-ftree是否包含「眼睛中的藍色」字段的子結構。自引用數據定義

(define-struct child (father mother name date eyes)) 

;; Oldest Generation: 
(define Carl (make-child empty empty 'Carl 1926 'green)) 
(define Bettina (make-child empty empty 'Bettina 1926 'green)) 

;; Middle Generation: 
(define Adam (make-child Carl Bettina 'Adam 1950 'yellow)) 
(define Dave (make-child Carl Bettina 'Dave 1955 'black)) 
(define Eva (make-child Carl Bettina 'Eva 1965 'blue)) 
(define Fred (make-child empty empty 'Fred 1966 'pink)) 

;; Youngest Generation: 
(define Gustav (make-child Fred Eva 'Gustav 1988 'brown)) 


;; blue-eyed-ancestor? : ftn -> boolean 
;; to determine whether a-ftree contains a child 
;; structure with 'blue in the eyes field 
;; version 2: using an or-expression 
(define (blue-eyed-ancestor? a-ftree) 
    (cond 
    [(empty? a-ftree) false] 
    [else (or (symbol=? (child-eyes a-ftree) 'blue) 
       (or (blue-eyed-ancestor? (child-father a-ftree)) 
        (blue-eyed-ancestor? (child-mother a-ftree))))])) 

我想知道你將如何重塑功能,因此可以判斷,ftree是否包含在日期字段出生日期1966年一個孩子?

回答

1

這與您已有的非常相似。這裏的總體思路:

; birth-date? returns true if there's a child in the tree with the given date 
; a-ftree: a family tree 
; date: the date we're looking for 
(define (birth-date? a-ftree date) 
    (cond 
    [<???> <???>]       ; identical base case 
    [else (or (= (<???> a-ftree) <???>) ; if this child has the expected date 
       (or (<???> <???> date)  ; advance the recursion over father 
        (<???> <???> date)))])) ; advance the recursion over mother 

使用方法如下:

(birth-date? Gustav 1966) 
=> #t