Difference between Function Factory and closure

Asked

Viewed 161 times

9

In the book Advanced R, to chapters 10 and 11, the author defines Function Factory as:

"a Factory for making new functions"

Translation Google Translate: a factory to do new functions.

And closure as:

"functions returned by Another Function"

Translation Google Translate: functions returned by another function.

So a Function Factory is a function that creates closures? For example:

myfun <- function(x) {
  funs <- c(mean, median, sd, mad, IQR)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

can be considered a Function Factory. Whereas: myfun can be considered a closure, for:

abc <- 1:10

myfun(abc)

I was doubtful about these concepts, which seem to be related.

Supplementary information

1 answer

7


That’s right. Consider the example:

power <- function(exponent) {
  function(x) {
    x ^ exponent
  }
}
square <- power(2)

In this case the function power is a Function Factory and square is a closure. The name closure comes because they include (enclose in English) the environment in which they were created. In this case, the closure square will include the name exponent in your environment and when called will use the value of exponent.

Function factories are legal abstractions, but have little more utility than a function with multiple arguments. Much of the codes with factory functions can be transformed using the function partial purrr, for example:

power <- function(x, exponent) {
  x^exponent
}

square <- purrr::partial(power, exponent = 2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.