-3

I want to create a procedure called (splice L i n A) where L is a list, i is an index, n is the number of elements and A is another list. So i is the index at which I would like to insert the list A into the list L and n is the number of elements that I want to remove from my new list starting at index i.

For example: if I run

(splice '(1 2 3 4 5) 2 1 '(a b c))

this will give me

(1 2 a b c 4 5)

so I added the list '(a b c) at index i and I removed 1 element starting at index i which would be the 3.

ceving
  • 21,900
  • 13
  • 104
  • 178
  • 1
    What is your question? What have you tried, and where did you get stuck? Is this homework? – Alexis King Oct 31 '17 at 03:18
  • 1
    I am able to splice the list A into the list L at the index i but I don't know how to remove n number of elements from the original list starting at i – smooky.secrets Oct 31 '17 at 03:55

1 Answers1

1

In this solution split accepts a continuation k, which takes the left and right part of the list L.

(define (split L i k)
  (let loop ((left '())
             (right L)
             (i i))
    (if (> i 0)
        (loop (cons (car right) left)
              (cdr right)
              (- i 1))
        (k (reverse left) right))))

;; (split '(1 2 3 4 5) 2 (lambda x x)) => ((1 2) (3 4 5))

How to removing the initial elements of a list should be obvious.

(define (chop L n)
  (if (> n 0)
      (chop (cdr L) (- n 1))
      L))

;; (chop '(3 4 5) 1) => (4 5)

And how to put the two functions together should be easy, too. split takes the continuation, which gets the left and right part. And the continuation appends to the left part the list A and then the remaining elements of the right part.

(define (splice L i n A)
  (split L i
         (lambda (left right)
           (append left A (chop right n)))))

;; (splice '(1 2 3 4 5) 2 1 '(a b c)) => (1 2 a b c 4 5)
ceving
  • 21,900
  • 13
  • 104
  • 178