LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Variable assignment in Lisp. (https://www.linuxquestions.org/questions/programming-9/variable-assignment-in-lisp-796195/)

zaxonus 03-18-2010 01:41 AM

Variable assignment in Lisp.
 
Hi,

I am exploring Clisp and my previous experience is extremely limited in the LISP programming language.

My question is this :
I have a list of numbers defined by say :
(setq mylist '(34 78 5 231 873 76 43 82))

Now, for some reason I need to set the first value to 97 instead of 34
How do I do it the correct LISP way ?

If the value I want to change is the first one I can use something like :
(setq mylist (cons 97 (cdr mylist)))
But how do I do if the value I need to modify is at an arbitrary rank (for example the 39th in a long list) ?

neonsignal 03-18-2010 06:58 AM

If you are happy to destructively modify the list, then you can use setf. For example, the following would set the 39th element to be 97:
Code:

(setf (nth 39 mylist) 97)
A more functional (non-destructive) approach could copy the list recursively, ie:
Code:

(defun nreplace (n l e)
  (cond
    ((= n 0) (cons e (cdr l)))
    (t (cons (car l) (nreplace (- n 1) (cdr l) e)))))
(nreplace 39 mylist 97)

But these are both inefficient; if you need to do this sort of thing often, perhaps you would look at using an array instead of a list.

grail 03-18-2010 07:10 AM

Hey zaxonus

See if this helps:

http://www.lispworks.com/documentati...y/f_replac.htm


All times are GMT -5. The time now is 08:38 PM.