Re: [R] list of interdependent functions

From: Thomas Petzoldt <thpe_at_hhbio.wasser.tu-dresden.de>
Date: Wed 21 Jun 2006 - 01:04:13 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Jun 21 01:07:41 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 21 Jun 2006 - 02:13:55 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.