繁体   English   中英

球拍方案删除范围内列表的元素

[英]Racket Scheme Deleting elemts of list in range

如何删除范围(a,b)中列表的值? 我试过:

#lang racket

(define (remove L i n)
  (cond ((null? L)
         empty)
        ((> i 0)
         (cons (car L) (remove (cdr L) (sub1 i) n)))
        ((> n 0)
         (remove (cdr L) i (sub1 n)))
        (else
         L)))

但结果是:

(remove '(1 2 3 4 5) 2 4)
'(1 2)
(remove '(1 2 3 4 5 6 7 8 9) 2 5)
'(1 2 8 9)

我想拥有:

(remove '(1 2 3 4 5) 2 4)
'(1 5)

如果您在当前索引中保留另一个参数,我认为这将更容易实现:

(define (remove L index start end)
  (cond ((null? L)
         empty)
        ((and (>= index start) (<= index end))
         (remove (cdr L) (add1 index) start end))
        (else
         (cons (car L) (remove (cdr L) (add1 index) start end)))))

如果您不想添加一个额外的参数,我们总是可以使用命名的let

(define (remove L start end)
  (let loop ((lst L) (index 1))
    (cond ((null? lst)
           empty)
          ((and (>= index start) (<= index end))
           (loop (cdr lst) (add1 index)))
          (else
           (cons (car lst) (loop (cdr lst) (add1 index)))))))

无论哪种方式,它都按预期工作:

(remove '(1 2 3 4 5) 2 4)
=> '(1 5)
(remove '(1 2 3 4 5 6 7 8 9) 2 5)
=> '(1 6 7 8 9)

有两个错误:

  • 您正在使用基于一个的索引,因此第一个条件应该是(> i 1)
  • 由于列表在第一个递归子句中缩小,因此您也需要(sub1 n)
    传递n使其计算要删除的元素数量,而不是停止位置的索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM