From Waclaw.Marcin.Kusnierczyk at idi.ntnu.no  Fri Mar 13 11:43:55 2009
From: Waclaw.Marcin.Kusnierczyk at idi.ntnu.no (Wacek Kusnierczyk)
Date: Fri, 13 Mar 2009 11:43:55 +0100
Subject: [Rd] surprising behaviour of names<-
In-Reply-To: <20090313120309.7acb13e5@berwin-nus1>
References: <49B67CB1.8060005@idi.ntnu.no>	<49B682F9.8050307@biostat.ku.dk>	<49B6E6D9.7010809@idi.ntnu.no>	<96A4BB14-D6EA-44B1-B524-6DB139F3A7F8@r-project.org>	<8CCAAAD3-919F-462F-A616-F4FDDB46D975@r-project.org>	<49B81186.4070107@idi.ntnu.no>	<20090312154008.56706f38@berwin-nus1>	<49B8D060.8090206@idi.ntnu.no>	<20090312173231.7a2929df@berwin-nus1>	<49B8DB8F.5030704@idi.ntnu.no>	<20090312213508.719afa73@berwin5>	<49B91A7E.50107@idi.ntnu.no>	<20090312231240.6a061f0b@berwin5>	<49B96FE7.2060705@idi.ntnu.no>
	<20090313120309.7acb13e5@berwin-nus1>
Message-ID: <49BA38EB.3000004@idi.ntnu.no>

Berwin A Turlach wrote:
>
>>     foo = function(arg) arg$foo = foo
>>
>>     e = new.env()
>>     foo(e)
>>     e$foo
>>       
>> are you sure this is pass by value?
>>     
>
> But that is what environments are for, aren't they?  

might be.

> And it is
> documented behaviour.  

sure!

> Read section 2.1.10 ("Environments") in the R
> Language Definition, 

haven't objected to that.  i object to your 'r uses pass by value',
which is only partially correct.

> in particular the last paragraph:
>
>   Unlike most other R objects, environments are not copied when 
>   passed to functions or used in assignments.  Thus, if you assign the
>   same environment to several symbols and change one, the others will
>   change too.  In particular, assigning attributes to an environment can
>   lead to surprises.
>
> [..]
>   
>> and actually, in the example we discuss, 'names<-' does *not* return
>> an updated *tmp*, so there's even less to entertain.  
>>     
>
> How do you know?  Are you sure?  Have you by now studied what goes on
> under the hood?
>   

yes, a bit.  but in this example, it's enough to look into *tmp* to see
that it hasn't got the names added, and since x does have names, names<-
must have returned a copy of *tmp* rather than *tmp* changed:
   
    x = 1
    tmp = x
    x = 'names<-'(tmp, 'foo')
    names(tmp)
    # NULL

you suggested that "One reads the manual, (...) one reflects and
investigates, ..." -- had you done it, you wouldn't have asked the question.



>   
>> for fun and more guesswork, the example could have been:
>>
>>     x = x
>>     x = 'names<-'(x, value=c('a', 'b'))
>>     
>
> But it is manifestly not written that way in the manual; and for good
> reasons since 'names<-' might have side effects which invokes in the
> last line undefined behaviour.  Just as in the equivalent C snippet
> that I mentioned.
>   

i just can't get it why the manual does not manifestly explain what
'names<-' does, and leaves you doing the guesswork you suggest.

vQ



[Rd] surprising behaviour of names<-
Wacek Kusnierczyk