自引用数据定义

时间:2013-02-24 22:57:48

标签: scheme racket

我正在读这本书,我遇到了一个例子。这确定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))))]))

我想知道你将如何重新制作这个功能,以便它能确定a-ftree是否包含日期字段中出生日期为1966的孩子?

1 个答案:

答案 0 :(得分: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