2012-11-09 37 views
3

我是計劃的初學者,有人能給我一些關於如何得到的想法,「列表中奇怪的元素?」所以( A B C D G)返回(G C A)。我得到了相反的名單,我現在需要拉其他數字。請幫忙。這是到目前爲止我的代碼:在計劃中獲得一個反向列表「奇怪位置的元素」

(define (list-rev lis) 
    (COND 
    ((NULL? lis) '()) 
    ((LIST? lis) 
    (append (oddrev (CDR lis)) (list (CAR LIS)))) 
    (ELSE (show " USAGE: (oddrev [LIST])")))) 

回答

1

一種方法是讓在與接受兩個參數的函數列表中的單次:列表和一個布爾值。

如果布爾值爲true,那麼您想cons當前元素與其餘處理列表。否則,您可以跳過當前元素並繼續。您需要每次翻轉布爾值,因爲您正在使用其他所有元素。

這有幫助嗎?


下面是代碼,如果你想要的,但我建議你自己先試試吧:

(define l '(A B C D G)) (define (orev lst acc) (if (null? lst) '() (if acc (cons (car lst) (orev (cdr lst) #f)) (orev (cdr lst) #t)))) (write (orev (reverse l) #t))

1

使用蓄能器,用於存儲答案 - 這將產生反向創建列表的效果(不需要使用append!)並生成一個尾遞歸解決方案。因爲這看起來像功課,我給你一些提示,這樣你就可以填寫了空白:

(define (odd-reverse lst acc) 
    (cond ((null? lst)  ; if the list is null 
     <???>)    ; return the empty list 
     (<???>    ; if there's only one element left in the list 
     (cons <???> acc)) ; cons that element with the accumulator 
     (else    ; otherwise advance the recursion 
     (odd-reverse <???> ; advance two positions over the list 
         (cons <???> acc))))) ; cons current element with the acc 

這樣稱呼它:

(odd-reverse '(A B C D G) '()) 
=> '(G C A) 

如果該過程必須接受只有一個參數(列表),編寫另一個調用odd-reverse總是將'()作爲累加器的初始值的過程很簡單。