简体   繁体   中英

Replace element of list at position n by e -Racket

How do i do in Racket a function that replaces the element of a list at the position n by e.

(repl-elem '(a b c d e) 2 d)

should return adcde

In order to replace the element with index 2 in a list with a new element 'A, one can do the following:

#lang racket
(define xs (list 1 2 3 4 5))

(append (take xs 2)
        (list 'A)
        (drop xs (+ 2 1)))

I'll leave it as an exercise to turn this into a function.

To see "the mechanics behind this list-set" one can use 'named let' recursion:

(define (f L n c)
  (let loop ((x 1)
             (ol '()))
    (cond
      [(> x (length L))
       (reverse ol)]
      [(= x n)
       (loop (add1 x) (cons c ol))]
      [else
       (loop (add1 x) (cons (list-ref L (sub1 x)) ol))])))

Testing:

(f '(a b c d e) 2 'd)

Output:

'(a d c d e)

OP can figure out how it is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM