From p.dalgaard at biostat.ku.dk  Sun Dec 19 11:20:23 2004
From: p.dalgaard at biostat.ku.dk (Peter Dalgaard)
Date: Sun Dec 19 11:21:11 2004
Subject: [Rd] value of a loop broken by break
In-Reply-To: <loom.20041219T045943-386@post.gmane.org>
References: <loom.20041219T045943-386@post.gmane.org>
Message-ID: <x2u0qi8u8o.fsf@biostat.ku.dk>

Gabor Grothendieck <ggrothendieck@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).

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)             FAX: (+45) 35327907


[Rd] value of a loop broken by break
Peter Dalgaard