From Waclaw.Marcin.Kusnierczyk at idi.ntnu.no  Thu Jun  4 00:01:36 2009
From: Waclaw.Marcin.Kusnierczyk at idi.ntnu.no (Wacek Kusnierczyk)
Date: Thu, 04 Jun 2009 00:01:36 +0200
Subject: [Rd] reference counting bug related to break and next in loops
In-Reply-To: <77EB52C6DD32BA4D87471DCD70C8D7000147BB83@NA-PA-VBE03.na.tibco.com>
References: <77EB52C6DD32BA4D87471DCD70C8D7000147B96C@NA-PA-VBE03.na.tibco.com><4A2638BD.6090503@idi.ntnu.no>
	<4A263CFA.70403@idi.ntnu.no>
	<77EB52C6DD32BA4D87471DCD70C8D7000147BB83@NA-PA-VBE03.na.tibco.com>
Message-ID: <4A26F2C0.5030107@idi.ntnu.no>

William Dunlap wrote:
> help('while') says:
>   Usage:
>      for(var in seq) expr
>      while(cond) expr
>      repeat expr
>      break
>      next
>   Value:
>      'for', 'while' and 'repeat' return the value of the last
>      expression evaluated (or 'NULL' if none was), invisibly. 'for'
>      sets 'var' to the last used element of 'seq', or to 'NULL' if it
>      was of length zero.
>
>      'break' and 'next' have value 'NULL', although it would be strange
>      to look for a return value.
>
> Does the 'the last expression evaluated' mean (a) the value from
> evaluating 'expr' the last time it was completely evaluated or
> does it mean (b) the value of the last element of a {} expr that was
> evaluated?  

it's interesting (if not "obvious") that

    i = 1;  y = 1:3
    (while (TRUE) {
       y[i] = 0
       if (i==2) break
       i = i +1
       y + 0 })
    # 0 2 3

does not reflect in the final value the modification made to y in the
second, incomplete iteration, and that

    i = 1;  y = 1:3
    (while (TRUE) {
       y[i] = 0
       if (i==2) break
       i = i +1
       y })
    # 0 0 3

does reflect this modification, yet

    i = 1;  y = 1:3
    (while (TRUE) {
       y[i] = 0
       if (i==2) { y = 1:3; break }
       i = i +1
       y })
    # 0 0 3

makes a copy of y on y = 1:3 and returns the previous value.  again,
this surely has a "straightforward" explanation in the copy-when-scared
mechanics, yet, intuitively, the returned value seems completely out of
place.



> R currently follow interpretation (a), modulo reference
> counting bugs.   My suggestion is to move to interpretation (b),
> so that the fact that break and next return NULL would mean that
> a broken-out-of loop would have value NULL.  (Personally, I'm happy
> with S+'s return value for all loops being NULL in all cases, but
> that might break existing R code.)
>   

i'm truly impressed by s+'s superiority over r.

> Of course, if the reference counting bug can be fixed without degrading
> performance in ordinary situations (does anyone look at the return
> value of a loop, particularly one that is broken out of?), then I'm
> happy
> retaining the current semantics.
>
>   

... with the current lousy documentation improved to match the actual
semantics.

vQ



[Rd] reference counting bug related to break and next in loops
Wacek Kusnierczyk