This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Calling PUSH in a function

3 posts · 1273 views

Beginner question:

Why doesn't a call to PUSH modify a list passed as a function arg? E.g.
(defun my-push (element lst)
  (push element lst))

(defvar *my-list* nil)

(my-push 'x *my-list*)
This returns (X) but leaves *my-list* unchanged. Why is that?

TIA.

- Phil -

Re: Calling PUSH in a function

Common Lisp does not have lists as an encapsulated data structure. List are constructed as chains of "cons cells", which are essentially pairs, where the first element of the pair holds the value, and the second element holds the tail of the list. What PUSH does is create a new cons cell, set the first value to the given object and the rest to the given list, and then set the binding to this new cons cell. The old list remains unchanged, and any references to it will also remain.

What is your experience with programming in general? In particular, do you understand the difference between values and bindings to them?

Re: Calling PUSH in a function

Thanks. Actually, I my question resulted from a serious brain-fart. I should know better than to program and drink at the same time!

What I was forgetting was not with how PUSH works, but with how function args are passed. This is pretty basic stuff, and I have actually already learned it. However, my thinking got confused for a bit :oops: