[Rd] experiments with slot functions and possible problems NOTE

Thomas Petzoldt Thomas.Petzoldt at tu-dresden.de
Mon Jan 21 14:30:01 CET 2008


Hello,

first of all, thanks to LT for \pkg{codeutils}. I agree that it is
indeed very useful to identify errors and also to encourage re-thinking
past solutions. My problem:

I want to compare different sets of related sub-functions which should
be used alternatively by the same top-level function. Sets of related
functions should be bound together (as lists) and the workspace should
be as clean as possible.

Finally, these functions are to be called by top-level functions that
work with such sets.

What's the best way to do this?

- clutter the workspace with lots of functions?
OR:
- ignore "notes about possible problems"
OR:
- a third way?

Thanks in advance

Thomas P.



An example:

##=============================================================
## 1) One possible "set of functions"
flistA <- list(
   foo = function() {
    1:10
   },
   bar = function() {
     log(foo())
   }
)

## .. we may also have alternative sets,
##    e.g. flistB, flistC, ... etc

## 2) Now we try to construct closures

## 2a) non-nested
makefun1 <- function(flist) {
   with(flist,
     function() foo()
   )
}

## 2b) nested call
makefun2 <- function(flist) {
   with(flist,
     function() bar()
   )
}

## 2c) or use an alternative way with a special function
##  addtoenv, suggested by Gabor Grothendieck some times ago:
addtoenv <- function(L, p = parent.frame()) {
   for(nm in names(L)) {
     assign(nm, L[[nm]], p)
     environment(p[[nm]]) <- p
   }
   L
}

makefun3 <- function(flist) {
   addtoenv(flist)
   function() bar()
}

## 3) now we create the "top-level" functions
##    with one particular "set of functions"
m1 <- makefun1(flistA)
m2 <- makefun2(flistA)
m3 <- makefun3(flistA)

m1()
## this was no problem, trivial

m2()
# Error in bar() : could not find function "foo"

m3()
# works, but even in that case we get problems
# if we do this in a package:

# * checking R code for possible problems ... NOTE
# bar: no visible global function definition for 'foo'

## tested with R version 2.6.1 and
## R 2.7.0 Under development, svn rev. 44061





-- 
Thomas Petzoldt
Technische Universitaet Dresden
Institut fuer Hydrobiologie
01062 Dresden
GERMANY

http://tu-dresden.de/Members/thomas.petzoldt



More information about the R-devel mailing list