An elegant way to define a function inside another function

I want to build

f <- function(...) {
   g <- function(x) x ^ 2
   list(...)
}

so that I can use f(g(4))with list(...)and list(...)in list(16).

In general, I will define several temporary functions inside fthat the user can call when called f(...).

I experimented with assignand newenvironment, but only got a little confused. Help with an elegant solution appreciated.

The reason for this is because I want the function in the package Hmisc drawPlotto allow users to specify common function names as input to create a series of graphic elements, and I don’t know if you want to reserve these names of a common type. For example:.

d <- drawPlot(Curve(), Points())   # interactively make a curve and
                                   # a set of points
+4
source share
3

, - , , , :

f <- function(...) {
   g <- function(x) x ^ 2
   list(eval(substitute(...)))
}

f(g(4))
# [[1]]
# [1] 16

, , - :

f <- function(...) {
   g <- function(x) x ^ 2
   h <- function(x) 100*x
   cc <- as.list(substitute(list(...))[-1])
   res <- list()
   for(i in seq_along(cc)) {
       res[[i]] <- eval(cc[[i]])
   }
   res
}
f(g(4), h(5))
# [[1]]
# [1] 16
# 
# [[2]]
# [1] 500
+7

, , :

match.fun_wrapper <- function(...) {
  #   `match.fun` searches in the parent environment of the environment that
  # calls `match.fun`, so this wrapper is a hack to be able to search in
  # the current environment rather than the parent of the current environemnt
  match.fun(...)
}

f <- function(fun, ...) {
  g <- function(x) x ^ 2
  fun <- match.fun_wrapper(substitute(fun))
  fun(...)
}

match.fun, :

f <- function(fun, ...) {
  g <- function(x) x ^ 2
  fun(...)
}
+3

, - :

f <- function(fun, ...) {
    g <- function(x) x ^ 2
    h <- function(x) x ^ 3
    i <- function(x) x ^ 4
    switch(fun,
           'g' = g(...),
           'h' = h(...),
           'i' = i(...))
}

> f('g', 3)
[1] 9
> f('h', 3)
[1] 27
> f('i', 3)
[1] 81

It's unclear why you want it, unless you are trying to encapsulate functions with similar names inside different namespaces and use this as a hacky workaround for the fact that R does not offer fully functional classes. In this case, you can also just use the actual namespaces, i.e. Put your functions inside the package so that they are called package::g(arg)instead f('g', arg).

0
source

Source: https://habr.com/ru/post/1616065/


All Articles