删除方案中的第n个项目 [英] delete every nth item in scheme

查看:62
本文介绍了删除方案中的第n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试递归删除方案中的第n个项目

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

当我打电话时:

    > (ndelete x 5)

输出应为:

(1 2 3 4 6 7 8 15)

(1 2 3 4 6 7 8 15)

但是我得到空白输出:

    > (ndelete x 5)
    > 

推荐答案

(= nth 1)条件下,您跳过了该元素,但没有将nth重置为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.

要解决此问题,您将需要一个内部计数器,该计数器保留一个计数器,同时仍使您保持初始的n.这是我的解决方案(我选择从n开始计数而不是从n开始计数):

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

这篇关于删除方案中的第n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆