从给定函数而不是类型化函数在 R 中创建函数工厂
Create a function factory in R from a given function instead of a typed function
通常在R中可以通过在里面编写"mother"函数的代码来创建一个函数工厂。但是我想使用一个已经定义的函数作为 "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
通常在R中可以通过在里面编写"mother"函数的代码来创建一个函数工厂。但是我想使用一个已经定义的函数作为 "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