delete every nth item in scheme

和自甴很熟 提交于 2019-12-10 12:17:08

问题


Trying to delete every nth item in scheme recursively

    (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)))]
    )))

when i call:

    > (ndelete x 5)

the output should be:

(1 2 3 4 6 7 8 15)

but i get blank output:

    > (ndelete x 5)
    > 

回答1:


At the (= nth 1) condition, you skipped the element but did not reset the nth back up to 5 (or whatever the initial value was). That means it stayed at 1 and skipped every element afterwards.

To solve this, you will need an inner function that keeps a counter, while still letting you hold on to the initial n. Here's my solution (I chose to count up to n rather than down from 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)))))))


来源:https://stackoverflow.com/questions/35365831/delete-every-nth-item-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!