Passing values by reference

Discussion of Common Lisp
leisulin
Posts: 1
Joined: Mon May 28, 2012 7:11 pm

Re: Passing values by reference

Post by leisulin » 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)

learningcommonlisp
Posts: 3
Joined: Thu Jun 21, 2012 4:11 pm

Re: Passing values by reference

Post by learningcommonlisp » Thu Jun 21, 2012 4:15 pm

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

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Passing values by reference

Post by gugamilare » Thu Jun 21, 2012 9:47 pm

learningcommonlisp wrote:Well I think this is wrong nevertheless as a literal list is modified here...
Yes, indeed, that doesn't work.

Post Reply