I’m new to lisp and I have a problem when adding an element to an existing list.
> (setq l '(1 2))
(1 2)
> (append l 3)
(1 2 . 3)
> l
(1 2)
> (append l '(3))
(1 2 3)
> l
(1 2)
> (list l '(3))
((1 2) (3))
> l
(1 2)
> (cons 3 l)
(3 1 2)
> l
(1 2)
> (push 3 l)
(3 1 2)
> l
(3 1 2)
The example above is what I made on commandline. Here only push works. But even push doesn’t add the element when I execute the code that I write in a file (and load it on commandline). My code example is available in another question’s page.
How can I update the original l so that it adds 3 to itself? I tried several other functions (cons, list) but the result was the same/similar – 3 wasn’t added to the original list.
So you are
pushing a value onto a list which is passed as a function parameter? That doesn’t work; push creates a new cons cell, makes it point to the original list, and sets the variable to refer to the new cons cell. Unfortunately, setting a function parameter inside the function doesn’t do anything to the variable which was passed originally (from outside the function).When you call a function, the arguments are first evaluated. So if you pass
lto a function, what is actually passed is the value ofl. Nothing which happens inside the function can change whatlrefers to (outside the function).If you want to make something like a function, but which actually changes the values of the variables used as parameters, you need to write a macro. Or, just make the function return the needed value, and set the original variable outside the function, after you get the return value back. Something like this:
(setf l (my-function l))OR, you could use an extra level of indirection: make
lrefer to a “dummy” cons cell, which points to the “real” list, and change thecdrof the “dummy” cons from inside your function. This is poor style, however; it’s usually better to use return values, rather than “returning” data in modified arguments.Note that if you need to return more than one value, that doesn’t mean you need to modify arguments; Common Lisp can return more than one value from a function, using
(values).