Calling PUSH in a function

Discussion of Common Lisp
Post Reply
psismondi
Posts: 13
Joined: Mon Jan 11, 2010 7:48 pm

Calling PUSH in a function

Post by psismondi » Thu Feb 11, 2010 2:26 pm

Beginner question:

Why doesn't a call to PUSH modify a list passed as a function arg? E.g.

Code: Select all

(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 -

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Calling PUSH in a function

Post by ramarren » Thu Feb 11, 2010 2:37 pm

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?

psismondi
Posts: 13
Joined: Mon Jan 11, 2010 7:48 pm

Re: Calling PUSH in a function

Post by psismondi » Thu Feb 11, 2010 4:26 pm

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:

Post Reply