Question

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))))))
Était-ce utile?

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

Autres conseils

If you had two functions:

  1. take-n - which returns as a list the first N elements, and
  2. last-n - which returns as a list the last N elements

then you could write:

(define (insert-at value index list)
  (let ((len (length list)))
    (assert (<= 0 index len))
    (append (take-n index list)
            (list value)
            (last-n (- len index) list))))

(DEFUN INS-ELEM (Nth item list)

(COND

((< Nth 1) (ERROR "Index too small ~A" Nth))

((= Nth 1) (CONS item list))

((ENDP list) (ERROR "Index too big"))

(T (CONS (FIRST list) (INS-ELEM (1- Nth) item(REST list))))))

Then, just call (INS-ELEM 2 'A '(B C D E F)) and view the result for yourself.

Good luck!

#lang racket

(define (insert-at Index item lst)

(cond

[(< Index 1) (error "Index too small: " Index)]

[(= Index 1) (cons item lst)]

[(> Index (length lst)) (error "Index too big: " Index)]

[else (cons (first lst) (insert-at (- Index 1) item (rest lst)))]))

user3660248

Your idea of how to solve this problem seems right and makes sense, but your implementation of it in Racket was not right and I fixed it and now it works :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top