【问题标题】:delete every nth item in scheme删除方案中的每第 n 个项目
【发布时间】:2016-05-23 19:02:26
【问题描述】:

尝试递归删除方案中的每第 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)
    > 

【问题讨论】:

    标签: list recursion scheme


    【解决方案1】:

    在(= 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)))))))
    

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 2020-01-06
      • 2022-06-24
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多