从给定函数而不是类型化函数在 R 中创建函数工厂



通常在R中,可以通过编写内部"mother"函数的代码来创建函数工厂。但是我想使用一个已经定义的函数作为"母"函数。

我执行以下操作:

#
# typical way of creating a function factory:
#
power_factory <- function(exp) {
function(x) {
x ^ exp
}
}
square <- power_factory(2)
rlang::env_print(square)
#> <environment: 0x7fae8900f3b8>
#> parent: <environment: global>
#> bindings:
#>  * exp: <lazy>
rlang::fn_env(square)$exp
#> [1] 2

#
# but I need to do this from an already defined "mother" function:
#
mother_fun <- function(x) {
x ^ exp
}
power_factory <- function(exp) {
mother_fun
}
square <- power_factory(2)
rlang::env_print(square)
#> <environment: global>
#> parent: <environment: package:rlang>
#> bindings:
#>  * power_factory: <fn>
#>  * mother_fun: <fn>
#>  * .Random.seed: <int>
#>  * square: <fn>
rlang::fn_env(square)$exp
#> NULL

显然,不能像我上面那样直接包含包含母函数(即 mother_fun(的变量,因为变量 exp 不会被绑定。我在元编程的背景下尝试了很多尝试使用表达式和准引号的东西,但没有成功。任何帮助将受到欢迎!谢谢。

你可以这样做(只要函数是闭包而不是基元函数(:

mother_fun <- function(x) {
x ^ exp
}
environment(mother_fun) <- new.env()
environment(mother_fun)$exp <- 2
mother_fun(3)
#[1] 9

最新更新