Skip to content
Prev 358999 / 398503 Next

Functional programming?

Thanks, Roger:

I think Duncan's approach is far more efficient, but I believe the
following replicates your result and may be a bit easier to
understand.

f <- function(u) function(x) u * x^2
g <- function(u) function(x) u * log(x)
set.seed(3)
a <- runif(5)
h <- list()
hit <- list()
h[[1]] <- f(a[1])
hit[[1]] <- f(a[1])
for(i in 2:5) h[[i]] <- eval(bquote(function(x)h[[.(i-1)]](x)*g(a[.(i)])(x)))
x <- 1:99/10
plot(x, h[[1]](x), type = "l")
for(i in 2:5){
  lines(x, h[[i]](x), col = i)
}

This uses recursion to "unwind" h[[i]] each time it's called, ergo
the inefficiency. But in that sense,anyway,  it seems to be more
"functional."

But certainly feel free to ignore.

Cheers,
Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Wed, Mar 2, 2016 at 10:40 AM, Roger Koenker <rkoenker at illinois.edu> wrote: