Replace an item in a list in Common Lisp?

前端 未结 10 1716
春和景丽
春和景丽 2021-02-02 10:12

I have a list of things (I\'ll call it L), an index(N) and a new thing(NEW). If I want to replace the thing in L at N with NEW, what is the best way to do this? Should I get the

10条回答
  •  隐瞒了意图╮
    2021-02-02 10:33

    How often are you going to do this; if you really want an array, you should use an array. Otherwise, yes, a function that makes a new list consisting of a copy of the first N elements, the new element, and the tail will be fine. I don't know of a builtin off the top of my head, but I haven't programmed in Lisp in a while.

    Here is a solution in Scheme (because I know that better than Common Lisp, and have an interpreter for checking my work):

    (define (replace-nth list n elem)
      (cond
        ((null? list) ())
        ((eq? n 0) (cons elem (cdr list)))
        (#t (cons (car list) (replace-nth (cdr list) (- n 1) elem)))))
    

提交回复
热议问题