【问题标题】:Mutual recursion in racket, making cond do two things球拍中的相互递归,使 cond 做两件事
【发布时间】:2014-11-12 21:55:08
【问题描述】:

我有两个定义,一个是家谱,一个是人。

; 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*/]))

知道如何递归调用列表其他部分的函数并添加一个吗?

【问题讨论】:

    标签: recursion scheme conditional racket mutual-recursion


    【解决方案1】:

    您的要求是通过 begin 表达式完成的。但你在这里不需要。你需要 结合 2 个递归调用的结果。在您的情况下,您需要将 1(当前人)添加到 对每个孩子调用count-descendants 的结果。您的功能中的另一个错误是您使用 firstrest 用于 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 将结果相加。

    【讨论】:

    • 非常感谢!请注意,最后一个“person1”必须是 (person-children person1) 才能工作,因为 count-descendants 只需要一个列表
    • 糟糕。感谢您指出。现在已经修好了。很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2013-09-24
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多