Search code examples
lisplet

Change variable defined in let function


Given the following let function:

(let ((foo (list a b c d)))
foo)

How can i modify the list foo?

(let ((foo (list a b c d)))
;some code
foo)

so the returned foo looks like eks: '(some new list) or (a b modified d)

i tried (set) but foo will still return as the original list.


Solution

  • You can use setf to modify a specific element in a list.

    (let ((foo (list 'a 'b 'c 'd)))
      (setf (third foo) 'modified)
      foo)
    

    This will return (a b modified d).

    Or if you want to replace the whole variable, you can assign directly to it with setq:

    (let ((foo (list 'a 'b 'c 'd)))
      (setq foo (list 'some 'new 'list))
      foo)
    

    You can't use set with lexical variables, only special variables.