user53073
user53073

Reputation: 51

Deleting n elements of a List

I am writing a program that does some list manipulations in scheme (R5RS). I am trying to create a procedure that will remove n items at index i of a list L. I have written procedures that return all but the first n items in L and a procedure that returns only the first n elements of L. I was able to write a procedure that removes the ith item of L but cannot figure out how to remove n items. This is my remove procedure:

(define (remove L i)
  (cond ((null? L)'())
        ((= i 0) (cdr L))
        (else (cons (car L) (remove (cdr L) (- i 1))))))

`(remove '(1 2 3 4 5) 2)` -> (1 2 4 5)

I am struggling to come up with a procedure (remove L i n) that will do the following:

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

Upvotes: 0

Views: 1160

Answers (1)

simmone
simmone

Reputation: 379

(define (remove L i count)
  (append
   (take L i)
   (if (< (length (list-tail L i)) count)
       (list-tail L i)
       (list-tail L (+ i count)))))

This function's meaning should be this: 1. Take first i items. 2. From i, check if have enough count item if have, ignore them, take the rest. if not, take the rest. Append 1 and 2 steps's items.

Upvotes: 1

Related Questions