2016-02-12 44 views
0

刪除每第n個項試圖在方案刪除每第n個項遞歸在方案

(define x '(1 2 3 4 5 6 7 8 15 10)) 

    (define ndelete 
     (lambda (alist nth) ;@params (list to delete items from) (nth intervals to delete items) 
      (cond [(null? alist) alist] ;if null, return empty list 
       [(if (= nth 1) (ndelete (cdr alist) nth))] 
       [else (list (car alist) (ndelete (cdr alist) (- nth 1)))] 
    ))) 

當我打電話:

> (ndelete x 5) 

輸出應爲:

(1 2 3 4 6 7 8 15)

,但我得到空白輸出:

> (ndelete x 5) 
    > 

回答

3

(= nth 1)條件,你跳過了元素,但沒有復位nth回升到5(或任何初始值)。這意味着它保持在1,然後跳過每個元素。

爲了解決這個問題,你需要一個內部函數來保持一個計數器,同時讓你保持原始的n。這裏是我的解決方案(我選擇計數到n而不是從n下降):

(define (ndelete lst n) 
    (let recur ((i 1) 
       (rest lst)) 
    (cond ((null? rest) '()) 
      ((= i n) (recur 1 (cdr rest))) 
      (else (cons (car rest) (recur (+ i 1) (cdr rest)))))))