[Rd] value of a loop broken by break

Gabor Grothendieck ggrothendieck at myway.com
Sun Dec 19 14:26:14 CET 2004


Peter Dalgaard <p.dalgaard <at> biostat.ku.dk> writes:

: 
: Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
: 
: > Should the 'for' loop in the following example not return 3 rather than 2?
: > The Language Manual says that it returns the result of the last evaluated
: > statement and that would be the i before the 'break'.  'repeat' and 'while'
: > have the same behavior.
: > 
: > R> (for(i in 1:10) if (i==3) { i; break } else i)
: > [1] 2
: 
: Hmmm... First, let's look at some variants:
: 
: >  (for(i in 1:10) {pi; if (i==3) { i; break } else 123})
: [1] 123
: 
: Notice that you're getting neither "2" nor "3.1415926", but the "123"
: from the previous iteration. Similarly
: 
: >  (for(i in 1:10) {pi; if (i==3) { i; break }else 123; 456})
: [1] 456
: 
: So you are getting the result of the last _completely_ evaluated
: statement (the enclosing "{"-statement is not completed either).
: 


This seems undesirable behavior to me.  The prototypical example
of this is searching for something and then returning it.  

I think break should be more like return:

  
    for (i in 1:10) if (i==3) { i; break } else i  # returns 3
    for(i in 1:10) if (i==3) break(i) else i  # same



More information about the R-devel mailing list