Replace an item in a list in Common Lisp?

前端 未结 10 1728
春和景丽
春和景丽 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

    quickly you can do it with JS on list-replace

    0 讨论(0)
  • 2021-02-02 10:36
    (setf (nth N L) NEW)
    

    should do the trick.

    0 讨论(0)
  • 2021-02-02 10:38

    The obvious solution is slow and uses memory, as noted by others. If possible, you should try to defer replacing the element(s) until you need to perform another element-wise operation on the list, e.g. (loop for x in list do ...).

    That way, you'll amortize away the consing (memory) and the iteration (cpu).

    0 讨论(0)
  • 2021-02-02 10:47

    I just try to fix hazzen's code:

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

    This code inserted new element in the list. If we want to replace an element:

    (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)))))
    
    > (replace-nth (list 3 2 9 2) 2 8)
    (3 2 8 2)
    

    0 <= n <= length(list) - 1

    0 讨论(0)
提交回复
热议问题