简体   繁体   English

R中的自引用嵌套函数?

[英]Self-referencing nested functions in R?

So, I'm trying to write a function that builds a large complicated formula recursively.所以,我正在尝试编写一个函数来递归地构建一个大型复杂的公式。 Basically, what I would love to work simply, is the following:基本上,我希望简单地工作如下:

f <- function(x) {
  g <- function(y) y
  for( i in 1:4 ) {
    h <- g
    g <- function(y) h(y)^2
  }
  g(x)
}

Please refrain from laughing at this insane motivation.请不要嘲笑这种疯狂的动机。 Now what I would like to get, is a function that returns ((((x^2)^2)^2)^2), but what actually happens is that my runtime just crashes immediately, probably because there's some sort of call to an unreferenced function or something, since I'm overwriting the expression for g every time (obviously I don't really know how r works in this scenario).现在我想得到的是一个返回 ((((x^2)^2)^2)^2) 的函数,但实际发生的是我的运行时立即崩溃,可能是因为有某种调用到一个未引用的函数或其他东西,因为我每次都覆盖g的表达式(显然我真的不知道 r 在这种情况下是如何工作的)。

How can I achieve this idea of retaining the information from the older g references?我怎样才能实现保留旧g引用中信息的想法?

1) Recursion We can use recursion like this: 1)递归我们可以像这样使用递归:

h1 <- function(f, n) if (n == 1) f else function(x) f(h1(f, n-1)(x))

# test using g from questioun
h1(g, 4)(3)
## [1] 43046721

(((3^2)^2)^2)^2
## [1] 43046721

2) Reduce This uses Reduce to compose a function f with itself iteratively n times. 2)Reduce这使用Reduce与自身迭代n次组合函数f

h2 <- function(f, n) function(y) Reduce(function(x, f) f(x), rep(list(f), n), y)

h2(g, 4)(3)
## [1] 43046721

3) for 3) 对于

h3 <- function(f, n) {
  function(x) {
   for(i in 1:n) x <- f(x)
   x
  }
}

h3(g, 4)(3)
## [1] 43046721

4) Fixed If there are a small fixed number we could just write it out explicitly: 4)固定如果有一个小的固定数字,我们可以明确地写出来:

h4 <- function(x) g(g(g(g(x))))

h4(3)
## [1] 43046721

5) Compose We could slightly simplify any of the above using Compose from the functional package. 5) Compose我们可以使用功能包中的Compose稍微简化上述任何一项。 (The purrr package also has a compose function. Use that if you are already using purrr; otherwise, functional has a smaller footprint.) (purrr 包也有一个compose功能。如果您已经在使用 purrr,请使用它;否则,functional 的占用空间更小。)

library(functional)

h1a <- function(f, n) if (n == 1) f else Compose(f, h(f, n-1))

h2a <- function(f, n) Reduce(Compose, rep(list(f), n))

h2b <- function(f, n) do.call(Compose, rep(list(f), n))

h3a <- function(f, n) {
  for(i in 1:n) ff <- if (i == 1) f else Compose(ff, f)
  ff
}

h4a <- Compose(g, g, g, g)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM