我有两个定义,一个家谱和一个人。
; 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*/]))知道如何递归调用列表其他部分上的函数并添加一个函数吗?
发布于 2014-11-12 22:14:04
您所要求的是使用begin表达式完成的。但你不需要这个。您需要组合两个递归调用的结果。在您的例子中,您需要在每个子调用count-descendants的结果中添加1(当前的人)。函数中的另一个错误是,您对first和rest使用了person-children,但是您的函数不是用来处理人员列表的。当您将其调用为空时,您将得到一个错误,因为您无法获得空的person-children。最后,在一个人没有孩子的情况下,我认为它仍然应该被计算在内,所以我返回1在这种情况下。因此,将所有这些加起来,您必须得到这样的结果:
(define (count-descendants person1)
(cond [(empty? (person-children person1)) 1]
[else (+ 1
(foldl + 0 (map count-descendants (person-children person1))))]))在这里,我使用map来计算person1所有子级的后代,使用foldl来计算结果。
https://stackoverflow.com/questions/26897373
复制相似问题