[R] list of interdependent functions

Thomas Petzoldt thpe at hhbio.wasser.tu-dresden.de
Tue Jun 20 17:04:13 CEST 2006


Martin Morgan wrote:
> Here's another way:
> 
> makeSolver <- function() {
>   f1 <- function(x, K) K - x
>   f2 <- function(x, r, K) r * x * f1(x, K)
>   function() f1(3,4) + f2(1,2,3)
> }
> 
> solverB <- makeSolver()
> 
> solverB()
> 
> makeSolver (implicitly) creates an environment, installs f1 and f2
> into it, and then returns a function that gets assigned to
> solverB. Calling solverB invokes the function in makeSolver, so f1
> and f2 are visible to it. The principle is similar to the 'bank
> account' example in section 10.7 of 'An introduction to R', available
> in the manuals section of cran.

Thank you, and of course, I know this section, but's in fact a little
bit different and uses a list of functions inside a function.

Your solution is obvious at a first look but more tricky in the details.
I wonder if it is possible to access the functions directly, e.g. to
change the body of f1 from "K-x" to, say "1" (switch it off) or to
introduce new functions afterwards (in a straigtforward way avoiding
things like as.list(body) ...

> A down side is that the signature of solverB is not obvious; I'm not
> sure how the documentation facilities (R CMD check) cope with this.

I don't know either and it may seem a little bit ghostly (to some users
;-) that one "copies" R function makeSolver to solverB but in reality
gets a completely different function solverB that in fact uses
*delegation* to access functions f1 and f2 stored in another object.

> Nice poster at useR!

Thanks!

> Martin

Thank you again.

Thomas



More information about the R-help mailing list