1

I have a list with me, for example: (B D F)

I want to insert an element at an arbitrary position in the list. For example, if the element is A, I want to insert it before B and if the element C, I want to insert it after B but before D.

Is there any way to insert elements at an arbitrary position in a list in Scheme?

nvlass
  • 665
  • 1
  • 6
  • 15
Rohit Shinde
  • 1,575
  • 5
  • 21
  • 47

1 Answers1

2

It's easy to implement a function for this:

(define (insert-at new k lst)
  (cond ((null? lst)
         (list new))
        ((zero? k)
         (cons new lst))
        (else
         (cons (car lst)
               (insert-at new (sub1 k) (cdr lst))))))

For example:

(insert-at 'B 1 '(A))
=> '(A B)

(insert-at 'A 0 '(B D F))
=> '(A B D F)

(insert-at 'C 2 '(A B D F))
=> '(A B C D F)
Óscar López
  • 232,561
  • 37
  • 312
  • 386