Page 2 of 2

Re: Passing values by reference

PostPosted: Mon May 28, 2012 7:30 pm
by leisulin
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)

Re: Passing values by reference

PostPosted: Thu Jun 21, 2012 4:15 pm
by learningcommonlisp
Code: Select all
(setf foo '(a b c))
(setf bar '(d e f))
(setf foo (nconc foo bar))  ; <= correct



Well I think this is wrong nevertheless as a literal list is modified here...

Re: Passing values by reference

PostPosted: Thu Jun 21, 2012 9:47 pm
by gugamilare
learningcommonlisp wrote:Well I think this is wrong nevertheless as a literal list is modified here...


Yes, indeed, that doesn't work.