[Rd] Strict seq: a recommendation

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 23 18:11:00 CEST 2006


On Wed, 23 Aug 2006, Thomas Lumley wrote:

> On Wed, 23 Aug 2006, Dominick Samperi wrote:
> 
> > In for loops of the form:
> > for(m in seq(beg,end))
> > ...
> >
> > when beg > end, the default behavior is
> > to decrement, and the action described
> > by ... is executed at least once.
> >
> > On the other hand, if you view this
> > construction as a translation of the C code:
> > for(m = beg; m < end; m++)
> > ...

Your R translates more closely to

  if(beg <= end) for(m = beg; m <= end; m++) {}
  else for(m = beg; m >= end; m--) {}

which is quite a lot different (and the <= vs < mistake seems to explain 
why you think it should not be executed at least once).

> > then the semantics of C/C++ is not
> > respected, 

or to put it another way, your translation was unfaithful to the original 
and

  for(m in beg + seq(length=max(0,end-beg)) )

is a better translation.

> > because the code in ... is
> > not executed when beg > end in
> > the case of C/C++.
> 
> There is another important way in which the C loop is different 
> from the R loop.  If you modify m or end inside the loop the number of 
> iterations of the C loop changes but the number of iterations of the R 
> loop doesn't.  R's for() loop just isn't the same as C's.

I was told only yesterday that one should try to think in the (human) 
language you are going to be writing in.  That I have never needed to 
write such constructs in years of S/R programming suggests to me that
thinking R changes one's perspective over thinking C (or Fortran or ...).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list