2010-10-29 167 views
0

我在課堂上學習計劃,我的教授在8點以後不回答問題,所以我希望你們都能幫助我。基本上我有一個家庭樹類型的東西,我試圖讓一個人的所有祖先,並顯示他們作爲一個字符串,按字母順序排序。排序問題

問題是,由於遞歸,每一代都被合併到他們自己的字符串中,所以不是讓「人一個」「人b」,而是「人一個人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> 

回答

2

的問題,如你所說,是在遞歸情況下,ancestors被返回包含所有祖先,然後不能進行排序的一個字符串因爲它是一回事,而不是幾件事。

您應該修改ancestors,以便不返回單個字符串,而是返回一個字符串列表(即不要在其中調用strlist-to-str)。然後,當它遞歸時,你會得到母親的祖先列表和父親的祖先列表;將這些列表與父母一起添加到一起,並將它們拼合成一個列表。

只有作爲最後一步,在所有遞歸完成之後,您應該致電strlist-to-str將最終名稱列表合併爲單個字符串。

+0

感謝您的快速回復。我意識到遞歸已關閉,只是無法弄清楚如何解決它。管理得到它的工作,感謝您的幫助。再次謝謝你! – 2010-10-29 02:19:56