2013-02-25 54 views
0

我是新的方案語法。 這是我一直在研究的項目的最後一部分。 我能夠從給定的Collat​​z序列中找到最大值,但項目的這部分需要從多個Collat​​z序列列表中找到最大長度。 因此,例如給出這個清單:'((110)(10 200)(201 210)(900 1000),輸出應該是這樣的:'(20 125 89 174) 我需要找到數字1到10,然後從10到200 ETS 這裏是我的代碼:從給出的列表中找到Collat​​z序列的最大值

#lang racket 
; Part I 
(define (sequence n) 
    (cond [(= n 1) 
     (list n)] 
    [(even? n) 
    (cons n(sequence(/ n 2)))] 
    [(odd? n) 
    (cons n(sequence (+(* n 3) 1))) ])) 

(sequence 10) 

; Part II 
(define (find-length items) 
    (if (null? items)   
    (list)     
    (cons     
    (length (sequence(car items)))   
    (find-length (rest items)))) 
    ) 
(find-length (list 10 16 22 90 123 169)) 


;Part III 
(define max-in-list (lambda (ls) 
(let ((head (car ls)) (tail (cdr ls))) 
    (if (null? tail) 
    ; list contains only one item, return it 
    head 
    ; else find largest item in tail 
    (let ((max-in-tail (max-in-list tail))) 
     ; return the larger of 'head' and 'max-in-tail' 
     (if (> head max-in-tail) 
     head 
     max-in-tail 
    ) 
    ) 
) 
) 
)) 

(define (find-max i j) 
(if (= i j) 
    (list) 
    (cons 
    (max-in-list (find-length(sequence i))) 
    (find-max (+ 1 i) j) 
)) 
) 
(max-in-list(find-max 1 10)) 

(define (max-length-list items) 
    (if (null? items) 
    (list) 

    (cons 
    (find-max ? ?)) ; how i can call this function ? 
    (max-length-list (?)) ; how i can call this function ? 
))) 

(max-length-list '((1 10) (10 200) (201 210) (900 1000))) 
+0

1.您還沒有告訴我們「Collat​​z」序列的含義。這是一些藝術術語嗎? 2.你的函數沒有契約,所以很難判斷像'max-in-list'這樣的函數是否形成良好。 (例如它是否需要處理空列表?)。但是,當然,3.你沒有寫任何數據定義,所以很難說出你的程序打算操作的數據類是什麼。 (數字列表?數字元組列表?)在你寫出許多合約之前,你需要寫出這些數據定義,我猜測。 – pnkfelix 2013-02-25 09:46:54

回答

0

在傳遞給max-length-list列表中的每個項目是兩個數字和一個nil,如(cons 1 (cons 2 '()))列表
的第一個數字是(car (car items))
第二個是(car (cdr (car items)))

或者,如果您let ((head (car items)),那麼它們是(car head)(car (cdr head))

遞歸調用是微不足道的;你已經處理了第一個元素find-max,現在你只需要處理其餘的元素。你顯然已經知道如何做到這一點,因爲你已經做到了。

+0

謝謝你,我在第二個元素和這(汽車(司機(汽車物品))))搞砸了魔法 – Muhsag 2013-02-25 13:31:49