Search code examples
listschemecons

Inserting an element at given position in list


I don't know how I can append an element in n position in a list. For example:

(insert-at new k lis)
(insert-at ’N 2 ’(a b c d e f))
=>
’(a b N c d e f)

It is ok?:

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

Solution

  • I'll give you some hints - because this looks like homework, I can't give you a straight answer, and it'll be much more useful if you arrive at the solution by your own means. Fill-in the blanks:

    (define (insert-at new k lis)
      (cond (<???>       ; if the list is empty
             <???>)      ; return a list with the single element `new`
            (<???>       ; if `k` is zero
             <???>)      ; cons `new` with the list
            (else        ; otherwise
             (cons <???> ; cons the lists' current element and
                   (insert-at new <???> <???>))))) ; advance the recursion
    

    Notice that here, "advancing the recursion" means passing the rest of the list and decrementing the k index by one unit. We're done once the k index is zero or the list's end is reached. Don't forget to test the procedure:

    (insert-at 'N 2 '(a b c d e f))
    => '(a b N c d e f)
    
    (insert-at 'N 0 '(a b c))
    => '(N a b c)
    
    (insert-at 'N 3 '(a b c))
    => '(a b c N)