Re: Passing values by reference
Posted: Mon May 28, 2012 7:30 pm
I'm glad I came across this post. I was trying to figure out why this iterative version of nth wouldn't cause harm to any list you passed in because of the fact that it's popping values off of it. But, if I understand you all correctly, what's really happening is that a COPY of the pointer to the first element of the list is being created, and each pop is modifying that copy to point to the next element in the list, and when the function ends, the pointer is discarded, and the original pointer to foo has never been changed, and still points to the head of the original list. And no cons cells in the list itself were modified, so the whole process was about as destructive to the original list as it would have been IF the list HAD been copied and only the copy modified (though of course that's not what happened). Am I getting this?
Code: Select all
> (defun it-nth (n x) (dotimes (i n (first x)) (pop x)))
IT-NTH
> (setf foo '(a b c d e f))
(A B C D E F)
> (it-nth 4 foo)
E
> foo
(A B C D E F)