我有两个定义,一个家谱和一个人。
; a family-tree is:
; (make-person list-of-family-tree symbol number symbol)
; a person is:
; (define-struct person [children name date eyes])
我需要创建一个“相互递归”函数来计算树中后代的数量(包括人)。但是,如果条件得到满足,我无法弄清楚如何让cond做多件事。
即:
(define (count-descendants person1)
(cond [(empty? (person-children person1)) +0]
[else (count-descendants (first (person-children person1)))/*also +1 here*/
(count-descendants (rest (person-children person1)))/*also +1 here*/]))
任何想法如何递归调用列表其他部分的函数,并添加一个?
答案 0 :(得分:1)
你问的是用begin
表达式完成的。但你不需要这里。你需要
结合2个递归调用的结果。在您的情况下,您需要添加1(当前人)
在每个孩子身上调用count-descendants
的结果。您的功能中的另一个错误是您使用
first
的{{1}}和rest
,但您的功能并非旨在处理人员列表。当你在空的时候调用它时,你会收到一个错误,因为你不能得到person-children
为空。最后,如果一个人没有孩子,我相信它仍然应该被计算在内,所以我在这种情况下返回1。所以加上所有这些,你必须得到这样的结论:
person-children
在这里,我使用(define (count-descendants person1)
(cond [(empty? (person-children person1)) 1]
[else (+ 1
(foldl + 0 (map count-descendants (person-children person1))))]))
来计算person1的所有子项的后代,并使用map
来计算结果。