Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace an item in a list in Common Lisp?

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 sublist up to N and from N to the end of the list and then glue together a new list from the first part, NEW, and the last part using list? Or is there a better way to do this?

like image 737
Paul Wicks Avatar asked Oct 04 '08 20:10

Paul Wicks


3 Answers

(setf (nth N L) NEW)

should do the trick.

like image 65
l0st3d Avatar answered Nov 19 '22 01:11

l0st3d


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)))))
like image 8
hazzen Avatar answered Nov 19 '22 01:11

hazzen


(setf (nth N L) T)

is the clearest, most succinct, and fastest way, if what you want to do is a "destructive" modification, i.e. actually change the existing list. It does not allocate any new memory.

like image 7
Dan Weinreb Avatar answered Nov 18 '22 23:11

Dan Weinreb