Search code examples
schemeguile

Inserting at arbitrary position in list in Scheme


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?


Solution

  • 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)