Capture a function from parameter in NESTED function (closure function)

StackOverflow https://stackoverflow.com/questions/23691403

  •  29-07-2023
  •  | 
  •  

Вопрос

Consider a code snippet as follow:

f = function(y) function() y()

f(version)()

Error in f(version)() : could not find function "y"

P.s. It seems that the closure mechanism is quite different from C# Lambda. (?)

Q: How can I capture a function in the closure?

--EDIT--

Scenario: Actually, I would like to write a function factory, and I don't want to add parameter to the nested function.

Like this:

theme_factory = function(theme_fun)
{
  function(device)
  {
    if (!is.onMac()) # Not Mac
    {
      (device == "RStudioGD") %?% theme_fun(): theme_fun(base_family="Heiti")
    }
    else
    {
      theme_fun(base_family="STHeiti")
    }
  }
}

And I defined two customized theme function for ggplot

theme_bw_rmd = theme_factory(theme_bw)

theme_grey_rmd = theme_factory(theme_grey)

Then I use them like:

function(device)
  ggplot(data) + geom_point() something like that + theme_bw_rmd(device)

Thanks.

Это было полезно?

Решение 2

Use eval(func, envir = list(... captured parameters)) or substitute(func, envir) to eval the captured function in a specific environment.

Другие советы

So the problem is with passing parameter? What about something like this:

alwaysaddone <- function(f) function(...) f(...)+1
biggersum <- alwaysaddone(sum)
sum(1:3)
# 6
biggersum(1:3)
# 7

You can use ... to "pass-through" any parameters you like.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top