我在课堂上学习计划,我的教授在8点之后没有回答问题,所以我希望你们都能帮助我。基本上我有一个家庭树类型的东西,我试图获得一个人的所有祖先,并将它们显示为一个字符串,按字母顺序排序。
问题是,由于递归,每一代都被组合成他们自己的字符串,所以不是让“人”成为“人b”,而是让“人成为一个人”。因此,当我对它们进行排序时,在将它们全部附加到一个字符串之前,它只对该对中的第一个名称进行排序,这意味着第二个名称不会被排序。
很抱歉,如果这听起来令人困惑,我不确定如何自己解释。我希望代码能为我解释大部分内容。
(define-struct person
(
first ; a string: first name
last ; a string: last name
sex ; a symbol: 'male, 'female
eyes ; a symbol: 'blue, 'brown', 'green
hair ; a symbol: 'blonde, 'brown, 'black, 'red
mother; a person: empty if not known
father; a person: empty if not known
born ; a number: year of birth
)
)
(define P-00000 (make-person "Alexandra" "Harper" 'female 'blue 'red empty empty 1897))
(define P-10000 (make-person "Joshua" "Sherman" 'male 'green 'blonde empty empty 1881))
(define P-20000 (make-person "Alexandra" "Hazel" 'female 'brown 'red empty empty 1906))
(define P-30000 (make-person "Christopher" "Abdul" 'male 'brown 'brown empty empty 1904))
(define P-01000 (make-person "Lauren" "Sherman" 'female 'green 'black P-00000 P-10000 1914))
(define P-21000 (make-person "Alexander" "Abdul" 'male 'blue 'brown P-20000 P-30000 1927))
(define P-01100 (make-person "Justine" "Abdul" 'female 'blue 'black P-01000 P-21000 1949))
(define (strlist-to-str StrLst Sep)
(cond
[(empty? StrLst) ""]
[(equal? (first StrLst) "") (strlist-to-str (rest StrLst) Sep)]
[(empty? (rest StrLst)) (first StrLst)]
[else (string-append (first StrLst) Sep (strlist-to-str (rest StrLst) Sep))]
)
)
(define (person-to-lfn ; string
who ; person
)
(cond
[(string? who) who]
[else (string-append (person-last who) "," (person-first who))]
)
)
(define (ancestors ; string
who ; person
)
(cond
[(empty? (person-mother who)) ""]
[else
(strlist-to-str (sort (list (person-to-lfn (person-mother who))
(person-to-lfn (person-father who))
(ancestors (person-mother who))
(ancestors (person-father who))) string<?) " ")]
)
)
(check-expect (ancestors P-01100) "Abdul,Alexander Abdul,Christopher Harper,Alexandra Hazel,Alexandra Sherman,Joshua Sherman,Lauren")
检查失败:
Actual value "Abdul,Alexander Abdul,Christopher Hazel,Alexandra Harper,Alexandra Sherman,Joshua Sherman,Lauren" differs from "Abdul,Alexander Abdul,Christopher Harper,Alexandra Hazel,Alexandra Sherman,Joshua Sherman,Lauren", the expected value.
at line 64, column 0 <code>
答案 0 :(得分:2)
正如你所说,问题是在递归的情况下,ancestors
返回一个包含所有祖先的字符串,然后无法正确排序,因为它是一件事,而不是几件事。
你应该修改ancestors
,这样它就不会返回一个字符串,而是返回一个字符串列表(即不要在其中调用strlist-to-str
)。然后,当它递归时,你会得到母亲祖先的名单和父亲祖先的名单;将这些列表与母亲和父亲一起添加,并将它们压缩成一个列表。
仅作为最后一步,在完成所有递归之后,您应该调用strlist-to-str
将最终名称列表合并为一个字符串。