Skip to content
Prev 58462 / 398502 Next

fold right - recursive list (vector) operators

Mads Jeppe Tarp-Johansen <s02mjtj at math.ku.dk> writes:
R does generally encourage abstraction and encapsulation. However
operations like foldr are not common in statistics, I'd say. We have
cumsum and cumprod, which are the same sort of thing, hard coded. It's
easy to implement in R, although possibly not efficiently. Something
like this should work (untested!):

foldr <- function(f, b, x) {
   if (!(n <- length(x))) stop("zero-length x not allowed")
   if (n == 1)
      f(b, x) 
   else
      foldr(f, f(x[n], b), x[-n])
}

or non-recursively (equally untested)

foldr <- function(f, b, x)
{
   if (!(n <- length(x))) stop("zero-length x not allowed")
   while (n) { 
     b <- f(b, x[n])
     n <- n - 1
   }
   b
}